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