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.isPartSet(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.getParts()).thenAnswer(new Answer<String[]>() {
176 public String[] answer(InvocationOnMock invocation) throws Throwable {
177 return requestParameters.keySet().toArray(new String[requestParameters.size()]);
180 when(httpRequest.getHeader(anyString())).thenAnswer(new Answer<String>() {
182 public String answer(InvocationOnMock invocation) throws Throwable {
183 return requestHeaders.get(invocation.<String>getArgument(0).toLowerCase());
186 when(httpRequest.getUploadedFile(anyString())).thenAnswer(new Answer<HTTPUploadedFile>() {
188 public HTTPUploadedFile answer(InvocationOnMock invocation) throws Throwable {
189 final String name = invocation.getArgument(0);
190 if (!uploadedFilesSources.containsKey(name)) {
193 return new HTTPUploadedFile() {
195 public String getContentType() {
196 return uploadedFilesContentTypes.get(name);
200 public Bucket getData() {
201 try (InputStream inputStream = getClass().getResourceAsStream(uploadedFilesSources.get(name))) {
202 byte[] bytes = ByteStreams.toByteArray(inputStream);
203 return new SimpleReadOnlyArrayBucket(bytes, 0, bytes.length);
204 } catch (IOException ioe1) {
205 return new NullBucket();
210 public String getFilename() {
211 return uploadedFilesNames.get(name);
219 public final void setupCore() {
220 UpdateChecker updateChecker = mock(UpdateChecker.class);
221 when(core.getUpdateChecker()).thenReturn(updateChecker);
222 when(core.getPreferences()).thenReturn(new Preferences(eventBus));
223 when(core.getLocalSone(anyString())).thenReturn(null);
224 when(core.getLocalSones()).thenReturn(localSones);
225 when(core.getSone(anyString())).thenReturn(Optional.<Sone>absent());
226 when(core.getSones()).thenAnswer(new Answer<Collection<Sone>>() {
228 public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
229 return sones.values();
232 when(core.getSone(anyString())).thenAnswer(new Answer<Optional<Sone>>() {
234 public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
235 return Optional.fromNullable(sones.get(invocation.getArgument(0)));
238 when(core.getPost(anyString())).thenReturn(Optional.<Post>absent());
239 when(core.getReplies(anyString())).thenAnswer(new Answer<List<PostReply>>() {
241 public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
242 return postReplies.get(invocation.<String>getArgument(0));
245 when(core.getAlbum(anyString())).thenReturn(null);
246 when(core.getImage(anyString())).thenReturn(null);
247 when(core.getImage(anyString(), anyBoolean())).thenReturn(null);
248 when(core.getTemporaryImage(anyString())).thenReturn(null);
252 public void setupL10n() {
253 when(l10n.getString(anyString())).thenAnswer(new Answer<String>() {
255 public String answer(InvocationOnMock invocation) throws Throwable {
256 return invocation.getArgument(0);
262 public final void setupIdentityManager() {
263 when(core.getIdentityManager().getAllOwnIdentities()).thenReturn(ownIdentities);
267 public final void setupWebInterface() {
268 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(currentSone);
269 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(currentSone);
270 when(webInterface.getNotification(anyString())).thenReturn(Optional.<Notification>absent());
271 when(webInterface.getNotifications(currentSone)).thenReturn(new ArrayList<Notification>());
275 public void setupSone() {
276 when(currentSone.getOptions()).thenReturn(new DefaultSoneOptions());
279 protected SoneTemplatePage getPage() {
283 protected void unsetCurrentSone() {
284 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(null);
285 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(null);
288 protected void request(String uri, Method method) {
290 when(httpRequest.getPath()).thenReturn(uri);
291 when(freenetRequest.getUri()).thenReturn(new URI(uri));
292 } catch (URISyntaxException e) {
293 throw new RuntimeException(e);
295 when(freenetRequest.getMethod()).thenReturn(method);
298 protected void addHttpRequestHeader(@Nonnull String name, String value) {
299 requestHeaders.put(name.toLowerCase(), value);
302 protected void addHttpRequestParameter(String name, final String value) {
303 requestParameters.put(name, value);
306 protected void addPost(String postId, Post post) {
307 when(core.getPost(postId)).thenReturn(Optional.fromNullable(post));
310 protected void addPostReply(String postReplyId, PostReply postReply) {
311 if (postReply.getPostId() != null) {
312 postReplies.put(postReply.getPostId(), postReply);
314 when(core.getPostReply(postReplyId)).thenReturn(Optional.fromNullable(postReply));
317 protected void addSone(String soneId, Sone sone) {
318 sones.put(soneId, sone);
321 protected void addLocalSone(String soneId, Sone sone) {
322 when(core.getLocalSone(eq(soneId))).thenReturn(sone);
323 localSones.add(sone);
326 protected void addOwnIdentity(OwnIdentity ownIdentity) {
327 ownIdentities.add(ownIdentity);
330 protected void addAlbum(String albumId, Album album) {
331 when(core.getAlbum(eq(albumId))).thenReturn(album);
334 protected void addImage(String imageId, Image image) {
335 when(core.getImage(eq(imageId))).thenReturn(image);
336 when(core.getImage(eq(imageId), anyBoolean())).thenReturn(image);
339 protected void addTemporaryImage(String imageId, TemporaryImage temporaryImage) {
340 when(core.getTemporaryImage(eq(imageId))).thenReturn(temporaryImage);
343 protected void addUploadedFile(@Nonnull String name, @Nonnull String filename, @Nonnull String contentType, @Nonnull String resource) {
344 uploadedFilesNames.put(name, filename);
345 uploadedFilesContentTypes.put(name, contentType);
346 uploadedFilesSources.put(name, resource);
349 protected byte[] getResponseBytes() throws IOException {
350 response.getContent().close();
351 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
352 ByteStreams.copy(responseInputStream, outputStream);
353 return outputStream.toByteArray();
357 protected void addNotification(String notificationId, Notification notification) {
358 when(webInterface.getNotification(eq(notificationId))).thenReturn(Optional.of(notification));
361 protected void verifyRedirect(String target) throws RedirectException {
362 expectedException.expect(redirectsTo(target));
363 getPage().handleRequest(freenetRequest, templateContext);
366 protected void verifyRedirect(String target, Runnable verification) throws RedirectException {
367 expectedException.expect(redirectsTo(target));
369 getPage().handleRequest(freenetRequest, templateContext);