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