Load friends before modifying them.
[Sone.git] / src / test / java / net / pterodactylus / sone / core / FreenetInterfaceTest.java
1 package net.pterodactylus.sone.core;
2
3 import static freenet.client.InsertException.CANCELLED;
4 import static freenet.client.InsertException.INTERNAL_ERROR;
5 import static freenet.keys.InsertableClientSSK.createRandom;
6 import static freenet.node.RequestStarter.INTERACTIVE_PRIORITY_CLASS;
7 import static freenet.node.RequestStarter.PREFETCH_PRIORITY_CLASS;
8 import static net.pterodactylus.sone.Matchers.delivers;
9 import static net.pterodactylus.sone.TestUtil.setFinalField;
10 import static org.hamcrest.MatcherAssert.assertThat;
11 import static org.hamcrest.Matchers.is;
12 import static org.hamcrest.Matchers.notNullValue;
13 import static org.hamcrest.Matchers.nullValue;
14 import static org.mockito.ArgumentCaptor.forClass;
15 import static org.mockito.Matchers.any;
16 import static org.mockito.Matchers.anyBoolean;
17 import static org.mockito.Matchers.anyShort;
18 import static org.mockito.Matchers.eq;
19 import static org.mockito.Mockito.doNothing;
20 import static org.mockito.Mockito.mock;
21 import static org.mockito.Mockito.never;
22 import static org.mockito.Mockito.times;
23 import static org.mockito.Mockito.verify;
24 import static org.mockito.Mockito.when;
25 import static org.mockito.Mockito.withSettings;
26
27 import java.io.IOException;
28 import java.net.MalformedURLException;
29 import java.util.HashMap;
30
31 import net.pterodactylus.sone.TestUtil;
32 import net.pterodactylus.sone.core.FreenetInterface.Callback;
33 import net.pterodactylus.sone.core.FreenetInterface.Fetched;
34 import net.pterodactylus.sone.core.FreenetInterface.InsertToken;
35 import net.pterodactylus.sone.core.FreenetInterface.InsertTokenSupplier;
36 import net.pterodactylus.sone.core.event.ImageInsertAbortedEvent;
37 import net.pterodactylus.sone.core.event.ImageInsertFailedEvent;
38 import net.pterodactylus.sone.core.event.ImageInsertFinishedEvent;
39 import net.pterodactylus.sone.core.event.ImageInsertStartedEvent;
40 import net.pterodactylus.sone.data.Image;
41 import net.pterodactylus.sone.data.impl.ImageImpl;
42 import net.pterodactylus.sone.data.Sone;
43 import net.pterodactylus.sone.data.TemporaryImage;
44 import net.pterodactylus.sone.freenet.StringBucket;
45
46 import freenet.client.ClientMetadata;
47 import freenet.client.FetchException;
48 import freenet.client.FetchResult;
49 import freenet.client.HighLevelSimpleClient;
50 import freenet.client.InsertBlock;
51 import freenet.client.InsertContext;
52 import freenet.client.InsertException;
53 import freenet.client.async.ClientPutter;
54 import freenet.client.async.USKCallback;
55 import freenet.client.async.USKManager;
56 import freenet.crypt.DummyRandomSource;
57 import freenet.crypt.RandomSource;
58 import freenet.keys.FreenetURI;
59 import freenet.keys.InsertableClientSSK;
60 import freenet.keys.USK;
61 import freenet.node.Node;
62 import freenet.node.NodeClientCore;
63 import freenet.node.RequestClient;
64 import freenet.support.Base64;
65 import freenet.support.api.Bucket;
66
67 import com.google.common.eventbus.EventBus;
68 import org.junit.Before;
69 import org.junit.Test;
70 import org.mockito.ArgumentCaptor;
71
72 /**
73  * Unit test for {@link FreenetInterface}.
74  *
75  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76  */
77 public class FreenetInterfaceTest {
78
79         private final EventBus eventBus = mock(EventBus.class);
80         private final Node node = mock(Node.class);
81         private final NodeClientCore nodeClientCore = mock(NodeClientCore.class);
82         private final HighLevelSimpleClient highLevelSimpleClient = mock(HighLevelSimpleClient.class, withSettings().extraInterfaces(RequestClient.class));
83         private final RandomSource randomSource = new DummyRandomSource();
84         private final USKManager uskManager = mock(USKManager.class);
85         private FreenetInterface freenetInterface;
86         private final Sone sone = mock(Sone.class);
87         private final ArgumentCaptor<USKCallback> callbackCaptor = forClass(USKCallback.class);
88         private final Image image = mock(Image.class);
89         private InsertToken insertToken;
90
91         @Before
92         public void setupFreenetInterface() {
93                 when(nodeClientCore.makeClient(anyShort(), anyBoolean(), anyBoolean())).thenReturn(highLevelSimpleClient);
94                 setFinalField(node, "clientCore", nodeClientCore);
95                 setFinalField(node, "random", randomSource);
96                 setFinalField(nodeClientCore, "uskManager", uskManager);
97                 freenetInterface = new FreenetInterface(eventBus, node);
98                 insertToken = freenetInterface.new InsertToken(image);
99         }
100
101         @Before
102         public void setupSone() {
103                 InsertableClientSSK insertSsk = createRandom(randomSource, "test-0");
104                 when(sone.getId()).thenReturn(Base64.encode(insertSsk.getURI().getRoutingKey()));
105                 when(sone.getRequestUri()).thenReturn(insertSsk.getURI().uskForSSK());
106         }
107
108         @Before
109         public void setupCallbackCaptorAndUskManager() {
110                 doNothing().when(uskManager).subscribe(any(USK.class), callbackCaptor.capture(), anyBoolean(), any(RequestClient.class));
111         }
112
113         @Test
114         public void canFetchUri() throws MalformedURLException, FetchException {
115                 FreenetURI freenetUri = new FreenetURI("KSK@GPLv3.txt");
116                 FetchResult fetchResult = createFetchResult();
117                 when(highLevelSimpleClient.fetch(freenetUri)).thenReturn(fetchResult);
118                 Fetched fetched = freenetInterface.fetchUri(freenetUri);
119                 assertThat(fetched, notNullValue());
120                 assertThat(fetched.getFetchResult(), is(fetchResult));
121                 assertThat(fetched.getFreenetUri(), is(freenetUri));
122         }
123
124         @Test
125         public void fetchFollowsRedirect() throws MalformedURLException, FetchException {
126                 FreenetURI freenetUri = new FreenetURI("KSK@GPLv2.txt");
127                 FreenetURI newFreenetUri = new FreenetURI("KSK@GPLv3.txt");
128                 FetchResult fetchResult = createFetchResult();
129                 FetchException fetchException = new FetchException(FetchException.PERMANENT_REDIRECT, newFreenetUri);
130                 when(highLevelSimpleClient.fetch(freenetUri)).thenThrow(fetchException);
131                 when(highLevelSimpleClient.fetch(newFreenetUri)).thenReturn(fetchResult);
132                 Fetched fetched = freenetInterface.fetchUri(freenetUri);
133                 assertThat(fetched.getFetchResult(), is(fetchResult));
134                 assertThat(fetched.getFreenetUri(), is(newFreenetUri));
135         }
136
137         @Test
138         public void fetchReturnsNullOnFetchExceptions() throws MalformedURLException, FetchException {
139                 FreenetURI freenetUri = new FreenetURI("KSK@GPLv2.txt");
140                 FetchException fetchException = new FetchException(FetchException.ALL_DATA_NOT_FOUND);
141                 when(highLevelSimpleClient.fetch(freenetUri)).thenThrow(fetchException);
142                 Fetched fetched = freenetInterface.fetchUri(freenetUri);
143                 assertThat(fetched, nullValue());
144         }
145
146         private FetchResult createFetchResult() {
147                 ClientMetadata clientMetadata = new ClientMetadata("text/plain");
148                 Bucket bucket = new StringBucket("Some Data.");
149                 return new FetchResult(clientMetadata, bucket);
150         }
151
152         @Test
153         public void insertingAnImage() throws SoneException, InsertException, IOException {
154                 TemporaryImage temporaryImage = new TemporaryImage("image-id");
155                 temporaryImage.setMimeType("image/png");
156                 byte[] imageData = new byte[] { 1, 2, 3, 4 };
157                 temporaryImage.setImageData(imageData);
158                 Image image = new ImageImpl("image-id");
159                 InsertToken insertToken = freenetInterface.new InsertToken(image);
160                 InsertContext insertContext = mock(InsertContext.class);
161                 when(highLevelSimpleClient.getInsertContext(anyBoolean())).thenReturn(insertContext);
162                 ClientPutter clientPutter = mock(ClientPutter.class);
163                 ArgumentCaptor<InsertBlock> insertBlockCaptor = forClass(InsertBlock.class);
164                 when(highLevelSimpleClient.insert(insertBlockCaptor.capture(), eq(false), eq((String) null), eq(false), eq(insertContext), eq(insertToken), anyShort())).thenReturn(clientPutter);
165                 freenetInterface.insertImage(temporaryImage, image, insertToken);
166                 assertThat(insertBlockCaptor.getValue().getData().getInputStream(), delivers(new byte[] { 1, 2, 3, 4 }));
167                 assertThat(TestUtil.<ClientPutter>getPrivateField(insertToken, "clientPutter"), is(clientPutter));
168                 verify(eventBus).post(any(ImageInsertStartedEvent.class));
169         }
170
171         @Test(expected = SoneInsertException.class)
172         public void insertExceptionCausesASoneException() throws InsertException, SoneException, IOException {
173                 TemporaryImage temporaryImage = new TemporaryImage("image-id");
174                 temporaryImage.setMimeType("image/png");
175                 byte[] imageData = new byte[] { 1, 2, 3, 4 };
176                 temporaryImage.setImageData(imageData);
177                 Image image = new ImageImpl("image-id");
178                 InsertToken insertToken = freenetInterface.new InsertToken(image);
179                 InsertContext insertContext = mock(InsertContext.class);
180                 when(highLevelSimpleClient.getInsertContext(anyBoolean())).thenReturn(insertContext);
181                 ArgumentCaptor<InsertBlock> insertBlockCaptor = forClass(InsertBlock.class);
182                 when(highLevelSimpleClient.insert(insertBlockCaptor.capture(), eq(false), eq((String) null), eq(false), eq(insertContext), eq(insertToken), anyShort())).thenThrow(InsertException.class);
183                 freenetInterface.insertImage(temporaryImage, image, insertToken);
184         }
185
186         @Test
187         public void insertingADirectory() throws InsertException, SoneException {
188                 FreenetURI freenetUri = mock(FreenetURI.class);
189                 HashMap<String, Object> manifestEntries = new HashMap<String, Object>();
190                 String defaultFile = "index.html";
191                 FreenetURI resultingUri = mock(FreenetURI.class);
192                 when(highLevelSimpleClient.insertManifest(eq(freenetUri), eq(manifestEntries), eq(defaultFile))).thenReturn(resultingUri);
193                 assertThat(freenetInterface.insertDirectory(freenetUri, manifestEntries, defaultFile), is(resultingUri));
194         }
195
196         @Test(expected = SoneException.class)
197         public void insertExceptionIsForwardedAsSoneException() throws InsertException, SoneException {
198                 when(highLevelSimpleClient.insertManifest(any(FreenetURI.class), any(HashMap.class), any(String.class))).thenThrow(InsertException.class);
199                 freenetInterface.insertDirectory(null, null, null);
200         }
201
202         @Test
203         public void soneWithWrongRequestUriWillNotBeSubscribed() throws MalformedURLException {
204                 when(sone.getRequestUri()).thenReturn(new FreenetURI("KSK@GPLv3.txt"));
205                 freenetInterface.registerUsk(new FreenetURI("KSK@GPLv3.txt"), null);
206                 verify(uskManager, never()).subscribe(any(USK.class), any(USKCallback.class), anyBoolean(), any(RequestClient.class));
207         }
208
209         @Test
210         public void registeringAUsk() {
211                 FreenetURI freenetUri = createRandom(randomSource, "test-0").getURI().uskForSSK();
212                 Callback callback = mock(Callback.class);
213                 freenetInterface.registerUsk(freenetUri, callback);
214                 verify(uskManager).subscribe(any(USK.class), any(USKCallback.class), anyBoolean(), eq((RequestClient) highLevelSimpleClient));
215         }
216
217         @Test
218         public void registeringANonUskKeyWillNotBeSubscribed() throws MalformedURLException {
219                 FreenetURI freenetUri = new FreenetURI("KSK@GPLv3.txt");
220                 Callback callback = mock(Callback.class);
221                 freenetInterface.registerUsk(freenetUri, callback);
222                 verify(uskManager, never()).subscribe(any(USK.class), any(USKCallback.class), anyBoolean(), eq((RequestClient) highLevelSimpleClient));
223         }
224
225         @Test
226         public void registeringAnActiveUskWillSubscribeToItCorrectly() {
227                 FreenetURI freenetUri = createRandom(randomSource, "test-0").getURI().uskForSSK();
228                 final USKCallback uskCallback = mock(USKCallback.class);
229                 freenetInterface.registerActiveUsk(freenetUri, uskCallback);
230                 verify(uskManager).subscribe(any(USK.class), eq(uskCallback), eq(true), any(RequestClient.class));
231         }
232
233         @Test
234         public void registeringAnInactiveUskWillSubscribeToItCorrectly() {
235                 FreenetURI freenetUri = createRandom(randomSource, "test-0").getURI().uskForSSK();
236                 final USKCallback uskCallback = mock(USKCallback.class);
237                 freenetInterface.registerPassiveUsk(freenetUri, uskCallback);
238                 verify(uskManager).subscribe(any(USK.class), eq(uskCallback), eq(false), any(RequestClient.class));
239         }
240
241         @Test
242         public void registeringAnActiveNonUskWillNotSubscribeToAUsk()
243         throws MalformedURLException {
244                 FreenetURI freenetUri = createRandom(randomSource, "test-0").getURI();
245             freenetInterface.registerActiveUsk(freenetUri, null);
246                 verify(uskManager, never()).subscribe(any(USK.class),
247                                 any(USKCallback.class), anyBoolean(),
248                                 eq((RequestClient) highLevelSimpleClient));
249         }
250
251         @Test
252         public void registeringAnInactiveNonUskWillNotSubscribeToAUsk()
253         throws MalformedURLException {
254                 FreenetURI freenetUri = createRandom(randomSource, "test-0").getURI();
255             freenetInterface.registerPassiveUsk(freenetUri, null);
256                 verify(uskManager, never()).subscribe(any(USK.class),
257                                 any(USKCallback.class), anyBoolean(),
258                                 eq((RequestClient) highLevelSimpleClient));
259         }
260
261         @Test
262         public void unregisteringANotRegisteredUskDoesNothing() {
263                 FreenetURI freenetURI = createRandom(randomSource, "test-0").getURI().uskForSSK();
264                 freenetInterface.unregisterUsk(freenetURI);
265                 verify(uskManager, never()).unsubscribe(any(USK.class), any(USKCallback.class));
266         }
267
268         @Test
269         public void unregisteringARegisteredUsk() {
270                 FreenetURI freenetURI = createRandom(randomSource, "test-0").getURI().uskForSSK();
271                 Callback callback = mock(Callback.class);
272                 freenetInterface.registerUsk(freenetURI, callback);
273                 freenetInterface.unregisterUsk(freenetURI);
274                 verify(uskManager).unsubscribe(any(USK.class), any(USKCallback.class));
275         }
276
277         @Test
278         public void unregisteringANotRegisteredSoneDoesNothing() {
279                 freenetInterface.unregisterUsk(sone);
280                 verify(uskManager, never()).unsubscribe(any(USK.class), any(USKCallback.class));
281         }
282
283         @Test
284         public void unregisteringARegisteredSoneUnregistersTheSone()
285         throws MalformedURLException {
286                 freenetInterface.registerActiveUsk(sone.getRequestUri(), mock(USKCallback.class));
287                 freenetInterface.unregisterUsk(sone);
288                 verify(uskManager).unsubscribe(any(USK.class), any(USKCallback.class));
289         }
290
291         @Test
292         public void unregisteringASoneWithAWrongRequestKeyWillNotUnsubscribe() throws MalformedURLException {
293                 when(sone.getRequestUri()).thenReturn(new FreenetURI("KSK@GPLv3.txt"));
294                 freenetInterface.registerUsk(sone.getRequestUri(), null);
295                 freenetInterface.unregisterUsk(sone);
296                 verify(uskManager, never()).unsubscribe(any(USK.class), any(USKCallback.class));
297         }
298
299         @Test
300         public void callbackForNormalUskUsesDifferentPriorities() {
301                 Callback callback = mock(Callback.class);
302                 FreenetURI soneUri = createRandom(randomSource, "test-0").getURI().uskForSSK();
303                 freenetInterface.registerUsk(soneUri, callback);
304                 assertThat(callbackCaptor.getValue().getPollingPriorityNormal(), is(PREFETCH_PRIORITY_CLASS));
305                 assertThat(callbackCaptor.getValue().getPollingPriorityProgress(), is(INTERACTIVE_PRIORITY_CLASS));
306         }
307
308         @Test
309         public void callbackForNormalUskForwardsImportantParameters() throws MalformedURLException {
310                 Callback callback = mock(Callback.class);
311                 FreenetURI uri = createRandom(randomSource, "test-0").getURI().uskForSSK();
312                 freenetInterface.registerUsk(uri, callback);
313                 USK key = mock(USK.class);
314                 when(key.getURI()).thenReturn(uri);
315                 callbackCaptor.getValue().onFoundEdition(3, key, null, null, false, (short) 0, null, true, true);
316                 verify(callback).editionFound(eq(uri), eq(3L), eq(true), eq(true));
317         }
318
319         @Test
320         public void fetchedRetainsUriAndFetchResult() {
321                 FreenetURI freenetUri = mock(FreenetURI.class);
322                 FetchResult fetchResult = mock(FetchResult.class);
323                 Fetched fetched = new Fetched(freenetUri, fetchResult);
324                 assertThat(fetched.getFreenetUri(), is(freenetUri));
325                 assertThat(fetched.getFetchResult(), is(fetchResult));
326         }
327
328         @Test
329         public void cancellingAnInsertWillFireImageInsertAbortedEvent() {
330                 ClientPutter clientPutter = mock(ClientPutter.class);
331                 insertToken.setClientPutter(clientPutter);
332                 ArgumentCaptor<ImageInsertStartedEvent> imageInsertStartedEvent = forClass(ImageInsertStartedEvent.class);
333                 verify(eventBus).post(imageInsertStartedEvent.capture());
334                 assertThat(imageInsertStartedEvent.getValue().image(), is(image));
335                 insertToken.cancel();
336                 ArgumentCaptor<ImageInsertAbortedEvent> imageInsertAbortedEvent = forClass(ImageInsertAbortedEvent.class);
337                 verify(eventBus, times(2)).post(imageInsertAbortedEvent.capture());
338                 assertThat(imageInsertAbortedEvent.getValue().image(), is(image));
339         }
340
341         @Test
342         public void failureWithoutExceptionSendsFailedEvent() {
343                 insertToken.onFailure(null, null, null);
344                 ArgumentCaptor<ImageInsertFailedEvent> imageInsertFailedEvent = forClass(ImageInsertFailedEvent.class);
345                 verify(eventBus).post(imageInsertFailedEvent.capture());
346                 assertThat(imageInsertFailedEvent.getValue().image(), is(image));
347                 assertThat(imageInsertFailedEvent.getValue().cause(), nullValue());
348         }
349
350         @Test
351         public void failureSendsFailedEventWithException() {
352                 InsertException insertException = new InsertException(INTERNAL_ERROR, "Internal error", null);
353                 insertToken.onFailure(insertException, null, null);
354                 ArgumentCaptor<ImageInsertFailedEvent> imageInsertFailedEvent = forClass(ImageInsertFailedEvent.class);
355                 verify(eventBus).post(imageInsertFailedEvent.capture());
356                 assertThat(imageInsertFailedEvent.getValue().image(), is(image));
357                 assertThat(imageInsertFailedEvent.getValue().cause(), is((Throwable) insertException));
358         }
359
360         @Test
361         public void failureBecauseCancelledByUserSendsAbortedEvent() {
362                 InsertException insertException = new InsertException(CANCELLED, null);
363                 insertToken.onFailure(insertException, null, null);
364                 ArgumentCaptor<ImageInsertAbortedEvent> imageInsertAbortedEvent = forClass(ImageInsertAbortedEvent.class);
365                 verify(eventBus).post(imageInsertAbortedEvent.capture());
366                 assertThat(imageInsertAbortedEvent.getValue().image(), is(image));
367         }
368
369         @Test
370         public void ignoredMethodsDoNotThrowExceptions() {
371                 insertToken.onMajorProgress(null);
372                 insertToken.onFetchable(null, null);
373                 insertToken.onGeneratedMetadata(null, null, null);
374         }
375
376         @Test
377         public void generatedUriIsPostedOnSuccess() {
378                 FreenetURI generatedUri = mock(FreenetURI.class);
379                 insertToken.onGeneratedURI(generatedUri, null, null);
380                 insertToken.onSuccess(null, null);
381                 ArgumentCaptor<ImageInsertFinishedEvent> imageInsertFinishedEvent = forClass(ImageInsertFinishedEvent.class);
382                 verify(eventBus).post(imageInsertFinishedEvent.capture());
383                 assertThat(imageInsertFinishedEvent.getValue().image(), is(image));
384                 assertThat(imageInsertFinishedEvent.getValue().resultingUri(), is(generatedUri));
385         }
386
387         @Test
388         public void insertTokenSupplierSuppliesInsertTokens() {
389                 InsertTokenSupplier insertTokenSupplier = freenetInterface.new InsertTokenSupplier();
390                 assertThat(insertTokenSupplier.apply(image), notNullValue());
391         }
392
393 }