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