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