1 package net.pterodactylus.sone.web.pages;
3 import static net.pterodactylus.sone.test.GuiceKt.supply;
4 import static net.pterodactylus.sone.web.WebTestUtils.redirectsTo;
5 import static net.pterodactylus.util.web.Method.GET;
6 import static org.junit.Assert.fail;
7 import static org.mockito.ArgumentMatchers.anyBoolean;
8 import static org.mockito.ArgumentMatchers.anyInt;
9 import static org.mockito.ArgumentMatchers.anyString;
10 import static org.mockito.ArgumentMatchers.eq;
11 import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
12 import static org.mockito.Mockito.mock;
13 import static org.mockito.Mockito.when;
15 import java.io.ByteArrayOutputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.io.PipedInputStream;
19 import java.io.PipedOutputStream;
21 import java.net.URISyntaxException;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
28 import java.util.NoSuchElementException;
31 import javax.annotation.Nonnull;
32 import javax.naming.SizeLimitExceededException;
34 import net.pterodactylus.sone.core.Core;
35 import net.pterodactylus.sone.core.Preferences;
36 import net.pterodactylus.sone.core.UpdateChecker;
37 import net.pterodactylus.sone.data.Album;
38 import net.pterodactylus.sone.data.Image;
39 import net.pterodactylus.sone.data.Post;
40 import net.pterodactylus.sone.data.PostReply;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.data.SoneOptions.DefaultSoneOptions;
43 import net.pterodactylus.sone.data.TemporaryImage;
44 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
45 import net.pterodactylus.sone.web.WebInterface;
46 import net.pterodactylus.sone.web.page.FreenetRequest;
47 import net.pterodactylus.sone.web.page.FreenetTemplatePage.RedirectException;
48 import net.pterodactylus.util.notify.Notification;
49 import net.pterodactylus.util.template.Template;
50 import net.pterodactylus.util.template.TemplateContext;
51 import net.pterodactylus.util.web.Method;
52 import net.pterodactylus.util.web.Response;
54 import freenet.clients.http.ToadletContext;
55 import freenet.l10n.BaseL10n;
56 import freenet.support.SimpleReadOnlyArrayBucket;
57 import freenet.support.api.Bucket;
58 import freenet.support.api.HTTPRequest;
59 import freenet.support.api.HTTPUploadedFile;
60 import freenet.support.io.NullBucket;
62 import com.google.common.base.Optional;
63 import com.google.common.collect.ArrayListMultimap;
64 import com.google.common.collect.ListMultimap;
65 import com.google.common.collect.Multimap;
66 import com.google.common.eventbus.EventBus;
67 import com.google.common.io.ByteStreams;
68 import com.google.inject.Guice;
69 import com.google.inject.Injector;
70 import org.junit.Before;
71 import org.junit.Rule;
72 import org.junit.rules.ExpectedException;
73 import org.mockito.ArgumentMatchers;
74 import org.mockito.Mockito;
75 import org.mockito.invocation.InvocationOnMock;
76 import org.mockito.stubbing.Answer;
79 * Base class for web page tests.
81 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
83 public abstract class WebPageTest {
86 public final ExpectedException expectedException = ExpectedException.none();
88 protected final Template template = new Template();
89 protected final WebInterface webInterface = mock(WebInterface.class, RETURNS_DEEP_STUBS);
90 protected final EventBus eventBus = mock(EventBus.class);
91 protected final Core core = webInterface.getCore();
92 protected final BaseL10n l10n = webInterface.getL10n();
94 protected final Sone currentSone = mock(Sone.class);
96 protected final TemplateContext templateContext = new TemplateContext();
97 protected final HTTPRequest httpRequest = mock(HTTPRequest.class);
98 protected final Multimap<String, String> requestParameters = ArrayListMultimap.create();
99 protected final Map<String, String> requestParts = new HashMap<>();
100 protected final Map<String, String> requestHeaders = new HashMap<>();
101 private final Map<String, String> uploadedFilesNames = new HashMap<>();
102 private final Map<String, String> uploadedFilesContentTypes = new HashMap<>();
103 private final Map<String, String> uploadedFilesSources = new HashMap<>();
104 protected final FreenetRequest freenetRequest = mock(FreenetRequest.class);
105 private final PipedOutputStream responseOutputStream = new PipedOutputStream();
106 private final PipedInputStream responseInputStream;
107 protected final Response response = new Response(responseOutputStream);
108 protected final ToadletContext toadletContext = mock(ToadletContext.class);
110 private final Set<OwnIdentity> ownIdentities = new HashSet<>();
111 private final Map<String, Sone> sones = new HashMap<>();
112 protected final List<Sone> localSones = new ArrayList<>();
113 private final ListMultimap<String, PostReply> postReplies = ArrayListMultimap.create();
115 protected final Injector injector = Guice.createInjector(
116 supply(WebInterface.class).byInstance(webInterface),
117 supply(Template.class).byInstance(template)
120 protected WebPageTest() {
122 responseInputStream = new PipedInputStream(responseOutputStream);
123 } catch (IOException e) {
124 throw new RuntimeException(e);
129 public final void setupFreenetRequest() throws SizeLimitExceededException {
131 when(freenetRequest.getToadletContext()).thenReturn(toadletContext);
132 when(freenetRequest.getHttpRequest()).thenReturn(httpRequest);
133 when(httpRequest.getMultipleParam(anyString())).thenAnswer(new Answer<String[]>() {
135 public String[] answer(InvocationOnMock invocation) throws Throwable {
136 return requestParameters.get(invocation.<String>getArgument(0)).toArray(new String[0]);
139 when(httpRequest.isPartSet(anyString())).thenAnswer(new Answer<Boolean>() {
141 public Boolean answer(InvocationOnMock invocation) throws Throwable {
142 return requestParts.get(invocation.<String>getArgument(0)) != null;
145 when(httpRequest.getParts()).thenAnswer(new Answer<String[]>() {
147 public String[] answer(InvocationOnMock invocation) throws Throwable {
148 return requestParts.keySet().toArray(new String[requestParts.size()]);
151 when(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).thenAnswer(new Answer<String>() {
153 public String answer(InvocationOnMock invocation) throws Throwable {
154 String parameter = invocation.getArgument(0);
155 int maxLength = invocation.getArgument(1);
156 String value = requestParts.get(parameter);
157 return requestParts.containsKey(parameter) ? value.substring(0, Math.min(maxLength, value.length())) : "";
160 when(httpRequest.getPartAsStringThrowing(anyString(), anyInt())).thenAnswer(new Answer<String>() {
162 public String answer(InvocationOnMock invocation) throws Throwable {
163 String partName = invocation.getArgument(0);
164 if (!requestParts.containsKey(partName)) throw new NoSuchElementException();
165 String partValue = requestParts.get(partName);
166 if (partValue.length() > invocation.<Integer>getArgument(1)) throw new SizeLimitExceededException();
170 when(httpRequest.hasParameters()).thenAnswer(new Answer<Boolean>() {
172 public Boolean answer(InvocationOnMock invocation) throws Throwable {
173 return !requestParameters.isEmpty();
176 when(httpRequest.getParameterNames()).thenAnswer(new Answer<Collection<String>>() {
178 public Collection<String> answer(InvocationOnMock invocation) throws Throwable {
179 return requestParameters.keySet();
182 when(httpRequest.getParam(anyString())).thenAnswer(new Answer<String>() {
184 public String answer(InvocationOnMock invocation) throws Throwable {
185 String parameter = invocation.getArgument(0);
186 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : "";
189 when(httpRequest.getParam(anyString(), ArgumentMatchers.<String>any())).thenAnswer(new Answer<String>() {
191 public String answer(InvocationOnMock invocation) throws Throwable {
192 String parameter = invocation.getArgument(0);
193 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : invocation.<String>getArgument(1);
196 when(httpRequest.isParameterSet(anyString())).thenAnswer(new Answer<Boolean>() {
198 public Boolean answer(InvocationOnMock invocation) throws Throwable {
199 return requestParameters.containsKey(invocation.<String>getArgument(0)) &&
200 requestParameters.get(invocation.<String>getArgument(0)).iterator().next() != null;
203 when(httpRequest.getHeader(anyString())).thenAnswer(new Answer<String>() {
205 public String answer(InvocationOnMock invocation) throws Throwable {
206 return requestHeaders.get(invocation.<String>getArgument(0).toLowerCase());
209 when(httpRequest.getUploadedFile(anyString())).thenAnswer(new Answer<HTTPUploadedFile>() {
211 public HTTPUploadedFile answer(InvocationOnMock invocation) throws Throwable {
212 final String name = invocation.getArgument(0);
213 if (!uploadedFilesSources.containsKey(name)) {
216 return new HTTPUploadedFile() {
218 public String getContentType() {
219 return uploadedFilesContentTypes.get(name);
223 public Bucket getData() {
224 try (InputStream inputStream = getClass().getResourceAsStream(uploadedFilesSources.get(name))) {
225 byte[] bytes = ByteStreams.toByteArray(inputStream);
226 return new SimpleReadOnlyArrayBucket(bytes, 0, bytes.length);
227 } catch (IOException ioe1) {
228 return new NullBucket();
233 public String getFilename() {
234 return uploadedFilesNames.get(name);
242 public final void setupCore() {
243 UpdateChecker updateChecker = mock(UpdateChecker.class);
244 when(core.getUpdateChecker()).thenReturn(updateChecker);
245 when(core.getPreferences()).thenReturn(new Preferences(eventBus));
246 when(core.getLocalSone(anyString())).thenReturn(null);
247 when(core.getLocalSones()).thenReturn(localSones);
248 when(core.getSone(anyString())).thenReturn(Optional.<Sone>absent());
249 when(core.getSones()).thenAnswer(new Answer<Collection<Sone>>() {
251 public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
252 return sones.values();
255 when(core.getSone(anyString())).thenAnswer(new Answer<Optional<Sone>>() {
257 public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
258 return Optional.fromNullable(sones.get(invocation.getArgument(0)));
261 when(core.getPost(anyString())).thenReturn(Optional.<Post>absent());
262 when(core.getPostReply(anyString())).thenReturn(Optional.<PostReply>absent());
263 when(core.getReplies(anyString())).thenAnswer(new Answer<List<PostReply>>() {
265 public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
266 return postReplies.get(invocation.<String>getArgument(0));
269 when(core.getAlbum(anyString())).thenReturn(null);
270 when(core.getImage(anyString())).thenReturn(null);
271 when(core.getImage(anyString(), anyBoolean())).thenReturn(null);
272 when(core.getTemporaryImage(anyString())).thenReturn(null);
276 public void setupL10n() {
277 when(l10n.getString(anyString())).thenAnswer(new Answer<String>() {
279 public String answer(InvocationOnMock invocation) throws Throwable {
280 return invocation.getArgument(0);
286 public final void setupIdentityManager() {
287 when(core.getIdentityManager().getAllOwnIdentities()).thenReturn(ownIdentities);
291 public final void setupWebInterface() {
292 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(currentSone);
293 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(currentSone);
294 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(currentSone);
295 when(webInterface.getNotification(anyString())).thenReturn(Optional.<Notification>absent());
296 when(webInterface.getNotifications(Mockito.<Sone>any())).thenReturn(new ArrayList<Notification>());
300 public void setupSone() {
301 when(currentSone.getOptions()).thenReturn(new DefaultSoneOptions());
304 protected SoneTemplatePage getPage() {
308 protected void unsetCurrentSone() {
309 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(null);
310 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(null);
311 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(null);
314 protected void setMethod(Method method) {
315 when(freenetRequest.getMethod()).thenReturn(method);
316 when(httpRequest.getMethod()).thenReturn(method.name());
319 protected void request(String uri) {
321 when(httpRequest.getPath()).thenReturn(uri);
322 when(freenetRequest.getUri()).thenReturn(new URI(uri));
323 } catch (URISyntaxException e) {
324 throw new RuntimeException(e);
328 protected void addHttpRequestHeader(@Nonnull String name, String value) {
329 requestHeaders.put(name.toLowerCase(), value);
332 protected void addHttpRequestParameter(String name, final String value) {
333 requestParameters.put(name, value);
336 protected void addHttpRequestPart(String name, String value) {
337 requestParts.put(name, value);
340 protected void addPost(String postId, Post post) {
341 when(core.getPost(postId)).thenReturn(Optional.fromNullable(post));
344 protected void addPostReply(String postReplyId, PostReply postReply) {
345 if (postReply.getPostId() != null) {
346 postReplies.put(postReply.getPostId(), postReply);
348 when(core.getPostReply(postReplyId)).thenReturn(Optional.fromNullable(postReply));
351 protected void addSone(String soneId, Sone sone) {
352 sones.put(soneId, sone);
355 protected void addLocalSone(String soneId, Sone sone) {
356 when(core.getLocalSone(eq(soneId))).thenReturn(sone);
357 localSones.add(sone);
360 protected void addOwnIdentity(OwnIdentity ownIdentity) {
361 ownIdentities.add(ownIdentity);
364 protected void addAlbum(String albumId, Album album) {
365 when(core.getAlbum(eq(albumId))).thenReturn(album);
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);
373 protected void addTemporaryImage(String imageId, TemporaryImage temporaryImage) {
374 when(core.getTemporaryImage(eq(imageId))).thenReturn(temporaryImage);
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);
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();
391 protected void addNotification(String notificationId, Notification notification) {
392 when(webInterface.getNotification(eq(notificationId))).thenReturn(Optional.of(notification));
395 protected void verifyRedirect(String target) throws RedirectException {
396 expectedException.expect(redirectsTo(target));
397 getPage().handleRequest(freenetRequest, templateContext);
400 protected void verifyRedirect(String target, Runnable verification) throws RedirectException {
401 expectedException.expect(redirectsTo(target));
403 getPage().handleRequest(freenetRequest, templateContext);
410 protected void verifyNoRedirect(Runnable verification) throws RedirectException {
411 getPage().handleRequest(freenetRequest, templateContext);
415 protected void addTranslation(@Nonnull String key, @Nonnull String value) {
416 when(l10n.getString(key)).thenReturn(value);