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;
27 import java.util.NoSuchElementException;
30 import javax.annotation.Nonnull;
31 import javax.naming.SizeLimitExceededException;
33 import net.pterodactylus.sone.core.Core;
34 import net.pterodactylus.sone.core.Preferences;
35 import net.pterodactylus.sone.core.UpdateChecker;
36 import net.pterodactylus.sone.data.Album;
37 import net.pterodactylus.sone.data.Image;
38 import net.pterodactylus.sone.data.Post;
39 import net.pterodactylus.sone.data.PostReply;
40 import net.pterodactylus.sone.data.Sone;
41 import net.pterodactylus.sone.data.SoneOptions.DefaultSoneOptions;
42 import net.pterodactylus.sone.data.TemporaryImage;
43 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
44 import net.pterodactylus.sone.web.WebInterface;
45 import net.pterodactylus.sone.web.page.FreenetRequest;
46 import net.pterodactylus.sone.web.page.FreenetTemplatePage.RedirectException;
47 import net.pterodactylus.util.notify.Notification;
48 import net.pterodactylus.util.template.Template;
49 import net.pterodactylus.util.template.TemplateContext;
50 import net.pterodactylus.util.web.Method;
51 import net.pterodactylus.util.web.Response;
53 import freenet.clients.http.ToadletContext;
54 import freenet.l10n.BaseL10n;
55 import freenet.support.SimpleReadOnlyArrayBucket;
56 import freenet.support.api.Bucket;
57 import freenet.support.api.HTTPRequest;
58 import freenet.support.api.HTTPUploadedFile;
59 import freenet.support.io.NullBucket;
61 import com.google.common.base.Optional;
62 import com.google.common.collect.ArrayListMultimap;
63 import com.google.common.collect.ListMultimap;
64 import com.google.common.collect.Multimap;
65 import com.google.common.eventbus.EventBus;
66 import com.google.common.io.ByteStreams;
67 import com.google.inject.Guice;
68 import com.google.inject.Injector;
69 import org.junit.Before;
70 import org.junit.Rule;
71 import org.junit.rules.ExpectedException;
72 import org.mockito.ArgumentMatchers;
73 import org.mockito.invocation.InvocationOnMock;
74 import org.mockito.stubbing.Answer;
77 * Base class for web page tests.
79 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
81 public abstract class WebPageTest {
84 public final ExpectedException expectedException = ExpectedException.none();
86 protected final Template template = new Template();
87 protected final WebInterface webInterface = mock(WebInterface.class, RETURNS_DEEP_STUBS);
88 protected final EventBus eventBus = mock(EventBus.class);
89 protected final Core core = webInterface.getCore();
90 protected final BaseL10n l10n = webInterface.getL10n();
92 protected final Sone currentSone = mock(Sone.class);
94 protected final TemplateContext templateContext = new TemplateContext();
95 protected final HTTPRequest httpRequest = mock(HTTPRequest.class);
96 protected final Multimap<String, String> requestParameters = ArrayListMultimap.create();
97 protected final Map<String, String> requestParts = new HashMap<>();
98 protected final Map<String, String> requestHeaders = new HashMap<>();
99 private final Map<String, String> uploadedFilesNames = new HashMap<>();
100 private final Map<String, String> uploadedFilesContentTypes = new HashMap<>();
101 private final Map<String, String> uploadedFilesSources = new HashMap<>();
102 protected final FreenetRequest freenetRequest = mock(FreenetRequest.class);
103 private final PipedOutputStream responseOutputStream = new PipedOutputStream();
104 private final PipedInputStream responseInputStream;
105 protected final Response response = new Response(responseOutputStream);
106 protected final ToadletContext toadletContext = mock(ToadletContext.class);
108 private final Set<OwnIdentity> ownIdentities = new HashSet<>();
109 private final Map<String, Sone> sones = new HashMap<>();
110 protected final List<Sone> localSones = new ArrayList<>();
111 private final ListMultimap<String, PostReply> postReplies = ArrayListMultimap.create();
113 protected final Injector injector = Guice.createInjector(
114 supply(WebInterface.class).byInstance(webInterface),
115 supply(Template.class).byInstance(template)
118 protected WebPageTest() {
120 responseInputStream = new PipedInputStream(responseOutputStream);
121 } catch (IOException e) {
122 throw new RuntimeException(e);
127 public final void setupFreenetRequest() throws SizeLimitExceededException {
128 when(freenetRequest.getToadletContext()).thenReturn(toadletContext);
129 when(freenetRequest.getHttpRequest()).thenReturn(httpRequest);
130 when(httpRequest.getMultipleParam(anyString())).thenAnswer(new Answer<String[]>() {
132 public String[] answer(InvocationOnMock invocation) throws Throwable {
133 return requestParameters.get(invocation.<String>getArgument(0)).toArray(new String[0]);
136 when(httpRequest.isPartSet(anyString())).thenAnswer(new Answer<Boolean>() {
138 public Boolean answer(InvocationOnMock invocation) throws Throwable {
139 return requestParts.get(invocation.<String>getArgument(0)) != null;
142 when(httpRequest.getParts()).thenAnswer(new Answer<String[]>() {
144 public String[] answer(InvocationOnMock invocation) throws Throwable {
145 return requestParts.keySet().toArray(new String[requestParts.size()]);
148 when(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).thenAnswer(new Answer<String>() {
150 public String answer(InvocationOnMock invocation) throws Throwable {
151 String parameter = invocation.getArgument(0);
152 int maxLength = invocation.getArgument(1);
153 String value = requestParts.get(parameter);
154 return requestParts.containsKey(parameter) ? value.substring(0, Math.min(maxLength, value.length())) : "";
157 when(httpRequest.getPartAsStringThrowing(anyString(), anyInt())).thenAnswer(new Answer<String>() {
159 public String answer(InvocationOnMock invocation) throws Throwable {
160 String partName = invocation.getArgument(0);
161 if (!requestParts.containsKey(partName)) throw new NoSuchElementException();
162 String partValue = requestParts.get(partName);
163 if (partValue.length() > invocation.<Integer>getArgument(1)) throw new SizeLimitExceededException();
167 when(httpRequest.hasParameters()).thenAnswer(new Answer<Boolean>() {
169 public Boolean answer(InvocationOnMock invocation) throws Throwable {
170 return !requestParameters.isEmpty();
173 when(httpRequest.getParameterNames()).thenAnswer(new Answer<Collection<String>>() {
175 public Collection<String> answer(InvocationOnMock invocation) throws Throwable {
176 return requestParameters.keySet();
179 when(httpRequest.getParam(anyString())).thenAnswer(new Answer<String>() {
181 public String answer(InvocationOnMock invocation) throws Throwable {
182 String parameter = invocation.getArgument(0);
183 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : "";
186 when(httpRequest.getParam(anyString(), ArgumentMatchers.<String>any())).thenAnswer(new Answer<String>() {
188 public String answer(InvocationOnMock invocation) throws Throwable {
189 String parameter = invocation.getArgument(0);
190 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : invocation.<String>getArgument(1);
193 when(httpRequest.isParameterSet(anyString())).thenAnswer(new Answer<Boolean>() {
195 public Boolean answer(InvocationOnMock invocation) throws Throwable {
196 return requestParameters.containsKey(invocation.<String>getArgument(0)) &&
197 requestParameters.get(invocation.<String>getArgument(0)).iterator().next() != null;
200 when(httpRequest.getHeader(anyString())).thenAnswer(new Answer<String>() {
202 public String answer(InvocationOnMock invocation) throws Throwable {
203 return requestHeaders.get(invocation.<String>getArgument(0).toLowerCase());
206 when(httpRequest.getUploadedFile(anyString())).thenAnswer(new Answer<HTTPUploadedFile>() {
208 public HTTPUploadedFile answer(InvocationOnMock invocation) throws Throwable {
209 final String name = invocation.getArgument(0);
210 if (!uploadedFilesSources.containsKey(name)) {
213 return new HTTPUploadedFile() {
215 public String getContentType() {
216 return uploadedFilesContentTypes.get(name);
220 public Bucket getData() {
221 try (InputStream inputStream = getClass().getResourceAsStream(uploadedFilesSources.get(name))) {
222 byte[] bytes = ByteStreams.toByteArray(inputStream);
223 return new SimpleReadOnlyArrayBucket(bytes, 0, bytes.length);
224 } catch (IOException ioe1) {
225 return new NullBucket();
230 public String getFilename() {
231 return uploadedFilesNames.get(name);
239 public final void setupCore() {
240 UpdateChecker updateChecker = mock(UpdateChecker.class);
241 when(core.getUpdateChecker()).thenReturn(updateChecker);
242 when(core.getPreferences()).thenReturn(new Preferences(eventBus));
243 when(core.getLocalSone(anyString())).thenReturn(null);
244 when(core.getLocalSones()).thenReturn(localSones);
245 when(core.getSone(anyString())).thenReturn(Optional.<Sone>absent());
246 when(core.getSones()).thenAnswer(new Answer<Collection<Sone>>() {
248 public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
249 return sones.values();
252 when(core.getSone(anyString())).thenAnswer(new Answer<Optional<Sone>>() {
254 public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
255 return Optional.fromNullable(sones.get(invocation.getArgument(0)));
258 when(core.getPost(anyString())).thenReturn(Optional.<Post>absent());
259 when(core.getPostReply(anyString())).thenReturn(Optional.<PostReply>absent());
260 when(core.getReplies(anyString())).thenAnswer(new Answer<List<PostReply>>() {
262 public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
263 return postReplies.get(invocation.<String>getArgument(0));
266 when(core.getAlbum(anyString())).thenReturn(null);
267 when(core.getImage(anyString())).thenReturn(null);
268 when(core.getImage(anyString(), anyBoolean())).thenReturn(null);
269 when(core.getTemporaryImage(anyString())).thenReturn(null);
273 public void setupL10n() {
274 when(l10n.getString(anyString())).thenAnswer(new Answer<String>() {
276 public String answer(InvocationOnMock invocation) throws Throwable {
277 return invocation.getArgument(0);
283 public final void setupIdentityManager() {
284 when(core.getIdentityManager().getAllOwnIdentities()).thenReturn(ownIdentities);
288 public final void setupWebInterface() {
289 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(currentSone);
290 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(currentSone);
291 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(currentSone);
292 when(webInterface.getNotification(anyString())).thenReturn(Optional.<Notification>absent());
293 when(webInterface.getNotifications(currentSone)).thenReturn(new ArrayList<Notification>());
297 public void setupSone() {
298 when(currentSone.getOptions()).thenReturn(new DefaultSoneOptions());
301 protected SoneTemplatePage getPage() {
305 protected void unsetCurrentSone() {
306 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(null);
307 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(null);
308 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(null);
311 protected void request(String uri, Method method) {
313 when(httpRequest.getPath()).thenReturn(uri);
314 when(freenetRequest.getUri()).thenReturn(new URI(uri));
315 } catch (URISyntaxException e) {
316 throw new RuntimeException(e);
318 when(freenetRequest.getMethod()).thenReturn(method);
319 when(httpRequest.getMethod()).thenReturn(method.name());
322 protected void addHttpRequestHeader(@Nonnull String name, String value) {
323 requestHeaders.put(name.toLowerCase(), value);
326 protected void addHttpRequestParameter(String name, final String value) {
327 requestParameters.put(name, value);
330 protected void addHttpRequestPart(String name, String value) {
331 requestParts.put(name, value);
334 protected void addPost(String postId, Post post) {
335 when(core.getPost(postId)).thenReturn(Optional.fromNullable(post));
338 protected void addPostReply(String postReplyId, PostReply postReply) {
339 if (postReply.getPostId() != null) {
340 postReplies.put(postReply.getPostId(), postReply);
342 when(core.getPostReply(postReplyId)).thenReturn(Optional.fromNullable(postReply));
345 protected void addSone(String soneId, Sone sone) {
346 sones.put(soneId, sone);
349 protected void addLocalSone(String soneId, Sone sone) {
350 when(core.getLocalSone(eq(soneId))).thenReturn(sone);
351 localSones.add(sone);
354 protected void addOwnIdentity(OwnIdentity ownIdentity) {
355 ownIdentities.add(ownIdentity);
358 protected void addAlbum(String albumId, Album album) {
359 when(core.getAlbum(eq(albumId))).thenReturn(album);
362 protected void addImage(String imageId, Image image) {
363 when(core.getImage(eq(imageId))).thenReturn(image);
364 when(core.getImage(eq(imageId), anyBoolean())).thenReturn(image);
367 protected void addTemporaryImage(String imageId, TemporaryImage temporaryImage) {
368 when(core.getTemporaryImage(eq(imageId))).thenReturn(temporaryImage);
371 protected void addUploadedFile(@Nonnull String name, @Nonnull String filename, @Nonnull String contentType, @Nonnull String resource) {
372 uploadedFilesNames.put(name, filename);
373 uploadedFilesContentTypes.put(name, contentType);
374 uploadedFilesSources.put(name, resource);
377 protected byte[] getResponseBytes() throws IOException {
378 response.getContent().close();
379 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
380 ByteStreams.copy(responseInputStream, outputStream);
381 return outputStream.toByteArray();
385 protected void addNotification(String notificationId, Notification notification) {
386 when(webInterface.getNotification(eq(notificationId))).thenReturn(Optional.of(notification));
389 protected void verifyRedirect(String target) throws RedirectException {
390 expectedException.expect(redirectsTo(target));
391 getPage().handleRequest(freenetRequest, templateContext);
394 protected void verifyRedirect(String target, Runnable verification) throws RedirectException {
395 expectedException.expect(redirectsTo(target));
397 getPage().handleRequest(freenetRequest, templateContext);