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 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;
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;
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;
29 import javax.annotation.Nonnull;
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;
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;
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;
75 * Base class for web page tests.
77 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
79 public abstract class WebPageTest {
82 public final ExpectedException expectedException = ExpectedException.none();
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();
90 protected final Sone currentSone = mock(Sone.class);
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);
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();
110 protected final Injector injector = Guice.createInjector(
111 supply(WebInterface.class).byInstance(webInterface),
112 supply(Template.class).byInstance(template)
115 protected WebPageTest() {
117 responseInputStream = new PipedInputStream(responseOutputStream);
118 } catch (IOException e) {
119 throw new RuntimeException(e);
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[]>() {
129 public String[] answer(InvocationOnMock invocation) throws Throwable {
130 return requestParameters.get(invocation.<String>getArgument(0)).toArray(new String[0]);
133 when(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).thenAnswer(new Answer<String>() {
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())) : "";
142 when(httpRequest.hasParameters()).thenAnswer(new Answer<Boolean>() {
144 public Boolean answer(InvocationOnMock invocation) throws Throwable {
145 return !requestParameters.isEmpty();
148 when(httpRequest.getParameterNames()).thenAnswer(new Answer<Collection<String>>() {
150 public Collection<String> answer(InvocationOnMock invocation) throws Throwable {
151 return requestParameters.keySet();
154 when(httpRequest.getParam(anyString())).thenAnswer(new Answer<String>() {
156 public String answer(InvocationOnMock invocation) throws Throwable {
157 String parameter = invocation.getArgument(0);
158 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : "";
161 when(httpRequest.getParam(anyString(), ArgumentMatchers.<String>any())).thenAnswer(new Answer<String>() {
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);
168 when(httpRequest.isParameterSet(anyString())).thenAnswer(new Answer<Boolean>() {
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;
175 when(httpRequest.isPartSet(anyString())).thenAnswer(new Answer<Boolean>() {
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;
182 when(httpRequest.getParts()).thenAnswer(new Answer<String[]>() {
184 public String[] answer(InvocationOnMock invocation) throws Throwable {
185 return requestParameters.keySet().toArray(new String[requestParameters.size()]);
188 when(httpRequest.getHeader(anyString())).thenAnswer(new Answer<String>() {
190 public String answer(InvocationOnMock invocation) throws Throwable {
191 return requestHeaders.get(invocation.<String>getArgument(0).toLowerCase());
194 when(httpRequest.getUploadedFile(anyString())).thenAnswer(new Answer<HTTPUploadedFile>() {
196 public HTTPUploadedFile answer(InvocationOnMock invocation) throws Throwable {
197 final String name = invocation.getArgument(0);
198 if (!uploadedFilesSources.containsKey(name)) {
201 return new HTTPUploadedFile() {
203 public String getContentType() {
204 return uploadedFilesContentTypes.get(name);
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();
218 public String getFilename() {
219 return uploadedFilesNames.get(name);
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>>() {
236 public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
237 return sones.values();
240 when(core.getSone(anyString())).thenAnswer(new Answer<Optional<Sone>>() {
242 public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
243 return Optional.fromNullable(sones.get(invocation.getArgument(0)));
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>>() {
250 public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
251 return postReplies.get(invocation.<String>getArgument(0));
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);
261 public void setupL10n() {
262 when(l10n.getString(anyString())).thenAnswer(new Answer<String>() {
264 public String answer(InvocationOnMock invocation) throws Throwable {
265 return invocation.getArgument(0);
271 public final void setupIdentityManager() {
272 when(core.getIdentityManager().getAllOwnIdentities()).thenReturn(ownIdentities);
276 public final void setupWebInterface() {
277 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(currentSone);
278 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(currentSone);
279 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(currentSone);
280 when(webInterface.getNotification(anyString())).thenReturn(Optional.<Notification>absent());
281 when(webInterface.getNotifications(currentSone)).thenReturn(new ArrayList<Notification>());
285 public void setupSone() {
286 when(currentSone.getOptions()).thenReturn(new DefaultSoneOptions());
289 protected SoneTemplatePage getPage() {
293 protected void unsetCurrentSone() {
294 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(null);
295 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(null);
296 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(null);
299 protected void request(String uri, Method method) {
301 when(httpRequest.getPath()).thenReturn(uri);
302 when(freenetRequest.getUri()).thenReturn(new URI(uri));
303 } catch (URISyntaxException e) {
304 throw new RuntimeException(e);
306 when(freenetRequest.getMethod()).thenReturn(method);
309 protected void addHttpRequestHeader(@Nonnull String name, String value) {
310 requestHeaders.put(name.toLowerCase(), value);
313 protected void addHttpRequestParameter(String name, final String value) {
314 requestParameters.put(name, value);
317 protected void addPost(String postId, Post post) {
318 when(core.getPost(postId)).thenReturn(Optional.fromNullable(post));
321 protected void addPostReply(String postReplyId, PostReply postReply) {
322 if (postReply.getPostId() != null) {
323 postReplies.put(postReply.getPostId(), postReply);
325 when(core.getPostReply(postReplyId)).thenReturn(Optional.fromNullable(postReply));
328 protected void addSone(String soneId, Sone sone) {
329 sones.put(soneId, sone);
332 protected void addLocalSone(String soneId, Sone sone) {
333 when(core.getLocalSone(eq(soneId))).thenReturn(sone);
334 localSones.add(sone);
337 protected void addOwnIdentity(OwnIdentity ownIdentity) {
338 ownIdentities.add(ownIdentity);
341 protected void addAlbum(String albumId, Album album) {
342 when(core.getAlbum(eq(albumId))).thenReturn(album);
345 protected void addImage(String imageId, Image image) {
346 when(core.getImage(eq(imageId))).thenReturn(image);
347 when(core.getImage(eq(imageId), anyBoolean())).thenReturn(image);
350 protected void addTemporaryImage(String imageId, TemporaryImage temporaryImage) {
351 when(core.getTemporaryImage(eq(imageId))).thenReturn(temporaryImage);
354 protected void addUploadedFile(@Nonnull String name, @Nonnull String filename, @Nonnull String contentType, @Nonnull String resource) {
355 uploadedFilesNames.put(name, filename);
356 uploadedFilesContentTypes.put(name, contentType);
357 uploadedFilesSources.put(name, resource);
360 protected byte[] getResponseBytes() throws IOException {
361 response.getContent().close();
362 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
363 ByteStreams.copy(responseInputStream, outputStream);
364 return outputStream.toByteArray();
368 protected void addNotification(String notificationId, Notification notification) {
369 when(webInterface.getNotification(eq(notificationId))).thenReturn(Optional.of(notification));
372 protected void verifyRedirect(String target) throws RedirectException {
373 expectedException.expect(redirectsTo(target));
374 getPage().handleRequest(freenetRequest, templateContext);
377 protected void verifyRedirect(String target, Runnable verification) throws RedirectException {
378 expectedException.expect(redirectsTo(target));
380 getPage().handleRequest(freenetRequest, templateContext);