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