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