Rename session-related Methode in web interface
[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.isPartSet(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.getParts()).thenAnswer(new Answer<String[]>() {
175                         @Override
176                         public String[] answer(InvocationOnMock invocation) throws Throwable {
177                                 return requestParameters.keySet().toArray(new String[requestParameters.size()]);
178                         }
179                 });
180                 when(httpRequest.getHeader(anyString())).thenAnswer(new Answer<String>() {
181                         @Override
182                         public String answer(InvocationOnMock invocation) throws Throwable {
183                                 return requestHeaders.get(invocation.<String>getArgument(0).toLowerCase());
184                         }
185                 });
186                 when(httpRequest.getUploadedFile(anyString())).thenAnswer(new Answer<HTTPUploadedFile>() {
187                         @Override
188                         public HTTPUploadedFile answer(InvocationOnMock invocation) throws Throwable {
189                                 final String name = invocation.getArgument(0);
190                                 if (!uploadedFilesSources.containsKey(name)) {
191                                         return null;
192                                 }
193                                 return new HTTPUploadedFile() {
194                                         @Override
195                                         public String getContentType() {
196                                                 return uploadedFilesContentTypes.get(name);
197                                         }
198
199                                         @Override
200                                         public Bucket getData() {
201                                                 try (InputStream inputStream = getClass().getResourceAsStream(uploadedFilesSources.get(name))) {
202                                                         byte[] bytes = ByteStreams.toByteArray(inputStream);
203                                                         return new SimpleReadOnlyArrayBucket(bytes, 0, bytes.length);
204                                                 } catch (IOException ioe1) {
205                                                         return new NullBucket();
206                                                 }
207                                         }
208
209                                         @Override
210                                         public String getFilename() {
211                                                 return uploadedFilesNames.get(name);
212                                         }
213                                 };
214                         }
215                 });
216         }
217
218         @Before
219         public final void setupCore() {
220                 UpdateChecker updateChecker = mock(UpdateChecker.class);
221                 when(core.getUpdateChecker()).thenReturn(updateChecker);
222                 when(core.getPreferences()).thenReturn(new Preferences(eventBus));
223                 when(core.getLocalSone(anyString())).thenReturn(null);
224                 when(core.getLocalSones()).thenReturn(localSones);
225                 when(core.getSone(anyString())).thenReturn(Optional.<Sone>absent());
226                 when(core.getSones()).thenAnswer(new Answer<Collection<Sone>>() {
227                         @Override
228                         public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
229                                 return sones.values();
230                         }
231                 });
232                 when(core.getSone(anyString())).thenAnswer(new Answer<Optional<Sone>>() {
233                         @Override
234                         public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
235                                 return Optional.fromNullable(sones.get(invocation.getArgument(0)));
236                         }
237                 });
238                 when(core.getPost(anyString())).thenReturn(Optional.<Post>absent());
239                 when(core.getReplies(anyString())).thenAnswer(new Answer<List<PostReply>>() {
240                         @Override
241                         public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
242                                 return postReplies.get(invocation.<String>getArgument(0));
243                         }
244                 });
245                 when(core.getAlbum(anyString())).thenReturn(null);
246                 when(core.getImage(anyString())).thenReturn(null);
247                 when(core.getImage(anyString(), anyBoolean())).thenReturn(null);
248                 when(core.getTemporaryImage(anyString())).thenReturn(null);
249         }
250
251         @Before
252         public void setupL10n() {
253                 when(l10n.getString(anyString())).thenAnswer(new Answer<String>() {
254                         @Override
255                         public String answer(InvocationOnMock invocation) throws Throwable {
256                                 return invocation.getArgument(0);
257                         }
258                 });
259         }
260
261         @Before
262         public final void setupIdentityManager() {
263                 when(core.getIdentityManager().getAllOwnIdentities()).thenReturn(ownIdentities);
264         }
265
266         @Before
267         public final void setupWebInterface() {
268                 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(currentSone);
269                 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(currentSone);
270                 when(webInterface.getNotification(anyString())).thenReturn(Optional.<Notification>absent());
271                 when(webInterface.getNotifications(currentSone)).thenReturn(new ArrayList<Notification>());
272         }
273
274         @Before
275         public void setupSone() {
276                 when(currentSone.getOptions()).thenReturn(new DefaultSoneOptions());
277         }
278
279         protected SoneTemplatePage getPage() {
280                 return null;
281         }
282
283         protected void unsetCurrentSone() {
284                 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(null);
285                 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(null);
286         }
287
288         protected void request(String uri, Method method) {
289                 try {
290                         when(httpRequest.getPath()).thenReturn(uri);
291                         when(freenetRequest.getUri()).thenReturn(new URI(uri));
292                 } catch (URISyntaxException e) {
293                         throw new RuntimeException(e);
294                 }
295                 when(freenetRequest.getMethod()).thenReturn(method);
296         }
297
298         protected void addHttpRequestHeader(@Nonnull String name, String value) {
299                 requestHeaders.put(name.toLowerCase(), value);
300         }
301
302         protected void addHttpRequestParameter(String name, final String value) {
303                 requestParameters.put(name, value);
304         }
305
306         protected void addPost(String postId, Post post) {
307                 when(core.getPost(postId)).thenReturn(Optional.fromNullable(post));
308         }
309
310         protected void addPostReply(String postReplyId, PostReply postReply) {
311                 if (postReply.getPostId() != null) {
312                         postReplies.put(postReply.getPostId(), postReply);
313                 }
314                 when(core.getPostReply(postReplyId)).thenReturn(Optional.fromNullable(postReply));
315         }
316
317         protected void addSone(String soneId, Sone sone) {
318                 sones.put(soneId, sone);
319         }
320
321         protected void addLocalSone(String soneId, Sone sone) {
322                 when(core.getLocalSone(eq(soneId))).thenReturn(sone);
323                 localSones.add(sone);
324         }
325
326         protected void addOwnIdentity(OwnIdentity ownIdentity) {
327                 ownIdentities.add(ownIdentity);
328         }
329
330         protected void addAlbum(String albumId, Album album) {
331                 when(core.getAlbum(eq(albumId))).thenReturn(album);
332         }
333
334         protected void addImage(String imageId, Image image) {
335                 when(core.getImage(eq(imageId))).thenReturn(image);
336                 when(core.getImage(eq(imageId), anyBoolean())).thenReturn(image);
337         }
338
339         protected void addTemporaryImage(String imageId, TemporaryImage temporaryImage) {
340                 when(core.getTemporaryImage(eq(imageId))).thenReturn(temporaryImage);
341         }
342
343         protected void addUploadedFile(@Nonnull String name, @Nonnull String filename, @Nonnull String contentType, @Nonnull String resource) {
344                 uploadedFilesNames.put(name, filename);
345                 uploadedFilesContentTypes.put(name, contentType);
346                 uploadedFilesSources.put(name, resource);
347         }
348
349         protected byte[] getResponseBytes() throws IOException {
350                 response.getContent().close();
351                 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
352                         ByteStreams.copy(responseInputStream, outputStream);
353                         return outputStream.toByteArray();
354                 }
355         }
356
357         protected void addNotification(String notificationId, Notification notification) {
358                 when(webInterface.getNotification(eq(notificationId))).thenReturn(Optional.of(notification));
359         }
360
361         protected void verifyRedirect(String target) throws RedirectException {
362                 expectedException.expect(redirectsTo(target));
363                 getPage().handleRequest(freenetRequest, templateContext);
364         }
365
366         protected void verifyRedirect(String target, Runnable verification) throws RedirectException {
367                 expectedException.expect(redirectsTo(target));
368                 try {
369                         getPage().handleRequest(freenetRequest, templateContext);
370                         fail();
371                 } finally {
372                         verification.run();
373                 }
374         }
375
376 }