Add unit test for search page
[Sone.git] / src / test / java / net / pterodactylus / sone / web / WebPageTest.java
1 package net.pterodactylus.sone.web;
2
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;
12
13 import java.io.ByteArrayOutputStream;
14 import java.io.IOException;
15 import java.io.PipedInputStream;
16 import java.io.PipedOutputStream;
17 import java.net.URI;
18 import java.net.URISyntaxException;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26
27 import javax.annotation.Nonnull;
28
29 import net.pterodactylus.sone.core.Core;
30 import net.pterodactylus.sone.core.Preferences;
31 import net.pterodactylus.sone.core.UpdateChecker;
32 import net.pterodactylus.sone.data.Album;
33 import net.pterodactylus.sone.data.Image;
34 import net.pterodactylus.sone.data.Post;
35 import net.pterodactylus.sone.data.PostReply;
36 import net.pterodactylus.sone.data.Sone;
37 import net.pterodactylus.sone.data.SoneOptions.DefaultSoneOptions;
38 import net.pterodactylus.sone.data.TemporaryImage;
39 import net.pterodactylus.sone.freenet.wot.OwnIdentity;
40 import net.pterodactylus.sone.web.page.FreenetRequest;
41 import net.pterodactylus.sone.web.page.FreenetTemplatePage.RedirectException;
42 import net.pterodactylus.util.notify.Notification;
43 import net.pterodactylus.util.template.Template;
44 import net.pterodactylus.util.template.TemplateContext;
45 import net.pterodactylus.util.web.Method;
46 import net.pterodactylus.util.web.Response;
47
48 import freenet.clients.http.ToadletContext;
49 import freenet.support.api.HTTPRequest;
50
51 import com.google.common.base.Optional;
52 import com.google.common.collect.ArrayListMultimap;
53 import com.google.common.collect.ListMultimap;
54 import com.google.common.eventbus.EventBus;
55 import com.google.common.io.ByteStreams;
56 import org.junit.Before;
57 import org.junit.Rule;
58 import org.junit.rules.ExpectedException;
59 import org.mockito.ArgumentMatchers;
60 import org.mockito.invocation.InvocationOnMock;
61 import org.mockito.stubbing.Answer;
62
63 /**
64  * Base class for web page tests.
65  *
66  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
67  */
68 public abstract class WebPageTest {
69
70         @Rule
71         public final ExpectedException expectedException = ExpectedException.none();
72
73         protected final Template template = new Template();
74         protected final WebInterface webInterface = mock(WebInterface.class, RETURNS_DEEP_STUBS);
75         protected final EventBus eventBus = mock(EventBus.class);
76         protected final Core core = webInterface.getCore();
77
78         protected final Sone currentSone = mock(Sone.class);
79
80         protected final TemplateContext templateContext = new TemplateContext();
81         protected final HTTPRequest httpRequest = mock(HTTPRequest.class);
82         protected final Map<String, String> requestParameters = new HashMap<>();
83         protected final Map<String, String> requestHeaders = new HashMap<>();
84         protected final FreenetRequest freenetRequest = mock(FreenetRequest.class);
85         private final PipedOutputStream responseOutputStream = new PipedOutputStream();
86         private final PipedInputStream responseInputStream;
87         protected final Response response = new Response(responseOutputStream);
88         protected final ToadletContext toadletContext = mock(ToadletContext.class);
89
90         private final Set<OwnIdentity> ownIdentities = new HashSet<>();
91         private final Map<String, Sone> sones = new HashMap<>();
92         protected final List<Sone> localSones = new ArrayList<>();
93         private final ListMultimap<String, PostReply> postReplies = ArrayListMultimap.create();
94
95         protected WebPageTest() {
96                 try {
97                         responseInputStream = new PipedInputStream(responseOutputStream);
98                 } catch (IOException e) {
99                         throw new RuntimeException(e);
100                 }
101         }
102
103         @Before
104         public final void setupFreenetRequest() {
105                 when(freenetRequest.getToadletContext()).thenReturn(toadletContext);
106                 when(freenetRequest.getHttpRequest()).thenReturn(httpRequest);
107                 when(httpRequest.getPartAsStringFailsafe(anyString(), anyInt())).thenAnswer(new Answer<String>() {
108                         @Override
109                         public String answer(InvocationOnMock invocation) throws Throwable {
110                                 String parameter = invocation.getArgument(0);
111                                 int maxLength = invocation.getArgument(1);
112                                 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter).substring(0, Math.min(maxLength, requestParameters.get(parameter).length())) : "";
113                         }
114                 });
115                 when(httpRequest.getParam(anyString())).thenAnswer(new Answer<String>() {
116                         @Override
117                         public String answer(InvocationOnMock invocation) throws Throwable {
118                                 String parameter = invocation.getArgument(0);
119                                 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter) : "";
120                         }
121                 });
122                 when(httpRequest.getParam(anyString(), ArgumentMatchers.<String>any())).thenAnswer(new Answer<String>() {
123                         @Override
124                         public String answer(InvocationOnMock invocation) throws Throwable {
125                                 String parameter = invocation.getArgument(0);
126                                 return requestParameters.containsKey(parameter) ? requestParameters.get(parameter) : invocation.<String>getArgument(1);
127                         }
128                 });
129                 when(httpRequest.isPartSet(anyString())).thenAnswer(new Answer<Boolean>() {
130                         @Override
131                         public Boolean answer(InvocationOnMock invocation) throws Throwable {
132                                 return requestParameters.get(invocation.<String>getArgument(0)) != null;
133                         }
134                 });
135                 when(httpRequest.getParts()).thenAnswer(new Answer<String[]>() {
136                         @Override
137                         public String[] answer(InvocationOnMock invocation) throws Throwable {
138                                 return requestParameters.keySet().toArray(new String[requestParameters.size()]);
139                         }
140                 });
141                 when(httpRequest.getHeader(anyString())).thenAnswer(new Answer<String>() {
142                         @Override
143                         public String answer(InvocationOnMock invocation) throws Throwable {
144                                 return requestHeaders.get(invocation.<String>getArgument(0).toLowerCase());
145                         }
146                 });
147         }
148
149         @Before
150         public final void setupCore() {
151                 UpdateChecker updateChecker = mock(UpdateChecker.class);
152                 when(core.getUpdateChecker()).thenReturn(updateChecker);
153                 when(core.getPreferences()).thenReturn(new Preferences(eventBus));
154                 when(core.getLocalSone(anyString())).thenReturn(null);
155                 when(core.getLocalSones()).thenReturn(localSones);
156                 when(core.getSone(anyString())).thenReturn(Optional.<Sone>absent());
157                 when(core.getSones()).thenAnswer(new Answer<Collection<Sone>>() {
158                         @Override
159                         public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
160                                 return sones.values();
161                         }
162                 });
163                 when(core.getSone(anyString())).thenAnswer(new Answer<Optional<Sone>>() {
164                         @Override
165                         public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
166                                 return Optional.fromNullable(sones.get(invocation.getArgument(0)));
167                         }
168                 });
169                 when(core.getPost(anyString())).thenReturn(Optional.<Post>absent());
170                 when(core.getReplies(anyString())).thenAnswer(new Answer<List<PostReply>>() {
171                         @Override
172                         public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
173                                 return postReplies.get(invocation.<String>getArgument(0));
174                         }
175                 });
176                 when(core.getAlbum(anyString())).thenReturn(null);
177                 when(core.getImage(anyString())).thenReturn(null);
178                 when(core.getImage(anyString(), anyBoolean())).thenReturn(null);
179                 when(core.getTemporaryImage(anyString())).thenReturn(null);
180         }
181
182         @Before
183         public final void setupIdentityManager() {
184                 when(core.getIdentityManager().getAllOwnIdentities()).thenReturn(ownIdentities);
185         }
186
187         @Before
188         public final void setupWebInterface() {
189                 when(webInterface.getCurrentSone(toadletContext)).thenReturn(currentSone);
190                 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(currentSone);
191                 when(webInterface.getNotification(anyString())).thenReturn(Optional.<Notification>absent());
192                 when(webInterface.getNotifications(currentSone)).thenReturn(new ArrayList<Notification>());
193         }
194
195         @Before
196         public void setupSone() {
197                 when(currentSone.getOptions()).thenReturn(new DefaultSoneOptions());
198         }
199
200         protected SoneTemplatePage getPage() {
201                 return null;
202         }
203
204         protected void unsetCurrentSone() {
205                 when(webInterface.getCurrentSone(toadletContext)).thenReturn(null);
206                 when(webInterface.getCurrentSone(eq(toadletContext), anyBoolean())).thenReturn(null);
207         }
208
209         protected void request(String uri, Method method) {
210                 try {
211                         when(freenetRequest.getUri()).thenReturn(new URI(uri));
212                 } catch (URISyntaxException e) {
213                         throw new RuntimeException(e);
214                 }
215                 when(freenetRequest.getMethod()).thenReturn(method);
216         }
217
218         protected void addHttpRequestHeader(@Nonnull String name, String value) {
219                 requestHeaders.put(name.toLowerCase(), value);
220         }
221
222         protected void addHttpRequestParameter(String name, final String value) {
223                 requestParameters.put(name, value);
224         }
225
226         protected void addPost(String postId, Post post) {
227                 when(core.getPost(postId)).thenReturn(Optional.fromNullable(post));
228         }
229
230         protected void addPostReply(String postReplyId, PostReply postReply) {
231                 if (postReply.getPostId() != null) {
232                         postReplies.put(postReply.getPostId(), postReply);
233                 }
234                 when(core.getPostReply(postReplyId)).thenReturn(Optional.fromNullable(postReply));
235         }
236
237         protected void addSone(String soneId, Sone sone) {
238                 sones.put(soneId, sone);
239         }
240
241         protected void addLocalSone(String soneId, Sone sone) {
242                 when(core.getLocalSone(eq(soneId))).thenReturn(sone);
243                 localSones.add(sone);
244         }
245
246         protected void addOwnIdentity(OwnIdentity ownIdentity) {
247                 ownIdentities.add(ownIdentity);
248         }
249
250         protected void addAlbum(String albumId, Album album) {
251                 when(core.getAlbum(eq(albumId))).thenReturn(album);
252         }
253
254         protected void addImage(String imageId, Image image) {
255                 when(core.getImage(eq(imageId))).thenReturn(image);
256                 when(core.getImage(eq(imageId), anyBoolean())).thenReturn(image);
257         }
258
259         protected void addTemporaryImage(String imageId, TemporaryImage temporaryImage) {
260                 when(core.getTemporaryImage(eq(imageId))).thenReturn(temporaryImage);
261         }
262
263         protected byte[] getResponseBytes() throws IOException {
264                 response.getContent().close();
265                 try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
266                         ByteStreams.copy(responseInputStream, outputStream);
267                         return outputStream.toByteArray();
268                 }
269         }
270
271         protected void addNotification(String notificationId, Notification notification) {
272                 when(webInterface.getNotification(eq(notificationId))).thenReturn(Optional.of(notification));
273         }
274
275         protected void verifyRedirect(String target) throws RedirectException {
276                 expectedException.expect(redirectsTo(target));
277                 getPage().handleRequest(freenetRequest, templateContext);
278         }
279
280         protected void verifyRedirect(String target,  Runnable verification) throws RedirectException {
281                 expectedException.expect(redirectsTo(target));
282                 try {
283                         getPage().handleRequest(freenetRequest, templateContext);
284                         fail();
285                 } finally {
286                         verification.run();
287                 }
288         }
289
290 }