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