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.Mockito;
74 import org.mockito.invocation.InvocationOnMock;
75 import org.mockito.stubbing.Answer;
78 * Base class for web page tests.
80 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
82 public abstract class WebPageTest {
85 public final ExpectedException expectedException = ExpectedException.none();
87 protected final Template template = new Template();
88 protected final WebInterface webInterface = mock(WebInterface.class, RETURNS_DEEP_STUBS);
89 protected final EventBus eventBus = mock(EventBus.class);
90 protected final Core core = webInterface.getCore();
91 protected final BaseL10n l10n = webInterface.getL10n();
93 protected final Sone currentSone = mock(Sone.class);
95 protected final TemplateContext templateContext = new TemplateContext();
96 protected final HTTPRequest httpRequest = mock(HTTPRequest.class);
97 protected final Multimap<String, String> requestParameters = ArrayListMultimap.create();
98 protected final Map<String, String> requestParts = new HashMap<>();
99 protected final Map<String, String> requestHeaders = new HashMap<>();
100 private final Map<String, String> uploadedFilesNames = new HashMap<>();
101 private final Map<String, String> uploadedFilesContentTypes = new HashMap<>();
102 private final Map<String, String> uploadedFilesSources = new HashMap<>();
103 protected final FreenetRequest freenetRequest = mock(FreenetRequest.class);
104 private final PipedOutputStream responseOutputStream = new PipedOutputStream();
105 private final PipedInputStream responseInputStream;
106 protected final Response response = new Response(responseOutputStream);
107 protected final ToadletContext toadletContext = mock(ToadletContext.class);
109 private final Set<OwnIdentity> ownIdentities = new HashSet<>();
110 private final Map<String, Sone> sones = new HashMap<>();
111 protected final List<Sone> localSones = new ArrayList<>();
112 private final ListMultimap<String, PostReply> postReplies = ArrayListMultimap.create();
114 protected final Injector injector = Guice.createInjector(
115 supply(WebInterface.class).byInstance(webInterface),
116 supply(Template.class).byInstance(template)
119 protected WebPageTest() {
121 responseInputStream = new PipedInputStream(responseOutputStream);
122 } catch (IOException e) {
123 throw new RuntimeException(e);
128 public final void setupFreenetRequest() throws SizeLimitExceededException {
129 when(freenetRequest.getToadletContext()).thenReturn(toadletContext);
130 when(freenetRequest.getHttpRequest()).thenReturn(httpRequest);
131 when(httpRequest.getMultipleParam(anyString())).thenAnswer(new Answer<String[]>() {
133 public String[] answer(InvocationOnMock invocation) throws Throwable {
134 return requestParameters.get(invocation.<String>getArgument(0)).toArray(new String[0]);
137 when(httpRequest.isPartSet(anyString())).thenAnswer(new Answer<Boolean>() {
139 public Boolean answer(InvocationOnMock invocation) throws Throwable {
140 return requestParts.get(invocation.<String>getArgument(0)) != null;
143 when(httpRequest.getParts()).thenAnswer(new Answer<String[]>() {
145 public String[] answer(InvocationOnMock invocation) throws Throwable {
146 return requestParts.keySet().toArray(new String[requestParts.size()]);
149 when(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).thenAnswer(new Answer<String>() {
151 public String answer(InvocationOnMock invocation) throws Throwable {
152 String parameter = invocation.getArgument(0);
153 int maxLength = invocation.getArgument(1);
154 String value = requestParts.get(parameter);
155 return requestParts.containsKey(parameter) ? value.substring(0, Math.min(maxLength, value.length())) : "";
158 when(httpRequest.getPartAsStringThrowing(anyString(), anyInt())).thenAnswer(new Answer<String>() {
160 public String answer(InvocationOnMock invocation) throws Throwable {
161 String partName = invocation.getArgument(0);
162 if (!requestParts.containsKey(partName)) throw new NoSuchElementException();
163 String partValue = requestParts.get(partName);
164 if (partValue.length() > invocation.<Integer>getArgument(1)) throw new SizeLimitExceededException();
168 when(httpRequest.hasParameters()).thenAnswer(new Answer<Boolean>() {
170 public Boolean answer(InvocationOnMock invocation) throws Throwable {
171 return !requestParameters.isEmpty();
174 when(httpRequest.getParameterNames()).thenAnswer(new Answer<Collection<String>>() {
176 public Collection<String> answer(InvocationOnMock invocation) throws Throwable {
177 return requestParameters.keySet();
180 when(httpRequest.getParam(anyString())).thenAnswer(new Answer<String>() {
182 public String answer(InvocationOnMock invocation) throws Throwable {
183 String parameter = invocation.getArgument(0);
184 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : "";
187 when(httpRequest.getParam(anyString(), ArgumentMatchers.<String>any())).thenAnswer(new Answer<String>() {
189 public String answer(InvocationOnMock invocation) throws Throwable {
190 String parameter = invocation.getArgument(0);
191 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).iterator().next() : invocation.<String>getArgument(1);
194 when(httpRequest.isParameterSet(anyString())).thenAnswer(new Answer<Boolean>() {
196 public Boolean answer(InvocationOnMock invocation) throws Throwable {
197 return requestParameters.containsKey(invocation.<String>getArgument(0)) &&
198 requestParameters.get(invocation.<String>getArgument(0)).iterator().next() != null;
201 when(httpRequest.getHeader(anyString())).thenAnswer(new Answer<String>() {
203 public String answer(InvocationOnMock invocation) throws Throwable {
204 return requestHeaders.get(invocation.<String>getArgument(0).toLowerCase());
207 when(httpRequest.getUploadedFile(anyString())).thenAnswer(new Answer<HTTPUploadedFile>() {
209 public HTTPUploadedFile answer(InvocationOnMock invocation) throws Throwable {
210 final String name = invocation.getArgument(0);
211 if (!uploadedFilesSources.containsKey(name)) {
214 return new HTTPUploadedFile() {
216 public String getContentType() {
217 return uploadedFilesContentTypes.get(name);
221 public Bucket getData() {
222 try (InputStream inputStream = getClass().getResourceAsStream(uploadedFilesSources.get(name))) {
223 byte[] bytes = ByteStreams.toByteArray(inputStream);
224 return new SimpleReadOnlyArrayBucket(bytes, 0, bytes.length);
225 } catch (IOException ioe1) {
226 return new NullBucket();
231 public String getFilename() {
232 return uploadedFilesNames.get(name);
240 public final void setupCore() {
241 UpdateChecker updateChecker = mock(UpdateChecker.class);
242 when(core.getUpdateChecker()).thenReturn(updateChecker);
243 when(core.getPreferences()).thenReturn(new Preferences(eventBus));
244 when(core.getLocalSone(anyString())).thenReturn(null);
245 when(core.getLocalSones()).thenReturn(localSones);
246 when(core.getSone(anyString())).thenReturn(Optional.<Sone>absent());
247 when(core.getSones()).thenAnswer(new Answer<Collection<Sone>>() {
249 public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
250 return sones.values();
253 when(core.getSone(anyString())).thenAnswer(new Answer<Optional<Sone>>() {
255 public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
256 return Optional.fromNullable(sones.get(invocation.getArgument(0)));
259 when(core.getPost(anyString())).thenReturn(Optional.<Post>absent());
260 when(core.getPostReply(anyString())).thenReturn(Optional.<PostReply>absent());
261 when(core.getReplies(anyString())).thenAnswer(new Answer<List<PostReply>>() {
263 public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
264 return postReplies.get(invocation.<String>getArgument(0));
267 when(core.getAlbum(anyString())).thenReturn(null);
268 when(core.getImage(anyString())).thenReturn(null);
269 when(core.getImage(anyString(), anyBoolean())).thenReturn(null);
270 when(core.getTemporaryImage(anyString())).thenReturn(null);
274 public void setupL10n() {
275 when(l10n.getString(anyString())).thenAnswer(new Answer<String>() {
277 public String answer(InvocationOnMock invocation) throws Throwable {
278 return invocation.getArgument(0);
284 public final void setupIdentityManager() {
285 when(core.getIdentityManager().getAllOwnIdentities()).thenReturn(ownIdentities);
289 public final void setupWebInterface() {
290 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(currentSone);
291 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(currentSone);
292 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(currentSone);
293 when(webInterface.getNotification(anyString())).thenReturn(Optional.<Notification>absent());
294 when(webInterface.getNotifications(Mockito.<Sone>any())).thenReturn(new ArrayList<Notification>());
298 public void setupSone() {
299 when(currentSone.getOptions()).thenReturn(new DefaultSoneOptions());
302 protected SoneTemplatePage getPage() {
306 protected void unsetCurrentSone() {
307 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(null);
308 when(webInterface.getCurrentSoneCreatingSession(toadletContext)).thenReturn(null);
309 when(webInterface.getCurrentSoneWithoutCreatingSession(toadletContext)).thenReturn(null);
312 protected void setMethod(Method method) {
313 when(freenetRequest.getMethod()).thenReturn(method);
314 when(httpRequest.getMethod()).thenReturn(method.name());
317 protected void request(String uri, Method method) {
319 when(httpRequest.getPath()).thenReturn(uri);
320 when(freenetRequest.getUri()).thenReturn(new URI(uri));
321 } catch (URISyntaxException e) {
322 throw new RuntimeException(e);
324 when(freenetRequest.getMethod()).thenReturn(method);
325 when(httpRequest.getMethod()).thenReturn(method.name());
328 protected void addHttpRequestHeader(@Nonnull String name, String value) {
329 requestHeaders.put(name.toLowerCase(), value);
332 protected void addHttpRequestParameter(String name, final String value) {
333 requestParameters.put(name, value);
336 protected void addHttpRequestPart(String name, String value) {
337 requestParts.put(name, value);
340 protected void addPost(String postId, Post post) {
341 when(core.getPost(postId)).thenReturn(Optional.fromNullable(post));
344 protected void addPostReply(String postReplyId, PostReply postReply) {
345 if (postReply.getPostId() != null) {
346 postReplies.put(postReply.getPostId(), postReply);
348 when(core.getPostReply(postReplyId)).thenReturn(Optional.fromNullable(postReply));
351 protected void addSone(String soneId, Sone sone) {
352 sones.put(soneId, sone);
355 protected void addLocalSone(String soneId, Sone sone) {
356 when(core.getLocalSone(eq(soneId))).thenReturn(sone);
357 localSones.add(sone);
360 protected void addOwnIdentity(OwnIdentity ownIdentity) {
361 ownIdentities.add(ownIdentity);
364 protected void addAlbum(String albumId, Album album) {
365 when(core.getAlbum(eq(albumId))).thenReturn(album);
368 protected void addImage(String imageId, Image image) {
369 when(core.getImage(eq(imageId))).thenReturn(image);
370 when(core.getImage(eq(imageId), anyBoolean())).thenReturn(image);
373 protected void addTemporaryImage(String imageId, TemporaryImage temporaryImage) {
374 when(core.getTemporaryImage(eq(imageId))).thenReturn(temporaryImage);
377 protected void addUploadedFile(@Nonnull String name, @Nonnull String filename, @Nonnull String contentType, @Nonnull String resource) {
378 uploadedFilesNames.put(name, filename);
379 uploadedFilesContentTypes.put(name, contentType);
380 uploadedFilesSources.put(name, resource);
383 protected byte[] getResponseBytes() throws IOException {
384 response.getContent().close();
385 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
386 ByteStreams.copy(responseInputStream, outputStream);
387 return outputStream.toByteArray();
391 protected void addNotification(String notificationId, Notification notification) {
392 when(webInterface.getNotification(eq(notificationId))).thenReturn(Optional.of(notification));
395 protected void verifyRedirect(String target) throws RedirectException {
396 expectedException.expect(redirectsTo(target));
397 getPage().handleRequest(freenetRequest, templateContext);
400 protected void verifyRedirect(String target, Runnable verification) throws RedirectException {
401 expectedException.expect(redirectsTo(target));
403 getPage().handleRequest(freenetRequest, templateContext);
410 protected void verifyNoRedirect(Runnable verification) throws RedirectException {
411 getPage().handleRequest(freenetRequest, templateContext);
415 protected void addTranslation(@Nonnull String key, @Nonnull String value) {
416 when(l10n.getString(key)).thenReturn(value);