✅ Add more tests for FreenetTemplatePage
[Sone.git] / src / test / java / net / pterodactylus / sone / core / FreenetInterfaceTest.java
1 package net.pterodactylus.sone.core;
2
3 import static freenet.client.FetchException.FetchExceptionMode.ALL_DATA_NOT_FOUND;
4 import static freenet.keys.InsertableClientSSK.createRandom;
5 import static freenet.node.RequestStarter.INTERACTIVE_PRIORITY_CLASS;
6 import static freenet.node.RequestStarter.PREFETCH_PRIORITY_CLASS;
7 import static net.pterodactylus.sone.test.Matchers.delivers;
8 import static net.pterodactylus.sone.test.TestUtil.setFinalField;
9 import static org.hamcrest.MatcherAssert.assertThat;
10 import static org.hamcrest.Matchers.is;
11 import static org.hamcrest.Matchers.notNullValue;
12 import static org.hamcrest.Matchers.nullValue;
13 import static org.mockito.ArgumentCaptor.forClass;
14 import static org.mockito.ArgumentMatchers.any;
15 import static org.mockito.ArgumentMatchers.anyBoolean;
16 import static org.mockito.ArgumentMatchers.anyLong;
17 import static org.mockito.ArgumentMatchers.anyShort;
18 import static org.mockito.ArgumentMatchers.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.verifyNoMoreInteractions;
25 import static org.mockito.Mockito.when;
26 import static org.mockito.Mockito.withSettings;
27
28 import java.io.IOException;
29 import java.net.MalformedURLException;
30 import java.util.HashMap;
31
32 import net.pterodactylus.sone.core.FreenetInterface.BackgroundFetchCallback;
33 import net.pterodactylus.sone.core.FreenetInterface.Callback;
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.Sone;
42 import net.pterodactylus.sone.data.TemporaryImage;
43 import net.pterodactylus.sone.data.impl.ImageImpl;
44 import net.pterodactylus.sone.test.TestUtil;
45
46 import freenet.client.ClientMetadata;
47 import freenet.client.FetchContext;
48 import freenet.client.FetchException;
49 import freenet.client.FetchException.FetchExceptionMode;
50 import freenet.client.FetchResult;
51 import freenet.client.HighLevelSimpleClient;
52 import freenet.client.InsertBlock;
53 import freenet.client.InsertContext;
54 import freenet.client.InsertException;
55 import freenet.client.InsertException.InsertExceptionMode;
56 import freenet.client.Metadata;
57 import freenet.client.async.ClientContext;
58 import freenet.client.async.ClientGetCallback;
59 import freenet.client.async.ClientGetter;
60 import freenet.client.async.ClientPutter;
61 import freenet.client.async.SnoopMetadata;
62 import freenet.client.async.USKCallback;
63 import freenet.client.async.USKManager;
64 import freenet.crypt.DummyRandomSource;
65 import freenet.crypt.RandomSource;
66 import freenet.keys.FreenetURI;
67 import freenet.keys.InsertableClientSSK;
68 import freenet.keys.USK;
69 import freenet.node.Node;
70 import freenet.node.NodeClientCore;
71 import freenet.node.RequestClient;
72 import freenet.support.Base64;
73 import freenet.support.api.Bucket;
74 import freenet.support.io.ArrayBucket;
75 import freenet.support.io.ResumeFailedException;
76
77 import com.google.common.eventbus.EventBus;
78 import org.junit.Before;
79 import org.junit.Test;
80 import org.mockito.ArgumentCaptor;
81 import org.mockito.ArgumentMatchers;
82
83 /**
84  * Unit test for {@link FreenetInterface}.
85  */
86 public class FreenetInterfaceTest {
87
88         private final EventBus eventBus = mock(EventBus.class);
89         private final Node node = mock(Node.class);
90         private final NodeClientCore nodeClientCore = mock(NodeClientCore.class);
91         private final HighLevelSimpleClient highLevelSimpleClient = mock(HighLevelSimpleClient.class, withSettings().extraInterfaces(RequestClient.class));
92         private final RandomSource randomSource = new DummyRandomSource();
93         private final USKManager uskManager = mock(USKManager.class);
94         private FreenetInterface freenetInterface;
95         private final Sone sone = mock(Sone.class);
96         private final ArgumentCaptor<USKCallback> callbackCaptor = forClass(USKCallback.class);
97         private final Image image = mock(Image.class);
98         private InsertToken insertToken;
99         private final Bucket bucket = mock(Bucket.class);
100         private final ArgumentCaptor<ClientGetCallback> clientGetCallback = forClass(ClientGetCallback.class);
101         private final FreenetURI uri = new FreenetURI("KSK@pgl.png");
102         private final FetchResult fetchResult = mock(FetchResult.class);
103         private final BackgroundFetchCallback backgroundFetchCallback = mock(BackgroundFetchCallback.class);
104         private final ClientGetter clientGetter = mock(ClientGetter.class);
105
106         public FreenetInterfaceTest() throws MalformedURLException {
107         }
108
109         @Before
110         public void setupHighLevelSimpleClient() throws Exception {
111                 when(highLevelSimpleClient.getFetchContext()).thenReturn(mock(FetchContext.class));
112                 when(highLevelSimpleClient.fetch(eq(uri), anyLong(), any(ClientGetCallback.class), any(FetchContext.class), anyShort())).thenReturn( clientGetter);
113         }
114
115         @Before
116         public void setupFreenetInterface() {
117                 when(nodeClientCore.makeClient(anyShort(), anyBoolean(), anyBoolean())).thenReturn(highLevelSimpleClient);
118                 setFinalField(node, "clientCore", nodeClientCore);
119                 setFinalField(node, "random", randomSource);
120                 setFinalField(nodeClientCore, "uskManager", uskManager);
121                 setFinalField(nodeClientCore, "clientContext", mock(ClientContext.class));
122                 freenetInterface = new FreenetInterface(eventBus, node);
123                 insertToken = freenetInterface.new InsertToken(image);
124                 insertToken.setBucket(bucket);
125         }
126
127         @Before
128         public void setupSone() {
129                 InsertableClientSSK insertSsk = createRandom(randomSource, "test-0");
130                 when(sone.getId()).thenReturn(Base64.encode(insertSsk.getURI().getRoutingKey()));
131                 when(sone.getRequestUri()).thenReturn(insertSsk.getURI().uskForSSK());
132         }
133
134         @Before
135         public void setupCallbackCaptorAndUskManager() {
136                 doNothing().when(uskManager).subscribe(any(USK.class), callbackCaptor.capture(), anyBoolean(), any(RequestClient.class));
137         }
138
139         @Test
140         public void canFetchUri() throws MalformedURLException, FetchException {
141                 FreenetURI freenetUri = new FreenetURI("KSK@GPLv3.txt");
142                 FetchResult fetchResult = createFetchResult();
143                 when(highLevelSimpleClient.fetch(freenetUri)).thenReturn(fetchResult);
144                 Fetched fetched = freenetInterface.fetchUri(freenetUri);
145                 assertThat(fetched, notNullValue());
146                 assertThat(fetched.getFetchResult(), is(fetchResult));
147                 assertThat(fetched.getFreenetUri(), is(freenetUri));
148         }
149
150         @Test
151         public void fetchFollowsRedirect() throws MalformedURLException, FetchException {
152                 FreenetURI freenetUri = new FreenetURI("KSK@GPLv2.txt");
153                 FreenetURI newFreenetUri = new FreenetURI("KSK@GPLv3.txt");
154                 FetchResult fetchResult = createFetchResult();
155                 FetchException fetchException = new FetchException(FetchExceptionMode.PERMANENT_REDIRECT, newFreenetUri);
156                 when(highLevelSimpleClient.fetch(freenetUri)).thenThrow(fetchException);
157                 when(highLevelSimpleClient.fetch(newFreenetUri)).thenReturn(fetchResult);
158                 Fetched fetched = freenetInterface.fetchUri(freenetUri);
159                 assertThat(fetched.getFetchResult(), is(fetchResult));
160                 assertThat(fetched.getFreenetUri(), is(newFreenetUri));
161         }
162
163         @Test
164         public void fetchReturnsNullOnFetchExceptions() throws MalformedURLException, FetchException {
165                 FreenetURI freenetUri = new FreenetURI("KSK@GPLv2.txt");
166                 FetchException fetchException = new FetchException(ALL_DATA_NOT_FOUND);
167                 when(highLevelSimpleClient.fetch(freenetUri)).thenThrow(fetchException);
168                 Fetched fetched = freenetInterface.fetchUri(freenetUri);
169                 assertThat(fetched, nullValue());
170         }
171
172         private FetchResult createFetchResult() {
173                 ClientMetadata clientMetadata = new ClientMetadata("text/plain");
174                 Bucket bucket = new ArrayBucket("Some Data.".getBytes());
175                 return new FetchResult(clientMetadata, bucket);
176         }
177
178         @Test
179         public void insertingAnImage() throws SoneException, InsertException, IOException {
180                 TemporaryImage temporaryImage = new TemporaryImage("image-id");
181                 temporaryImage.setMimeType("image/png");
182                 byte[] imageData = new byte[] { 1, 2, 3, 4 };
183                 temporaryImage.setImageData(imageData);
184                 Image image = new ImageImpl("image-id");
185                 InsertToken insertToken = freenetInterface.new InsertToken(image);
186                 InsertContext insertContext = mock(InsertContext.class);
187                 when(highLevelSimpleClient.getInsertContext(anyBoolean())).thenReturn(insertContext);
188                 ClientPutter clientPutter = mock(ClientPutter.class);
189                 ArgumentCaptor<InsertBlock> insertBlockCaptor = forClass(InsertBlock.class);
190                 when(highLevelSimpleClient.insert(insertBlockCaptor.capture(), eq((String) null), eq(false), eq(insertContext), eq(insertToken), anyShort())).thenReturn(clientPutter);
191                 freenetInterface.insertImage(temporaryImage, image, insertToken);
192                 assertThat(insertBlockCaptor.getValue().getData().getInputStream(), delivers(new byte[] { 1, 2, 3, 4 }));
193                 assertThat(TestUtil.<ClientPutter>getPrivateField(insertToken, "clientPutter"), is(clientPutter));
194                 verify(eventBus).post(any(ImageInsertStartedEvent.class));
195         }
196
197         @Test(expected = SoneInsertException.class)
198         public void insertExceptionCausesASoneException() throws InsertException, SoneException, IOException {
199                 TemporaryImage temporaryImage = new TemporaryImage("image-id");
200                 temporaryImage.setMimeType("image/png");
201                 byte[] imageData = new byte[] { 1, 2, 3, 4 };
202                 temporaryImage.setImageData(imageData);
203                 Image image = new ImageImpl("image-id");
204                 InsertToken insertToken = freenetInterface.new InsertToken(image);
205                 InsertContext insertContext = mock(InsertContext.class);
206                 when(highLevelSimpleClient.getInsertContext(anyBoolean())).thenReturn(insertContext);
207                 ArgumentCaptor<InsertBlock> insertBlockCaptor = forClass(InsertBlock.class);
208                 when(highLevelSimpleClient.insert(insertBlockCaptor.capture(), eq((String) null), eq(false), eq(insertContext), eq(insertToken), anyShort())).thenThrow(InsertException.class);
209                 freenetInterface.insertImage(temporaryImage, image, insertToken);
210         }
211
212         @Test
213         public void insertingADirectory() throws InsertException, SoneException {
214                 FreenetURI freenetUri = mock(FreenetURI.class);
215                 HashMap<String, Object> manifestEntries = new HashMap<>();
216                 String defaultFile = "index.html";
217                 FreenetURI resultingUri = mock(FreenetURI.class);
218                 when(highLevelSimpleClient.insertManifest(eq(freenetUri), eq(manifestEntries), eq(defaultFile))).thenReturn(resultingUri);
219                 assertThat(freenetInterface.insertDirectory(freenetUri, manifestEntries, defaultFile), is(resultingUri));
220         }
221
222         @Test(expected = SoneException.class)
223         public void insertExceptionIsForwardedAsSoneException() throws InsertException, SoneException {
224                 when(highLevelSimpleClient.insertManifest(ArgumentMatchers.<FreenetURI>any(), ArgumentMatchers.<HashMap<String, Object>>any(), ArgumentMatchers.<String>any())).thenThrow(InsertException.class);
225                 freenetInterface.insertDirectory(null, null, null);
226         }
227
228         @Test
229         public void soneWithWrongRequestUriWillNotBeSubscribed() throws MalformedURLException {
230                 when(sone.getRequestUri()).thenReturn(new FreenetURI("KSK@GPLv3.txt"));
231                 freenetInterface.registerUsk(new FreenetURI("KSK@GPLv3.txt"), null);
232                 verify(uskManager, never()).subscribe(any(USK.class), any(USKCallback.class), anyBoolean(), any(RequestClient.class));
233         }
234
235         @Test
236         public void registeringAUsk() {
237                 FreenetURI freenetUri = createRandom(randomSource, "test-0").getURI().uskForSSK();
238                 Callback callback = mock(Callback.class);
239                 freenetInterface.registerUsk(freenetUri, callback);
240                 verify(uskManager).subscribe(any(USK.class), any(USKCallback.class), anyBoolean(), any(RequestClient.class));
241         }
242
243         @Test
244         public void registeringANonUskKeyWillNotBeSubscribed() throws MalformedURLException {
245                 FreenetURI freenetUri = new FreenetURI("KSK@GPLv3.txt");
246                 Callback callback = mock(Callback.class);
247                 freenetInterface.registerUsk(freenetUri, callback);
248                 verify(uskManager, never()).subscribe(any(USK.class), any(USKCallback.class), anyBoolean(), any(RequestClient.class));
249         }
250
251         @Test
252         public void registeringAnActiveUskWillSubscribeToItCorrectly() {
253                 FreenetURI freenetUri = createRandom(randomSource, "test-0").getURI().uskForSSK();
254                 final USKCallback uskCallback = mock(USKCallback.class);
255                 freenetInterface.registerActiveUsk(freenetUri, uskCallback);
256                 verify(uskManager).subscribe(any(USK.class), eq(uskCallback), eq(true), any(RequestClient.class));
257         }
258
259         @Test
260         public void registeringAnInactiveUskWillSubscribeToItCorrectly() {
261                 FreenetURI freenetUri = createRandom(randomSource, "test-0").getURI().uskForSSK();
262                 final USKCallback uskCallback = mock(USKCallback.class);
263                 freenetInterface.registerPassiveUsk(freenetUri, uskCallback);
264                 verify(uskManager).subscribe(any(USK.class), eq(uskCallback), eq(false), any(RequestClient.class));
265         }
266
267         @Test
268         public void registeringAnActiveNonUskWillNotSubscribeToAUsk()
269         throws MalformedURLException {
270                 FreenetURI freenetUri = createRandom(randomSource, "test-0").getURI();
271                 freenetInterface.registerActiveUsk(freenetUri, null);
272                 verify(uskManager, never()).subscribe(any(USK.class), any(USKCallback.class), anyBoolean(), any(RequestClient.class));
273         }
274
275         @Test
276         public void registeringAnInactiveNonUskWillNotSubscribeToAUsk()
277         throws MalformedURLException {
278                 FreenetURI freenetUri = createRandom(randomSource, "test-0").getURI();
279                 freenetInterface.registerPassiveUsk(freenetUri, null);
280                 verify(uskManager, never()).subscribe(any(USK.class), any(USKCallback.class), anyBoolean(), any(RequestClient.class));
281         }
282
283         @Test
284         public void unregisteringANotRegisteredUskDoesNothing() {
285                 FreenetURI freenetURI = createRandom(randomSource, "test-0").getURI().uskForSSK();
286                 freenetInterface.unregisterUsk(freenetURI);
287                 verify(uskManager, never()).unsubscribe(any(USK.class), any(USKCallback.class));
288         }
289
290         @Test
291         public void unregisteringARegisteredUsk() {
292                 FreenetURI freenetURI = createRandom(randomSource, "test-0").getURI().uskForSSK();
293                 Callback callback = mock(Callback.class);
294                 freenetInterface.registerUsk(freenetURI, callback);
295                 freenetInterface.unregisterUsk(freenetURI);
296                 verify(uskManager).unsubscribe(any(USK.class), any(USKCallback.class));
297         }
298
299         @Test
300         public void unregisteringANotRegisteredSoneDoesNothing() {
301                 freenetInterface.unregisterUsk(sone);
302                 verify(uskManager, never()).unsubscribe(any(USK.class), any(USKCallback.class));
303         }
304
305         @Test
306         public void unregisteringARegisteredSoneUnregistersTheSone()
307         throws MalformedURLException {
308                 freenetInterface.registerActiveUsk(sone.getRequestUri(), mock(USKCallback.class));
309                 freenetInterface.unregisterUsk(sone);
310                 verify(uskManager).unsubscribe(any(USK.class), any(USKCallback.class));
311         }
312
313         @Test
314         public void unregisteringASoneWithAWrongRequestKeyWillNotUnsubscribe() throws MalformedURLException {
315                 when(sone.getRequestUri()).thenReturn(new FreenetURI("KSK@GPLv3.txt"));
316                 freenetInterface.registerUsk(sone.getRequestUri(), null);
317                 freenetInterface.unregisterUsk(sone);
318                 verify(uskManager, never()).unsubscribe(any(USK.class), any(USKCallback.class));
319         }
320
321         @Test
322         public void callbackForNormalUskUsesDifferentPriorities() {
323                 Callback callback = mock(Callback.class);
324                 FreenetURI soneUri = createRandom(randomSource, "test-0").getURI().uskForSSK();
325                 freenetInterface.registerUsk(soneUri, callback);
326                 assertThat(callbackCaptor.getValue().getPollingPriorityNormal(), is(PREFETCH_PRIORITY_CLASS));
327                 assertThat(callbackCaptor.getValue().getPollingPriorityProgress(), is(INTERACTIVE_PRIORITY_CLASS));
328         }
329
330         @Test
331         public void callbackForNormalUskForwardsImportantParameters() throws MalformedURLException {
332                 Callback callback = mock(Callback.class);
333                 FreenetURI uri = createRandom(randomSource, "test-0").getURI().uskForSSK();
334                 freenetInterface.registerUsk(uri, callback);
335                 USK key = mock(USK.class);
336                 when(key.getURI()).thenReturn(uri);
337                 callbackCaptor.getValue().onFoundEdition(3, key, null, false, (short) 0, null, true, true);
338                 verify(callback).editionFound(eq(uri), eq(3L), eq(true), eq(true));
339         }
340
341         @Test
342         public void fetchedRetainsUriAndFetchResult() {
343                 FreenetURI freenetUri = mock(FreenetURI.class);
344                 FetchResult fetchResult = mock(FetchResult.class);
345                 Fetched fetched = new Fetched(freenetUri, fetchResult);
346                 assertThat(fetched.getFreenetUri(), is(freenetUri));
347                 assertThat(fetched.getFetchResult(), is(fetchResult));
348         }
349
350         @Test
351         public void cancellingAnInsertWillFireImageInsertAbortedEvent() {
352                 ClientPutter clientPutter = mock(ClientPutter.class);
353                 insertToken.setClientPutter(clientPutter);
354                 ArgumentCaptor<ImageInsertStartedEvent> imageInsertStartedEvent = forClass(ImageInsertStartedEvent.class);
355                 verify(eventBus).post(imageInsertStartedEvent.capture());
356                 assertThat(imageInsertStartedEvent.getValue().image(), is(image));
357                 insertToken.cancel();
358                 ArgumentCaptor<ImageInsertAbortedEvent> imageInsertAbortedEvent = forClass(ImageInsertAbortedEvent.class);
359                 verify(eventBus, times(2)).post(imageInsertAbortedEvent.capture());
360                 verify(bucket).free();
361                 assertThat(imageInsertAbortedEvent.getValue().image(), is(image));
362         }
363
364         @Test
365         public void failureWithoutExceptionSendsFailedEvent() {
366                 insertToken.onFailure(null, null);
367                 ArgumentCaptor<ImageInsertFailedEvent> imageInsertFailedEvent = forClass(ImageInsertFailedEvent.class);
368                 verify(eventBus).post(imageInsertFailedEvent.capture());
369                 verify(bucket).free();
370                 assertThat(imageInsertFailedEvent.getValue().image(), is(image));
371                 assertThat(imageInsertFailedEvent.getValue().cause(), nullValue());
372         }
373
374         @Test
375         public void failureSendsFailedEventWithException() {
376                 InsertException insertException = new InsertException(InsertExceptionMode.INTERNAL_ERROR, "Internal error", null);
377                 insertToken.onFailure(insertException, null);
378                 ArgumentCaptor<ImageInsertFailedEvent> imageInsertFailedEvent = forClass(ImageInsertFailedEvent.class);
379                 verify(eventBus).post(imageInsertFailedEvent.capture());
380                 verify(bucket).free();
381                 assertThat(imageInsertFailedEvent.getValue().image(), is(image));
382                 assertThat(imageInsertFailedEvent.getValue().cause(), is((Throwable) insertException));
383         }
384
385         @Test
386         public void failureBecauseCancelledByUserSendsAbortedEvent() {
387                 InsertException insertException = new InsertException(InsertExceptionMode.CANCELLED, null);
388                 insertToken.onFailure(insertException, null);
389                 ArgumentCaptor<ImageInsertAbortedEvent> imageInsertAbortedEvent = forClass(ImageInsertAbortedEvent.class);
390                 verify(eventBus).post(imageInsertAbortedEvent.capture());
391                 verify(bucket).free();
392                 assertThat(imageInsertAbortedEvent.getValue().image(), is(image));
393         }
394
395         @Test
396         public void ignoredMethodsDoNotThrowExceptions() throws ResumeFailedException {
397                 insertToken.onResume(null);
398                 insertToken.onFetchable(null);
399                 insertToken.onGeneratedMetadata(null, null);
400         }
401
402         @Test
403         public void generatedUriIsPostedOnSuccess() {
404                 FreenetURI generatedUri = mock(FreenetURI.class);
405                 insertToken.onGeneratedURI(generatedUri, null);
406                 insertToken.onSuccess(null);
407                 ArgumentCaptor<ImageInsertFinishedEvent> imageInsertFinishedEvent = forClass(ImageInsertFinishedEvent.class);
408                 verify(eventBus).post(imageInsertFinishedEvent.capture());
409                 verify(bucket).free();
410                 assertThat(imageInsertFinishedEvent.getValue().image(), is(image));
411                 assertThat(imageInsertFinishedEvent.getValue().resultingUri(), is(generatedUri));
412         }
413
414         @Test
415         public void insertTokenSupplierSuppliesInsertTokens() {
416                 InsertTokenSupplier insertTokenSupplier = new InsertTokenSupplier(freenetInterface);
417                 assertThat(insertTokenSupplier.apply(image), notNullValue());
418         }
419
420         @Test
421         public void backgroundFetchCanBeStarted() throws Exception {
422                 freenetInterface.startFetch(uri, backgroundFetchCallback);
423                 verify(highLevelSimpleClient).fetch(eq(uri), anyLong(), any(ClientGetCallback.class), any(FetchContext.class), anyShort());
424         }
425
426         @Test
427         public void backgroundFetchRegistersSnoopAndRestartsTheRequest() throws Exception {
428                 freenetInterface.startFetch(uri, backgroundFetchCallback);
429                 verify(clientGetter).setMetaSnoop(any(SnoopMetadata.class));
430                 verify(clientGetter).restart(eq(uri), anyBoolean(), any(ClientContext.class));
431         }
432
433         @Test
434         public void requestIsNotCancelledForImageMimeType() {
435                 verifySnoopCancelsRequestForMimeType("image/png", false);
436                 verify(backgroundFetchCallback, never()).failed(uri);
437         }
438
439         @Test
440         public void requestIsCancelledForNullMimeType() {
441                 verifySnoopCancelsRequestForMimeType(null, true);
442                 verify(backgroundFetchCallback, never()).shouldCancel(eq(uri), ArgumentMatchers.<String>any(), anyLong());
443                 verify(backgroundFetchCallback).failed(uri);
444         }
445
446         @Test
447         public void requestIsCancelledForVideoMimeType() {
448                 verifySnoopCancelsRequestForMimeType("video/mkv", true);
449                 verify(backgroundFetchCallback).failed(uri);
450         }
451
452         @Test
453         public void requestIsCancelledForAudioMimeType() {
454                 verifySnoopCancelsRequestForMimeType("audio/mpeg", true);
455                 verify(backgroundFetchCallback).failed(uri);
456         }
457
458         @Test
459         public void requestIsCancelledForTextMimeType() {
460                 verifySnoopCancelsRequestForMimeType("text/plain", true);
461                 verify(backgroundFetchCallback).failed(uri);
462         }
463
464         private void verifySnoopCancelsRequestForMimeType(String mimeType, boolean cancel) {
465                 when(backgroundFetchCallback.shouldCancel(eq(uri), eq(mimeType), anyLong())).thenReturn(cancel);
466                 freenetInterface.startFetch(uri, backgroundFetchCallback);
467                 ArgumentCaptor<SnoopMetadata> snoopMetadata = forClass(SnoopMetadata.class);
468                 verify(clientGetter).setMetaSnoop(snoopMetadata.capture());
469                 Metadata metadata = mock(Metadata.class);
470                 when(metadata.getMIMEType()).thenReturn(mimeType);
471                 assertThat(snoopMetadata.getValue().snoopMetadata(metadata, mock(ClientContext.class)), is(cancel));
472         }
473
474         @Test
475         public void callbackOfBackgroundFetchIsNotifiedOnSuccess() throws Exception {
476                 freenetInterface.startFetch(uri, backgroundFetchCallback);
477                 verify(highLevelSimpleClient).fetch(eq(uri), anyLong(), clientGetCallback.capture(), any(FetchContext.class), anyShort());
478                 when(fetchResult.getMimeType()).thenReturn("image/png");
479                 when(fetchResult.asByteArray()).thenReturn(new byte[] { 1, 2, 3, 4, 5 });
480                 clientGetCallback.getValue().onSuccess(fetchResult, mock(ClientGetter.class));
481                 verify(backgroundFetchCallback).loaded(uri, "image/png", new byte[] { 1, 2, 3, 4, 5 });
482                 verifyNoMoreInteractions(backgroundFetchCallback);
483         }
484
485         @Test
486         public void callbackOfBackgroundFetchIsNotifiedOnFailure() throws Exception {
487                 freenetInterface.startFetch(uri, backgroundFetchCallback);
488                 verify(highLevelSimpleClient).fetch(eq(uri), anyLong(), clientGetCallback.capture(), any(FetchContext.class), anyShort());
489                 when(fetchResult.getMimeType()).thenReturn("image/png");
490                 when(fetchResult.asByteArray()).thenReturn(new byte[] { 1, 2, 3, 4, 5 });
491                 clientGetCallback.getValue().onFailure(new FetchException(ALL_DATA_NOT_FOUND), mock(ClientGetter.class));
492                 verify(backgroundFetchCallback).failed(uri);
493                 verifyNoMoreInteractions(backgroundFetchCallback);
494         }
495
496         @Test
497         public void callbackOfBackgroundFetchIsNotifiedAsFailureIfBucketCanNotBeLoaded() throws Exception {
498                 freenetInterface.startFetch(uri, backgroundFetchCallback);
499                 verify(highLevelSimpleClient).fetch(eq(uri), anyLong(), clientGetCallback.capture(), any(FetchContext.class), anyShort());
500                 when(fetchResult.getMimeType()).thenReturn("image/png");
501                 when(fetchResult.asByteArray()).thenThrow(IOException.class);
502                 clientGetCallback.getValue().onSuccess(fetchResult, mock(ClientGetter.class));
503                 verify(backgroundFetchCallback).failed(uri);
504                 verifyNoMoreInteractions(backgroundFetchCallback);
505         }
506
507 }