1 package net.pterodactylus.sone.web;
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.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;
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;
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;
74 * Base class for web page tests.
76 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
78 public abstract class WebPageTest {
81 public final ExpectedException expectedException = ExpectedException.none();
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();
89 protected final Sone currentSone = mock(Sone.class);
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);
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();
109 protected final Injector injector = Guice.createInjector(
110 supply(WebInterface.class).byInstance(webInterface),
111 supply(Template.class).byInstance(template)
114 protected WebPageTest() {
116 responseInputStream = new PipedInputStream(responseOutputStream);
117 } catch (IOException e) {
118 throw new RuntimeException(e);
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[]>() {
128 public String[] answer(InvocationOnMock invocation) throws Throwable {
129 return requestParameters.get(invocation.<String>getArgument(0)).toArray(new String[0]);
132 when(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).thenAnswer(new Answer<String>() {
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())) : "";
141 when(httpRequest.hasParameters()).thenAnswer(new Answer<Boolean>() {
143 public Boolean answer(InvocationOnMock invocation) throws Throwable {
144 return !requestParameters.isEmpty();
147 when(httpRequest.getParameterNames()).thenAnswer(new Answer<Collection<String>>() {
149 public Collection<String> answer(InvocationOnMock invocation) throws Throwable {
150 return requestParameters.keySet();
153 when(httpRequest.getParam(anyString())).thenAnswer(new Answer<String>() {
155 public String answer(InvocationOnMock invocation) throws Throwable {
156 String parameter = invocation.getArgument(0);
157 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : "";
160 when(httpRequest.getParam(anyString(), ArgumentMatchers.<String>any())).thenAnswer(new Answer<String>() {
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);
167 when(httpRequest.isParameterSet(anyString())).thenAnswer(new Answer<Boolean>() {
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;
174 when(httpRequest.isPartSet(anyString())).thenAnswer(new Answer<Boolean>() {
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;
181 when(httpRequest.getParts()).thenAnswer(new Answer<String[]>() {
183 public String[] answer(InvocationOnMock invocation) throws Throwable {
184 return requestParameters.keySet().toArray(new String[requestParameters.size()]);
187 when(httpRequest.getHeader(anyString())).thenAnswer(new Answer<String>() {
189 public String answer(InvocationOnMock invocation) throws Throwable {
190 return requestHeaders.get(invocation.<String>getArgument(0).toLowerCase());
193 when(httpRequest.getUploadedFile(anyString())).thenAnswer(new Answer<HTTPUploadedFile>() {
195 public HTTPUploadedFile answer(InvocationOnMock invocation) throws Throwable {
196 final String name = invocation.getArgument(0);
197 if (!uploadedFilesSources.containsKey(name)) {
200 return new HTTPUploadedFile() {
202 public String getContentType() {
203 return uploadedFilesContentTypes.get(name);
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();
217 public String getFilename() {
218 return uploadedFilesNames.get(name);
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>>() {
235 public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
236 return sones.values();
239 when(core.getSone(anyString())).thenAnswer(new Answer<Optional<Sone>>() {
241 public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
242 return Optional.fromNullable(sones.get(invocation.getArgument(0)));
245 when(core.getPost(anyString())).thenReturn(Optional.<Post>absent());
246 when(core.getPostReply(anyString())).thenReturn(Optional.<PostReply>absent());
247 when(core.getReplies(anyString())).thenAnswer(new Answer<List<PostReply>>() {
249 public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
250 return postReplies.get(invocation.<String>getArgument(0));
253 when(core.getAlbum(anyString())).thenReturn(null);
254 when(core.getImage(anyString())).thenReturn(null);
255 when(core.getImage(anyString(), anyBoolean())).thenReturn(null);
256 when(core.getTemporaryImage(anyString())).thenReturn(null);
260 public void setupL10n() {
261 when(l10n.getString(anyString())).thenAnswer(new Answer<String>() {
263 public String answer(InvocationOnMock invocation) throws Throwable {
264 return invocation.getArgument(0);
270 public final void setupIdentityManager() {
271 when(core.getIdentityManager().getAllOwnIdentities()).thenReturn(ownIdentities);
275 public final void setupWebInterface() {
276 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(currentSone);
277 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(currentSone);
278 when(webInterface.getNotification(anyString())).thenReturn(Optional.<Notification>absent());
279 when(webInterface.getNotifications(currentSone)).thenReturn(new ArrayList<Notification>());
283 public void setupSone() {
284 when(currentSone.getOptions()).thenReturn(new DefaultSoneOptions());
287 protected SoneTemplatePage getPage() {
291 protected void unsetCurrentSone() {
292 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(null);
293 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(null);
296 protected void request(String uri, Method method) {
298 when(httpRequest.getPath()).thenReturn(uri);
299 when(freenetRequest.getUri()).thenReturn(new URI(uri));
300 } catch (URISyntaxException e) {
301 throw new RuntimeException(e);
303 when(freenetRequest.getMethod()).thenReturn(method);
306 protected void addHttpRequestHeader(@Nonnull String name, String value) {
307 requestHeaders.put(name.toLowerCase(), value);
310 protected void addHttpRequestParameter(String name, final String value) {
311 requestParameters.put(name, value);
314 protected void addPost(String postId, Post post) {
315 when(core.getPost(postId)).thenReturn(Optional.fromNullable(post));
318 protected void addPostReply(String postReplyId, PostReply postReply) {
319 if (postReply.getPostId() != null) {
320 postReplies.put(postReply.getPostId(), postReply);
322 when(core.getPostReply(postReplyId)).thenReturn(Optional.fromNullable(postReply));
325 protected void addSone(String soneId, Sone sone) {
326 sones.put(soneId, sone);
329 protected void addLocalSone(String soneId, Sone sone) {
330 when(core.getLocalSone(eq(soneId))).thenReturn(sone);
331 localSones.add(sone);
334 protected void addOwnIdentity(OwnIdentity ownIdentity) {
335 ownIdentities.add(ownIdentity);
338 protected void addAlbum(String albumId, Album album) {
339 when(core.getAlbum(eq(albumId))).thenReturn(album);
342 protected void addImage(String imageId, Image image) {
343 when(core.getImage(eq(imageId))).thenReturn(image);
344 when(core.getImage(eq(imageId), anyBoolean())).thenReturn(image);
347 protected void addTemporaryImage(String imageId, TemporaryImage temporaryImage) {
348 when(core.getTemporaryImage(eq(imageId))).thenReturn(temporaryImage);
351 protected void addUploadedFile(@Nonnull String name, @Nonnull String filename, @Nonnull String contentType, @Nonnull String resource) {
352 uploadedFilesNames.put(name, filename);
353 uploadedFilesContentTypes.put(name, contentType);
354 uploadedFilesSources.put(name, resource);
357 protected byte[] getResponseBytes() throws IOException {
358 response.getContent().close();
359 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
360 ByteStreams.copy(responseInputStream, outputStream);
361 return outputStream.toByteArray();
365 protected void addNotification(String notificationId, Notification notification) {
366 when(webInterface.getNotification(eq(notificationId))).thenReturn(Optional.of(notification));
369 protected void verifyRedirect(String target) throws RedirectException {
370 expectedException.expect(redirectsTo(target));
371 getPage().handleRequest(freenetRequest, templateContext);
374 protected void verifyRedirect(String target, Runnable verification) throws RedirectException {
375 expectedException.expect(redirectsTo(target));
377 getPage().handleRequest(freenetRequest, templateContext);