Mock the HTTP request, too.
[Sone.git] / src / test / java / net / pterodactylus / sone / data / Mocks.java
1 /*
2  * Sone - Mocks.java - Copyright © 2013 David Roden
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 package net.pterodactylus.sone.data;
19
20 import static com.google.common.base.Optional.absent;
21 import static com.google.common.base.Optional.fromNullable;
22 import static com.google.common.base.Optional.of;
23 import static com.google.common.collect.ArrayListMultimap.create;
24 import static com.google.common.collect.Maps.newHashMap;
25 import static com.google.common.collect.Ordering.from;
26 import static java.util.Collections.emptySet;
27 import static org.mockito.Matchers.anyString;
28 import static org.mockito.Matchers.eq;
29 import static org.mockito.Mockito.doAnswer;
30 import static org.mockito.Mockito.mock;
31 import static org.mockito.Mockito.when;
32
33 import java.net.URI;
34 import java.net.URISyntaxException;
35 import java.util.Collection;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39
40 import net.pterodactylus.sone.core.Core;
41 import net.pterodactylus.sone.core.Options;
42 import net.pterodactylus.sone.core.Options.DefaultOption;
43 import net.pterodactylus.sone.core.Options.Option;
44 import net.pterodactylus.sone.core.Options.OptionWatcher;
45 import net.pterodactylus.sone.core.Preferences;
46 import net.pterodactylus.sone.core.SoneInserter;
47 import net.pterodactylus.sone.data.impl.DefaultPostBuilder;
48 import net.pterodactylus.sone.data.impl.DefaultPostReplyBuilder;
49 import net.pterodactylus.sone.database.Database;
50 import net.pterodactylus.sone.database.PostReplyBuilder;
51 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
52 import net.pterodactylus.sone.utils.IntegerRangePredicate;
53 import net.pterodactylus.sone.web.WebInterface;
54 import net.pterodactylus.sone.web.page.FreenetRequest;
55
56 import freenet.clients.http.HTTPRequestImpl;
57 import freenet.support.api.HTTPRequest;
58
59 import com.google.common.base.Function;
60 import com.google.common.base.Optional;
61 import com.google.common.base.Predicates;
62 import com.google.common.collect.FluentIterable;
63 import com.google.common.collect.HashMultimap;
64 import com.google.common.collect.Multimap;
65 import com.google.common.collect.Ordering;
66 import com.google.common.collect.SetMultimap;
67 import org.mockito.Matchers;
68 import org.mockito.invocation.InvocationOnMock;
69 import org.mockito.stubbing.Answer;
70
71 /**
72  * Mocks reusable in multiple tests.
73  *
74  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
75  */
76 public class Mocks {
77
78         private final Multimap<Sone, Post> sonePosts = create();
79         private final Map<String, Sone> sones = newHashMap();
80         private final Multimap<Post, PostReply> postReplies = create();
81         private final Multimap<String, Post> directedPosts = create();
82         private final SetMultimap<Post, Sone> postLikingSones = HashMultimap.create();
83         private final SetMultimap<PostReply, Sone> postReplyLikingSones = HashMultimap.create();
84         public final Database database;
85         public final Core core;
86         public final WebInterface webInterface;
87
88         public Mocks() {
89                 database = mockDatabase();
90                 core = mockCore(database);
91                 webInterface = mockWebInterface(core);
92                 when(database.getSone()).thenReturn(new Function<String, Optional<Sone>>() {
93                         @Override
94                         public Optional<Sone> apply(String soneId) {
95                                 return (soneId == null) ? Optional.<Sone>absent() : fromNullable(sones.get(soneId));
96                         }
97                 });
98                 when(core.getSones()).then(new Answer<Collection<Sone>>() {
99                         @Override
100                         public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
101                                 return sones.values();
102                         }
103                 });
104                 when(core.getLocalSones()).then(new Answer<Collection<Sone>>() {
105                         @Override
106                         public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
107                                 return FluentIterable.from(sones.values()).filter(Sone.LOCAL_SONE_FILTER).toList();
108                         }
109                 });
110                 Options options = createOptions();
111                 when(core.getPreferences()).thenReturn(new Preferences(options));
112                 when(database.getDirectedPosts(anyString())).then(new Answer<Collection<Post>>() {
113                         @Override
114                         public Collection<Post> answer(InvocationOnMock invocation) throws Throwable {
115                                 return directedPosts.get((String) invocation.getArguments()[0]);
116                         }
117                 });
118         }
119
120         private Options createOptions() {
121                 Options options = new Options();
122                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE)));
123                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
124                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
125                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
126                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
127                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
128                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
129                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
130                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
131                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false));
132                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2));
133                 return options;
134         }
135
136         private static Core mockCore(Database database) {
137                 Core core = mock(Core.class);
138                 when(core.getDatabase()).thenReturn(database);
139                 when(core.getSone(anyString())).thenReturn(Optional.<Sone>absent());
140                 return core;
141         }
142
143         private static Database mockDatabase() {
144                 Database database = mock(Database.class);
145                 when(database.getSone(anyString())).thenReturn(Optional.<Sone>absent());
146                 when(database.getPost(anyString())).thenReturn(Optional.<Post>absent());
147                 when(database.getPostReply(anyString())).thenReturn(Optional.<PostReply>absent());
148                 return database;
149         }
150
151         private static WebInterface mockWebInterface(Core core) {
152                 WebInterface webInterface = mock(WebInterface.class);
153                 when(webInterface.getCore()).thenReturn(core);
154                 return webInterface;
155         }
156
157         public SoneMocker mockSone(String id) {
158                 return new SoneMocker(id);
159         }
160
161         public PostMocker mockPost(Sone sone, String postId) {
162                 return new PostMocker(postId, sone);
163         }
164
165         public PostReplyMocker mockPostReply(Sone sone, String replyId) {
166                 return new PostReplyMocker(replyId, sone);
167         }
168
169         public FreenetRequest mockRequest(String path) {
170                 HTTPRequest httpRequest = mock(HTTPRequest.class);
171                 when(httpRequest.getMethod()).thenReturn("GET");
172                 when(httpRequest.getPath()).thenReturn(path);
173                 FreenetRequest request = mock(FreenetRequest.class);
174                 when(request.getHttpRequest()).thenReturn(httpRequest);
175                 return request;
176         }
177
178         public class SoneMocker {
179
180                 private final Sone mockedSone = mock(Sone.class);
181                 private final String id;
182                 private boolean local;
183                 private Optional<String> name = absent();
184                 private long time;
185                 private Profile profile = new Profile(mockedSone);
186                 private Collection<String> friends = emptySet();
187
188                 private SoneMocker(String id) {
189                         this.id = id;
190                 }
191
192                 public SoneMocker local() {
193                         local = true;
194                         return this;
195                 }
196
197                 public SoneMocker withName(String name) {
198                         this.name = fromNullable(name);
199                         return this;
200                 }
201
202                 public SoneMocker withTime(long time) {
203                         this.time = time;
204                         return this;
205                 }
206
207                 public SoneMocker withProfileName(String firstName, String middleName, String lastName) {
208                         profile.modify().setFirstName(firstName).setMiddleName(middleName).setLastName(lastName).update();
209                         return this;
210                 }
211
212                 public SoneMocker addProfileField(String fieldName, String fieldValue) {
213                         profile.setField(profile.addField(fieldName), fieldValue);
214                         return this;
215                 }
216
217                 public SoneMocker withFriends(Collection<String> friends) {
218                         this.friends = friends;
219                         return this;
220                 }
221
222                 public Sone create() {
223                         when(mockedSone.getId()).thenReturn(id);
224                         when(mockedSone.isLocal()).thenReturn(local);
225                         if (name.isPresent()) {
226                                 when(mockedSone.getName()).thenReturn(name.get());
227                         }
228                         when(mockedSone.getTime()).thenReturn(time);
229                         when(mockedSone.getProfile()).thenReturn(profile);
230                         if (local) {
231                                 when(mockedSone.newPostBuilder()).thenReturn(new DefaultPostBuilder(database, id));
232                                 when(mockedSone.newPostReplyBuilder(anyString())).then(new Answer<PostReplyBuilder>() {
233                                         @Override
234                                         public PostReplyBuilder answer(InvocationOnMock invocation) throws Throwable {
235                                                 return new DefaultPostReplyBuilder(database, id, (String) invocation.getArguments()[0]);
236                                         }
237                                 });
238                                 when(mockedSone.hasFriend(anyString())).thenReturn(false);
239                                 when(mockedSone.getFriends()).thenReturn(friends);
240                                 when(mockedSone.hasFriend(anyString())).then(new Answer<Boolean>() {
241                                         @Override
242                                         public Boolean answer(InvocationOnMock invocation) throws Throwable {
243                                                 return friends.contains(invocation.getArguments()[0]);
244                                         }
245                                 });
246                         } else {
247                                 when(mockedSone.newPostBuilder()).thenThrow(IllegalStateException.class);
248                                 when(mockedSone.newPostReplyBuilder(anyString())).thenThrow(IllegalStateException.class);
249                         }
250                         when(core.getSone(eq(id))).thenReturn(of(mockedSone));
251                         when(database.getSone(eq(id))).thenReturn(of(mockedSone));
252                         when(mockedSone.getPosts()).then(new Answer<List<Post>>() {
253                                 @Override
254                                 public List<Post> answer(InvocationOnMock invocationOnMock) throws Throwable {
255                                         return from(Post.TIME_COMPARATOR).sortedCopy(sonePosts.get(mockedSone));
256                                 }
257                         });
258                         when(mockedSone.toString()).thenReturn(String.format("Sone[%s]", id));
259                         sones.put(id, mockedSone);
260                         return mockedSone;
261                 }
262
263         }
264
265         public class PostMocker {
266
267                 private final Post post = mock(Post.class);
268                 private final String id;
269                 private final Sone sone;
270                 private Optional<String> recipientId = absent();
271                 private long time;
272                 private Optional<String> text = absent();
273
274                 public PostMocker(String id, Sone sone) {
275                         this.id = id;
276                         this.sone = sone;
277                 }
278
279                 public PostMocker withRecipient(String recipientId) {
280                         this.recipientId = fromNullable(recipientId);
281                         return this;
282                 }
283
284                 public PostMocker withTime(long time) {
285                         this.time = time;
286                         return this;
287                 }
288
289                 public PostMocker withText(String text) {
290                         this.text = fromNullable(text);
291                         return this;
292                 }
293
294                 public Post create() {
295                         when(post.getId()).thenReturn(id);
296                         when(post.getSone()).thenReturn(sone);
297                         when(post.getRecipientId()).thenReturn(recipientId);
298                         if (recipientId.isPresent()) {
299                                 directedPosts.put(recipientId.get(), post);
300                         }
301                         when(post.getTime()).thenReturn(time);
302                         if (text.isPresent()) {
303                                 when(post.getText()).thenReturn(text.get());
304                         }
305                         when(database.getPost(eq(id))).thenReturn(of(post));
306                         sonePosts.put(sone, post);
307                         when(post.getReplies()).then(new Answer<List<PostReply>>() {
308                                 @Override
309                                 public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
310                                         return Ordering.from(Reply.TIME_COMPARATOR).sortedCopy(postReplies.get(post));
311                                 }
312                         });
313                         doAnswer(new Answer<Void>() {
314                                 @Override
315                                 public Void answer(InvocationOnMock invocation) throws Throwable {
316                                         postLikingSones.put(post, (Sone) invocation.getArguments()[0]);
317                                         return null;
318                                 }
319                         }).when(post).like(Matchers.<Sone>any());
320                         doAnswer(new Answer<Void>() {
321                                 @Override
322                                 public Void answer(InvocationOnMock invocation) throws Throwable {
323                                         postLikingSones.remove(post, (Sone) invocation.getArguments()[0]);
324                                         return null;
325                                 }
326                         }).when(post).unlike(Matchers.<Sone>any());
327                         when(post.getLikes()).thenAnswer(new Answer<Set<Sone>>() {
328                                 @Override
329                                 public Set<Sone> answer(InvocationOnMock invocation) throws Throwable {
330                                         return postLikingSones.get(post);
331                                 }
332                         });
333                         return post;
334                 }
335
336         }
337
338         public class PostReplyMocker {
339
340                 private final PostReply postReply = mock(PostReply.class);
341                 private final String id;
342                 private final Sone sone;
343                 private Optional<Post> post = absent();
344                 private long time;
345                 private Optional<String> text = absent();
346
347                 public PostReplyMocker(String id, Sone sone) {
348                         this.id = id;
349                         this.sone = sone;
350                 }
351
352                 public PostReplyMocker inReplyTo(Post post) {
353                         this.post = fromNullable(post);
354                         return this;
355                 }
356
357                 public PostReplyMocker withTime(long time) {
358                         this.time = time;
359                         return this;
360                 }
361
362                 public PostReplyMocker withText(String text) {
363                         this.text = fromNullable(text);
364                         return this;
365                 }
366
367                 public PostReply create() {
368                         when(postReply.getId()).thenReturn(id);
369                         when(postReply.getSone()).thenReturn(sone);
370                         when(postReply.getTime()).thenReturn(time);
371                         when(database.getPostReply(eq(id))).thenReturn(of(postReply));
372                         if (post.isPresent()) {
373                                 postReplies.put(post.get(), postReply);
374                         }
375                         if (text.isPresent()) {
376                                 when(postReply.getText()).thenReturn(text.get());
377                         }
378                         doAnswer(new Answer<Void>() {
379                                 @Override
380                                 public Void answer(InvocationOnMock invocation) throws Throwable {
381                                         postReplyLikingSones.put(postReply, (Sone) invocation.getArguments()[0]);
382                                         return null;
383                                 }
384                         }).when(postReply).like(Matchers.<Sone>any());
385                         doAnswer(new Answer<Void>() {
386                                 @Override
387                                 public Void answer(InvocationOnMock invocation) throws Throwable {
388                                         postReplyLikingSones.remove(postReply, invocation.getArguments()[0]);
389                                         return null;
390                                 }
391                         }).when(postReply).unlike(Matchers.<Sone>any());
392                         when(postReply.getLikes()).thenAnswer(new Answer<Set<Sone>>() {
393                                 @Override
394                                 public Set<Sone> answer(InvocationOnMock invocation) throws Throwable {
395                                         return postReplyLikingSones.get(postReply);
396                                 }
397                         });
398                         return postReply;
399                 }
400         }
401
402 }