Replace image browser page with Kotlin version
[Sone.git] / src / test / java / net / pterodactylus / sone / web / pages / WebPageTest.java
1 package net.pterodactylus.sone.web.pages;
2
3 import static net.pterodactylus.sone.test.GuiceKt.supply;
4 import static net.pterodactylus.sone.web.WebTestUtils.redirectsTo;
5 import static org.junit.Assert.fail;
6 import static org.mockito.ArgumentMatchers.anyBoolean;
7 import static org.mockito.ArgumentMatchers.anyInt;
8 import static org.mockito.ArgumentMatchers.anyString;
9 import static org.mockito.ArgumentMatchers.eq;
10 import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
11 import static org.mockito.Mockito.mock;
12 import static org.mockito.Mockito.when;
13
14 import java.io.ByteArrayOutputStream;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.PipedInputStream;
18 import java.io.PipedOutputStream;
19 import java.net.URI;
20 import java.net.URISyntaxException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.NoSuchElementException;
28 import java.util.Set;
29
30 import javax.annotation.Nonnull;
31 import javax.naming.SizeLimitExceededException;
32
33 import net.pterodactylus.sone.core.Core;
34 import net.pterodactylus.sone.core.Preferences;
35 import net.pterodactylus.sone.core.UpdateChecker;
36 import net.pterodactylus.sone.data.Album;
37 import net.pterodactylus.sone.data.Image;
38 import net.pterodactylus.sone.data.Post;
39 import net.pterodactylus.sone.data.PostReply;
40 import net.pterodactylus.sone.data.Sone;
41 import net.pterodactylus.sone.data.SoneOptions.DefaultSoneOptions;
42 import net.pterodactylus.sone.data.TemporaryImage;
43 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
44 import net.pterodactylus.sone.web.WebInterface;
45 import net.pterodactylus.sone.web.page.FreenetRequest;
46 import net.pterodactylus.sone.web.page.FreenetTemplatePage.RedirectException;
47 import net.pterodactylus.util.notify.Notification;
48 import net.pterodactylus.util.template.Template;
49 import net.pterodactylus.util.template.TemplateContext;
50 import net.pterodactylus.util.web.Method;
51 import net.pterodactylus.util.web.Response;
52
53 import freenet.clients.http.ToadletContext;
54 import freenet.l10n.BaseL10n;
55 import freenet.support.SimpleReadOnlyArrayBucket;
56 import freenet.support.api.Bucket;
57 import freenet.support.api.HTTPRequest;
58 import freenet.support.api.HTTPUploadedFile;
59 import freenet.support.io.NullBucket;
60
61 import com.google.common.base.Optional;
62 import com.google.common.collect.ArrayListMultimap;
63 import com.google.common.collect.ListMultimap;
64 import com.google.common.collect.Multimap;
65 import com.google.common.eventbus.EventBus;
66 import com.google.common.io.ByteStreams;
67 import com.google.inject.Guice;
68 import com.google.inject.Injector;
69 import org.junit.Before;
70 import org.junit.Rule;
71 import org.junit.rules.ExpectedException;
72 import org.mockito.ArgumentMatchers;
73 import org.mockito.invocation.InvocationOnMock;
74 import org.mockito.stubbing.Answer;
75
76 /**
77  * Base class for web page tests.
78  *
79  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
80  */
81 public abstract class WebPageTest {
82
83         @Rule
84         public final ExpectedException expectedException = ExpectedException.none();
85
86         protected final Template template = new Template();
87         protected final WebInterface webInterface = mock(WebInterface.class, RETURNS_DEEP_STUBS);
88         protected final EventBus eventBus = mock(EventBus.class);
89         protected final Core core = webInterface.getCore();
90         protected final BaseL10n l10n = webInterface.getL10n();
91
92         protected final Sone currentSone = mock(Sone.class);
93
94         protected final TemplateContext templateContext = new TemplateContext();
95         protected final HTTPRequest httpRequest = mock(HTTPRequest.class);
96         protected final Multimap<String, String> requestParameters = ArrayListMultimap.create();
97         protected final Map<String, String> requestParts = new HashMap<>();
98         protected final Map<String, String> requestHeaders = new HashMap<>();
99         private final Map<String, String> uploadedFilesNames = new HashMap<>();
100         private final Map<String, String> uploadedFilesContentTypes = new HashMap<>();
101         private final Map<String, String> uploadedFilesSources = new HashMap<>();
102         protected final FreenetRequest freenetRequest = mock(FreenetRequest.class);
103         private final PipedOutputStream responseOutputStream = new PipedOutputStream();
104         private final PipedInputStream responseInputStream;
105         protected final Response response = new Response(responseOutputStream);
106         protected final ToadletContext toadletContext = mock(ToadletContext.class);
107
108         private final Set<OwnIdentity> ownIdentities = new HashSet<>();
109         private final Map<String, Sone> sones = new HashMap<>();
110         protected final List<Sone> localSones = new ArrayList<>();
111         private final ListMultimap<String, PostReply> postReplies = ArrayListMultimap.create();
112
113         protected final Injector injector = Guice.createInjector(
114                         supply(WebInterface.class).byInstance(webInterface),
115                         supply(Template.class).byInstance(template)
116         );
117
118         protected WebPageTest() {
119                 try {
120                         responseInputStream = new PipedInputStream(responseOutputStream);
121                 } catch (IOException e) {
122                         throw new RuntimeException(e);
123                 }
124         }
125
126         @Before
127         public final void setupFreenetRequest() throws SizeLimitExceededException {
128                 when(freenetRequest.getToadletContext()).thenReturn(toadletContext);
129                 when(freenetRequest.getHttpRequest()).thenReturn(httpRequest);
130                 when(httpRequest.getMultipleParam(anyString())).thenAnswer(new Answer<String[]>() {
131                         @Override
132                         public String[] answer(InvocationOnMock invocation) throws Throwable {
133                                 return requestParameters.get(invocation.<String>getArgument(0)).toArray(new String[0]);
134                         }
135                 });
136                 when(httpRequest.isPartSet(anyString())).thenAnswer(new Answer<Boolean>() {
137                         @Override
138                         public Boolean answer(InvocationOnMock invocation) throws Throwable {
139                                 return requestParts.get(invocation.<String>getArgument(0)) != null;
140                         }
141                 });
142                 when(httpRequest.getParts()).thenAnswer(new Answer<String[]>() {
143                         @Override
144                         public String[] answer(InvocationOnMock invocation) throws Throwable {
145                                 return requestParts.keySet().toArray(new String[requestParts.size()]);
146                         }
147                 });
148                 when(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).thenAnswer(new Answer<String>() {
149                         @Override
150                         public String answer(InvocationOnMock invocation) throws Throwable {
151                                 String parameter = invocation.getArgument(0);
152                                 int maxLength = invocation.getArgument(1);
153                                 String value = requestParts.get(parameter);
154                                 return requestParts.containsKey(parameter) ? value.substring(0, Math.min(maxLength, value.length())) : "";
155                         }
156                 });
157                 when(httpRequest.getPartAsStringThrowing(anyString(), anyInt())).thenAnswer(new Answer<String>() {
158                         @Override
159                         public String answer(InvocationOnMock invocation) throws Throwable {
160                                 String partName = invocation.getArgument(0);
161                                 if (!requestParts.containsKey(partName)) throw new NoSuchElementException();
162                                 String partValue = requestParts.get(partName);
163                                 if (partValue.length() > invocation.<Integer>getArgument(1)) throw new SizeLimitExceededException();
164                                 return partValue;
165                         }
166                 });
167                 when(httpRequest.hasParameters()).thenAnswer(new Answer<Boolean>() {
168                         @Override
169                         public Boolean answer(InvocationOnMock invocation) throws Throwable {
170                                 return !requestParameters.isEmpty();
171                         }
172                 });
173                 when(httpRequest.getParameterNames()).thenAnswer(new Answer<Collection<String>>() {
174                         @Override
175                         public Collection<String> answer(InvocationOnMock invocation) throws Throwable {
176                                 return requestParameters.keySet();
177                         }
178                 });
179                 when(httpRequest.getParam(anyString())).thenAnswer(new Answer<String>() {
180                         @Override
181                         public String answer(InvocationOnMock invocation) throws Throwable {
182                                 String parameter = invocation.getArgument(0);
183                                 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : "";
184                         }
185                 });
186                 when(httpRequest.getParam(anyString(), ArgumentMatchers.<String>any())).thenAnswer(new Answer<String>() {
187                         @Override
188                         public String answer(InvocationOnMock invocation) throws Throwable {
189                                 String parameter = invocation.getArgument(0);
190                                 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : invocation.<String>getArgument(1);
191                         }
192                 });
193                 when(httpRequest.isParameterSet(anyString())).thenAnswer(new Answer<Boolean>() {
194                         @Override
195                         public Boolean answer(InvocationOnMock invocation) throws Throwable {
196                                 return requestParameters.containsKey(invocation.<String>getArgument(0)) &&
197                                                 requestParameters.get(invocation.<String>getArgument(0)).iterator().next() != null;
198                         }
199                 });
200                 when(httpRequest.getHeader(anyString())).thenAnswer(new Answer<String>() {
201                         @Override
202                         public String answer(InvocationOnMock invocation) throws Throwable {
203                                 return requestHeaders.get(invocation.<String>getArgument(0).toLowerCase());
204                         }
205                 });
206                 when(httpRequest.getUploadedFile(anyString())).thenAnswer(new Answer<HTTPUploadedFile>() {
207                         @Override
208                         public HTTPUploadedFile answer(InvocationOnMock invocation) throws Throwable {
209                                 final String name = invocation.getArgument(0);
210                                 if (!uploadedFilesSources.containsKey(name)) {
211                                         return null;
212                                 }
213                                 return new HTTPUploadedFile() {
214                                         @Override
215                                         public String getContentType() {
216                                                 return uploadedFilesContentTypes.get(name);
217                                         }
218
219                                         @Override
220                                         public Bucket getData() {
221                                                 try (InputStream inputStream = getClass().getResourceAsStream(uploadedFilesSources.get(name))) {
222                                                         byte[] bytes = ByteStreams.toByteArray(inputStream);
223                                                         return new SimpleReadOnlyArrayBucket(bytes, 0, bytes.length);
224                                                 } catch (IOException ioe1) {
225                                                         return new NullBucket();
226                                                 }
227                                         }
228
229                                         @Override
230                                         public String getFilename() {
231                                                 return uploadedFilesNames.get(name);
232                                         }
233                                 };
234                         }
235                 });
236         }
237
238         @Before
239         public final void setupCore() {
240                 UpdateChecker updateChecker = mock(UpdateChecker.class);
241                 when(core.getUpdateChecker()).thenReturn(updateChecker);
242                 when(core.getPreferences()).thenReturn(new Preferences(eventBus));
243                 when(core.getLocalSone(anyString())).thenReturn(null);
244                 when(core.getLocalSones()).thenReturn(localSones);
245                 when(core.getSone(anyString())).thenReturn(Optional.<Sone>absent());
246                 when(core.getSones()).thenAnswer(new Answer<Collection<Sone>>() {
247                         @Override
248                         public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
249                                 return sones.values();
250                         }
251                 });
252                 when(core.getSone(anyString())).thenAnswer(new Answer<Optional<Sone>>() {
253                         @Override
254                         public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
255                                 return Optional.fromNullable(sones.get(invocation.getArgument(0)));
256                         }
257                 });
258                 when(core.getPost(anyString())).thenReturn(Optional.<Post>absent());
259                 when(core.getPostReply(anyString())).thenReturn(Optional.<PostReply>absent());
260                 when(core.getReplies(anyString())).thenAnswer(new Answer<List<PostReply>>() {
261                         @Override
262                         public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
263                                 return postReplies.get(invocation.<String>getArgument(0));
264                         }
265                 });
266                 when(core.getAlbum(anyString())).thenReturn(null);
267                 when(core.getImage(anyString())).thenReturn(null);
268                 when(core.getImage(anyString(), anyBoolean())).thenReturn(null);
269                 when(core.getTemporaryImage(anyString())).thenReturn(null);
270         }
271
272         @Before
273         public void setupL10n() {
274                 when(l10n.getString(anyString())).thenAnswer(new Answer<String>() {
275                         @Override
276                         public String answer(InvocationOnMock invocation) throws Throwable {
277                                 return invocation.getArgument(0);
278                         }
279                 });
280         }
281
282         @Before
283         public final void setupIdentityManager() {
284                 when(core.getIdentityManager().getAllOwnIdentities()).thenReturn(ownIdentities);
285         }
286
287         @Before
288         public final void setupWebInterface() {
289                 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(currentSone);
290                 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(currentSone);
291                 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(currentSone);
292                 when(webInterface.getNotification(anyString())).thenReturn(Optional.<Notification>absent());
293                 when(webInterface.getNotifications(currentSone)).thenReturn(new ArrayList<Notification>());
294         }
295
296         @Before
297         public void setupSone() {
298                 when(currentSone.getOptions()).thenReturn(new DefaultSoneOptions());
299         }
300
301         protected SoneTemplatePage getPage() {
302                 return null;
303         }
304
305         protected void unsetCurrentSone() {
306                 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(null);
307                 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(null);
308                 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(null);
309         }
310
311         protected void request(String uri, Method method) {
312                 try {
313                         when(httpRequest.getPath()).thenReturn(uri);
314                         when(freenetRequest.getUri()).thenReturn(new URI(uri));
315                 } catch (URISyntaxException e) {
316                         throw new RuntimeException(e);
317                 }
318                 when(freenetRequest.getMethod()).thenReturn(method);
319                 when(httpRequest.getMethod()).thenReturn(method.name());
320         }
321
322         protected void addHttpRequestHeader(@Nonnull String name, String value) {
323                 requestHeaders.put(name.toLowerCase(), value);
324         }
325
326         protected void addHttpRequestParameter(String name, final String value) {
327                 requestParameters.put(name, value);
328         }
329
330         protected void addHttpRequestPart(String name, String value) {
331                 requestParts.put(name, value);
332         }
333
334         protected void addPost(String postId, Post post) {
335                 when(core.getPost(postId)).thenReturn(Optional.fromNullable(post));
336         }
337
338         protected void addPostReply(String postReplyId, PostReply postReply) {
339                 if (postReply.getPostId() != null) {
340                         postReplies.put(postReply.getPostId(), postReply);
341                 }
342                 when(core.getPostReply(postReplyId)).thenReturn(Optional.fromNullable(postReply));
343         }
344
345         protected void addSone(String soneId, Sone sone) {
346                 sones.put(soneId, sone);
347         }
348
349         protected void addLocalSone(String soneId, Sone sone) {
350                 when(core.getLocalSone(eq(soneId))).thenReturn(sone);
351                 localSones.add(sone);
352         }
353
354         protected void addOwnIdentity(OwnIdentity ownIdentity) {
355                 ownIdentities.add(ownIdentity);
356         }
357
358         protected void addAlbum(String albumId, Album album) {
359                 when(core.getAlbum(eq(albumId))).thenReturn(album);
360         }
361
362         protected void addImage(String imageId, Image image) {
363                 when(core.getImage(eq(imageId))).thenReturn(image);
364                 when(core.getImage(eq(imageId), anyBoolean())).thenReturn(image);
365         }
366
367         protected void addTemporaryImage(String imageId, TemporaryImage temporaryImage) {
368                 when(core.getTemporaryImage(eq(imageId))).thenReturn(temporaryImage);
369         }
370
371         protected void addUploadedFile(@Nonnull String name, @Nonnull String filename, @Nonnull String contentType, @Nonnull String resource) {
372                 uploadedFilesNames.put(name, filename);
373                 uploadedFilesContentTypes.put(name, contentType);
374                 uploadedFilesSources.put(name, resource);
375         }
376
377         protected byte[] getResponseBytes() throws IOException {
378                 response.getContent().close();
379                 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
380                         ByteStreams.copy(responseInputStream, outputStream);
381                         return outputStream.toByteArray();
382                 }
383         }
384
385         protected void addNotification(String notificationId, Notification notification) {
386                 when(webInterface.getNotification(eq(notificationId))).thenReturn(Optional.of(notification));
387         }
388
389         protected void verifyRedirect(String target) throws RedirectException {
390                 expectedException.expect(redirectsTo(target));
391                 getPage().handleRequest(freenetRequest, templateContext);
392         }
393
394         protected void verifyRedirect(String target, Runnable verification) throws RedirectException {
395                 expectedException.expect(redirectsTo(target));
396                 try {
397                         getPage().handleRequest(freenetRequest, templateContext);
398                         fail();
399                 } finally {
400                         verification.run();
401                 }
402         }
403
404 }