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