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