1 package net.pterodactylus.sone.web;
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;
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;
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;
28 import javax.annotation.Nonnull;
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;
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;
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;
71 * Base class for web page tests.
73 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75 public abstract class WebPageTest {
78 public final ExpectedException expectedException = ExpectedException.none();
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();
86 protected final Sone currentSone = mock(Sone.class);
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);
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();
106 protected WebPageTest() {
108 responseInputStream = new PipedInputStream(responseOutputStream);
109 } catch (IOException e) {
110 throw new RuntimeException(e);
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[]>() {
120 public String[] answer(InvocationOnMock invocation) throws Throwable {
121 return requestParameters.get(invocation.<String>getArgument(0)).toArray(new String[0]);
124 when(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).thenAnswer(new Answer<String>() {
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())) : "";
133 when(httpRequest.hasParameters()).thenAnswer(new Answer<Boolean>() {
135 public Boolean answer(InvocationOnMock invocation) throws Throwable {
136 return !requestParameters.isEmpty();
139 when(httpRequest.getParameterNames()).thenAnswer(new Answer<Collection<String>>() {
141 public Collection<String> answer(InvocationOnMock invocation) throws Throwable {
142 return requestParameters.keySet();
145 when(httpRequest.getParam(anyString())).thenAnswer(new Answer<String>() {
147 public String answer(InvocationOnMock invocation) throws Throwable {
148 String parameter = invocation.getArgument(0);
149 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : "";
152 when(httpRequest.getParam(anyString(), ArgumentMatchers.<String>any())).thenAnswer(new Answer<String>() {
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);
159 when(httpRequest.isPartSet(anyString())).thenAnswer(new Answer<Boolean>() {
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;
166 when(httpRequest.getParts()).thenAnswer(new Answer<String[]>() {
168 public String[] answer(InvocationOnMock invocation) throws Throwable {
169 return requestParameters.keySet().toArray(new String[requestParameters.size()]);
172 when(httpRequest.getHeader(anyString())).thenAnswer(new Answer<String>() {
174 public String answer(InvocationOnMock invocation) throws Throwable {
175 return requestHeaders.get(invocation.<String>getArgument(0).toLowerCase());
178 when(httpRequest.getUploadedFile(anyString())).thenAnswer(new Answer<HTTPUploadedFile>() {
180 public HTTPUploadedFile answer(InvocationOnMock invocation) throws Throwable {
181 final String name = invocation.getArgument(0);
182 if (!uploadedFilesSources.containsKey(name)) {
185 return new HTTPUploadedFile() {
187 public String getContentType() {
188 return uploadedFilesContentTypes.get(name);
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();
202 public String getFilename() {
203 return uploadedFilesNames.get(name);
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>>() {
220 public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
221 return sones.values();
224 when(core.getSone(anyString())).thenAnswer(new Answer<Optional<Sone>>() {
226 public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
227 return Optional.fromNullable(sones.get(invocation.getArgument(0)));
230 when(core.getPost(anyString())).thenReturn(Optional.<Post>absent());
231 when(core.getReplies(anyString())).thenAnswer(new Answer<List<PostReply>>() {
233 public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
234 return postReplies.get(invocation.<String>getArgument(0));
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);
244 public void setupL10n() {
245 when(l10n.getString(anyString())).thenAnswer(new Answer<String>() {
247 public String answer(InvocationOnMock invocation) throws Throwable {
248 return invocation.getArgument(0);
254 public final void setupIdentityManager() {
255 when(core.getIdentityManager().getAllOwnIdentities()).thenReturn(ownIdentities);
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>());
267 public void setupSone() {
268 when(currentSone.getOptions()).thenReturn(new DefaultSoneOptions());
271 protected SoneTemplatePage getPage() {
275 protected void unsetCurrentSone() {
276 when(webInterface.getCurrentSone(toadletContext)).thenReturn(null);
277 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(null);
280 protected void request(String uri, Method method) {
282 when(httpRequest.getPath()).thenReturn(uri);
283 when(freenetRequest.getUri()).thenReturn(new URI(uri));
284 } catch (URISyntaxException e) {
285 throw new RuntimeException(e);
287 when(freenetRequest.getMethod()).thenReturn(method);
290 protected void addHttpRequestHeader(@Nonnull String name, String value) {
291 requestHeaders.put(name.toLowerCase(), value);
294 protected void addHttpRequestParameter(String name, final String value) {
295 requestParameters.put(name, value);
298 protected void addPost(String postId, Post post) {
299 when(core.getPost(postId)).thenReturn(Optional.fromNullable(post));
302 protected void addPostReply(String postReplyId, PostReply postReply) {
303 if (postReply.getPostId() != null) {
304 postReplies.put(postReply.getPostId(), postReply);
306 when(core.getPostReply(postReplyId)).thenReturn(Optional.fromNullable(postReply));
309 protected void addSone(String soneId, Sone sone) {
310 sones.put(soneId, sone);
313 protected void addLocalSone(String soneId, Sone sone) {
314 when(core.getLocalSone(eq(soneId))).thenReturn(sone);
315 localSones.add(sone);
318 protected void addOwnIdentity(OwnIdentity ownIdentity) {
319 ownIdentities.add(ownIdentity);
322 protected void addAlbum(String albumId, Album album) {
323 when(core.getAlbum(eq(albumId))).thenReturn(album);
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);
331 protected void addTemporaryImage(String imageId, TemporaryImage temporaryImage) {
332 when(core.getTemporaryImage(eq(imageId))).thenReturn(temporaryImage);
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);
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();
349 protected void addNotification(String notificationId, Notification notification) {
350 when(webInterface.getNotification(eq(notificationId))).thenReturn(Optional.of(notification));
353 protected void verifyRedirect(String target) throws RedirectException {
354 expectedException.expect(redirectsTo(target));
355 getPage().handleRequest(freenetRequest, templateContext);
358 protected void verifyRedirect(String target, Runnable verification) throws RedirectException {
359 expectedException.expect(redirectsTo(target));
361 getPage().handleRequest(freenetRequest, templateContext);