Simplify verifying that no redirect is called
[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.Mockito;
74 import org.mockito.invocation.InvocationOnMock;
75 import org.mockito.stubbing.Answer;
76
77 /**
78  * Base class for web page tests.
79  *
80  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
81  */
82 public abstract class WebPageTest {
83
84         @Rule
85         public final ExpectedException expectedException = ExpectedException.none();
86
87         protected final Template template = new Template();
88         protected final WebInterface webInterface = mock(WebInterface.class, RETURNS_DEEP_STUBS);
89         protected final EventBus eventBus = mock(EventBus.class);
90         protected final Core core = webInterface.getCore();
91         protected final BaseL10n l10n = webInterface.getL10n();
92
93         protected final Sone currentSone = mock(Sone.class);
94
95         protected final TemplateContext templateContext = new TemplateContext();
96         protected final HTTPRequest httpRequest = mock(HTTPRequest.class);
97         protected final Multimap<String, String> requestParameters = ArrayListMultimap.create();
98         protected final Map<String, String> requestParts = new HashMap<>();
99         protected final Map<String, String> requestHeaders = new HashMap<>();
100         private final Map<String, String> uploadedFilesNames = new HashMap<>();
101         private final Map<String, String> uploadedFilesContentTypes = new HashMap<>();
102         private final Map<String, String> uploadedFilesSources = new HashMap<>();
103         protected final FreenetRequest freenetRequest = mock(FreenetRequest.class);
104         private final PipedOutputStream responseOutputStream = new PipedOutputStream();
105         private final PipedInputStream responseInputStream;
106         protected final Response response = new Response(responseOutputStream);
107         protected final ToadletContext toadletContext = mock(ToadletContext.class);
108
109         private final Set<OwnIdentity> ownIdentities = new HashSet<>();
110         private final Map<String, Sone> sones = new HashMap<>();
111         protected final List<Sone> localSones = new ArrayList<>();
112         private final ListMultimap<String, PostReply> postReplies = ArrayListMultimap.create();
113
114         protected final Injector injector = Guice.createInjector(
115                         supply(WebInterface.class).byInstance(webInterface),
116                         supply(Template.class).byInstance(template)
117         );
118
119         protected WebPageTest() {
120                 try {
121                         responseInputStream = new PipedInputStream(responseOutputStream);
122                 } catch (IOException e) {
123                         throw new RuntimeException(e);
124                 }
125         }
126
127         @Before
128         public final void setupFreenetRequest() throws SizeLimitExceededException {
129                 when(freenetRequest.getToadletContext()).thenReturn(toadletContext);
130                 when(freenetRequest.getHttpRequest()).thenReturn(httpRequest);
131                 when(httpRequest.getMultipleParam(anyString())).thenAnswer(new Answer<String[]>() {
132                         @Override
133                         public String[] answer(InvocationOnMock invocation) throws Throwable {
134                                 return requestParameters.get(invocation.<String>getArgument(0)).toArray(new String[0]);
135                         }
136                 });
137                 when(httpRequest.isPartSet(anyString())).thenAnswer(new Answer<Boolean>() {
138                         @Override
139                         public Boolean answer(InvocationOnMock invocation) throws Throwable {
140                                 return requestParts.get(invocation.<String>getArgument(0)) != null;
141                         }
142                 });
143                 when(httpRequest.getParts()).thenAnswer(new Answer<String[]>() {
144                         @Override
145                         public String[] answer(InvocationOnMock invocation) throws Throwable {
146                                 return requestParts.keySet().toArray(new String[requestParts.size()]);
147                         }
148                 });
149                 when(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).thenAnswer(new Answer<String>() {
150                         @Override
151                         public String answer(InvocationOnMock invocation) throws Throwable {
152                                 String parameter = invocation.getArgument(0);
153                                 int maxLength = invocation.getArgument(1);
154                                 String value = requestParts.get(parameter);
155                                 return requestParts.containsKey(parameter) ? value.substring(0, Math.min(maxLength, value.length())) : "";
156                         }
157                 });
158                 when(httpRequest.getPartAsStringThrowing(anyString(), anyInt())).thenAnswer(new Answer<String>() {
159                         @Override
160                         public String answer(InvocationOnMock invocation) throws Throwable {
161                                 String partName = invocation.getArgument(0);
162                                 if (!requestParts.containsKey(partName)) throw new NoSuchElementException();
163                                 String partValue = requestParts.get(partName);
164                                 if (partValue.length() > invocation.<Integer>getArgument(1)) throw new SizeLimitExceededException();
165                                 return partValue;
166                         }
167                 });
168                 when(httpRequest.hasParameters()).thenAnswer(new Answer<Boolean>() {
169                         @Override
170                         public Boolean answer(InvocationOnMock invocation) throws Throwable {
171                                 return !requestParameters.isEmpty();
172                         }
173                 });
174                 when(httpRequest.getParameterNames()).thenAnswer(new Answer<Collection<String>>() {
175                         @Override
176                         public Collection<String> answer(InvocationOnMock invocation) throws Throwable {
177                                 return requestParameters.keySet();
178                         }
179                 });
180                 when(httpRequest.getParam(anyString())).thenAnswer(new Answer<String>() {
181                         @Override
182                         public String answer(InvocationOnMock invocation) throws Throwable {
183                                 String parameter = invocation.getArgument(0);
184                                 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : "";
185                         }
186                 });
187                 when(httpRequest.getParam(anyString(), ArgumentMatchers.<String>any())).thenAnswer(new Answer<String>() {
188                         @Override
189                         public String answer(InvocationOnMock invocation) throws Throwable {
190                                 String parameter = invocation.getArgument(0);
191                                 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : invocation.<String>getArgument(1);
192                         }
193                 });
194                 when(httpRequest.isParameterSet(anyString())).thenAnswer(new Answer<Boolean>() {
195                         @Override
196                         public Boolean answer(InvocationOnMock invocation) throws Throwable {
197                                 return requestParameters.containsKey(invocation.<String>getArgument(0)) &&
198                                                 requestParameters.get(invocation.<String>getArgument(0)).iterator().next() != null;
199                         }
200                 });
201                 when(httpRequest.getHeader(anyString())).thenAnswer(new Answer<String>() {
202                         @Override
203                         public String answer(InvocationOnMock invocation) throws Throwable {
204                                 return requestHeaders.get(invocation.<String>getArgument(0).toLowerCase());
205                         }
206                 });
207                 when(httpRequest.getUploadedFile(anyString())).thenAnswer(new Answer<HTTPUploadedFile>() {
208                         @Override
209                         public HTTPUploadedFile answer(InvocationOnMock invocation) throws Throwable {
210                                 final String name = invocation.getArgument(0);
211                                 if (!uploadedFilesSources.containsKey(name)) {
212                                         return null;
213                                 }
214                                 return new HTTPUploadedFile() {
215                                         @Override
216                                         public String getContentType() {
217                                                 return uploadedFilesContentTypes.get(name);
218                                         }
219
220                                         @Override
221                                         public Bucket getData() {
222                                                 try (InputStream inputStream = getClass().getResourceAsStream(uploadedFilesSources.get(name))) {
223                                                         byte[] bytes = ByteStreams.toByteArray(inputStream);
224                                                         return new SimpleReadOnlyArrayBucket(bytes, 0, bytes.length);
225                                                 } catch (IOException ioe1) {
226                                                         return new NullBucket();
227                                                 }
228                                         }
229
230                                         @Override
231                                         public String getFilename() {
232                                                 return uploadedFilesNames.get(name);
233                                         }
234                                 };
235                         }
236                 });
237         }
238
239         @Before
240         public final void setupCore() {
241                 UpdateChecker updateChecker = mock(UpdateChecker.class);
242                 when(core.getUpdateChecker()).thenReturn(updateChecker);
243                 when(core.getPreferences()).thenReturn(new Preferences(eventBus));
244                 when(core.getLocalSone(anyString())).thenReturn(null);
245                 when(core.getLocalSones()).thenReturn(localSones);
246                 when(core.getSone(anyString())).thenReturn(Optional.<Sone>absent());
247                 when(core.getSones()).thenAnswer(new Answer<Collection<Sone>>() {
248                         @Override
249                         public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
250                                 return sones.values();
251                         }
252                 });
253                 when(core.getSone(anyString())).thenAnswer(new Answer<Optional<Sone>>() {
254                         @Override
255                         public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
256                                 return Optional.fromNullable(sones.get(invocation.getArgument(0)));
257                         }
258                 });
259                 when(core.getPost(anyString())).thenReturn(Optional.<Post>absent());
260                 when(core.getPostReply(anyString())).thenReturn(Optional.<PostReply>absent());
261                 when(core.getReplies(anyString())).thenAnswer(new Answer<List<PostReply>>() {
262                         @Override
263                         public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
264                                 return postReplies.get(invocation.<String>getArgument(0));
265                         }
266                 });
267                 when(core.getAlbum(anyString())).thenReturn(null);
268                 when(core.getImage(anyString())).thenReturn(null);
269                 when(core.getImage(anyString(), anyBoolean())).thenReturn(null);
270                 when(core.getTemporaryImage(anyString())).thenReturn(null);
271         }
272
273         @Before
274         public void setupL10n() {
275                 when(l10n.getString(anyString())).thenAnswer(new Answer<String>() {
276                         @Override
277                         public String answer(InvocationOnMock invocation) throws Throwable {
278                                 return invocation.getArgument(0);
279                         }
280                 });
281         }
282
283         @Before
284         public final void setupIdentityManager() {
285                 when(core.getIdentityManager().getAllOwnIdentities()).thenReturn(ownIdentities);
286         }
287
288         @Before
289         public final void setupWebInterface() {
290                 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(currentSone);
291                 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(currentSone);
292                 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(currentSone);
293                 when(webInterface.getNotification(anyString())).thenReturn(Optional.<Notification>absent());
294                 when(webInterface.getNotifications(Mockito.<Sone>any())).thenReturn(new ArrayList<Notification>());
295         }
296
297         @Before
298         public void setupSone() {
299                 when(currentSone.getOptions()).thenReturn(new DefaultSoneOptions());
300         }
301
302         protected SoneTemplatePage getPage() {
303                 return null;
304         }
305
306         protected void unsetCurrentSone() {
307                 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(null);
308                 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(null);
309                 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(null);
310         }
311
312         protected void setMethod(Method method) {
313                 when(freenetRequest.getMethod()).thenReturn(method);
314                 when(httpRequest.getMethod()).thenReturn(method.name());
315         }
316
317         protected void request(String uri, Method method) {
318                 try {
319                         when(httpRequest.getPath()).thenReturn(uri);
320                         when(freenetRequest.getUri()).thenReturn(new URI(uri));
321                 } catch (URISyntaxException e) {
322                         throw new RuntimeException(e);
323                 }
324                 when(freenetRequest.getMethod()).thenReturn(method);
325                 when(httpRequest.getMethod()).thenReturn(method.name());
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 }