Mock some post database interactions.
[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.PostBuilder.PostCreated;
51 import net.pterodactylus.sone.database.PostReplyBuilder;
52 import net.pterodactylus.sone.fcp.FcpInterface.FullAccessRequired;
53 import net.pterodactylus.sone.utils.IntegerRangePredicate;
54 import net.pterodactylus.sone.web.WebInterface;
55 import net.pterodactylus.sone.web.page.FreenetRequest;
56
57 import freenet.clients.http.HTTPRequestImpl;
58 import freenet.support.api.HTTPRequest;
59
60 import com.google.common.base.Function;
61 import com.google.common.base.Optional;
62 import com.google.common.base.Predicates;
63 import com.google.common.collect.FluentIterable;
64 import com.google.common.collect.HashMultimap;
65 import com.google.common.collect.Multimap;
66 import com.google.common.collect.Ordering;
67 import com.google.common.collect.SetMultimap;
68 import org.mockito.Matchers;
69 import org.mockito.invocation.InvocationOnMock;
70 import org.mockito.stubbing.Answer;
71
72 /**
73  * Mocks reusable in multiple tests.
74  *
75  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76  */
77 public class Mocks {
78
79         private final Multimap<Sone, Post> sonePosts = create();
80         private final Map<String, Sone> sones = newHashMap();
81         private final Map<String, Post> posts = newHashMap();
82         private final Multimap<Post, PostReply> postReplies = create();
83         private final Multimap<String, Post> directedPosts = create();
84         private final SetMultimap<Post, Sone> postLikingSones = HashMultimap.create();
85         private final SetMultimap<PostReply, Sone> postReplyLikingSones = HashMultimap.create();
86         public final Database database;
87         public final Core core;
88         public final WebInterface webInterface;
89
90         public Mocks() {
91                 database = mockDatabase();
92                 core = mockCore(database);
93                 webInterface = mockWebInterface(core);
94                 when(database.getSone()).thenReturn(new Function<String, Optional<Sone>>() {
95                         @Override
96                         public Optional<Sone> apply(String soneId) {
97                                 return (soneId == null) ? Optional.<Sone>absent() : fromNullable(sones.get(soneId));
98                         }
99                 });
100                 when(core.getSones()).then(new Answer<Collection<Sone>>() {
101                         @Override
102                         public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
103                                 return sones.values();
104                         }
105                 });
106                 when(core.getLocalSone(anyString())).then(new Answer<Optional<Sone>>() {
107                         @Override
108                         public Optional<Sone> answer(InvocationOnMock invocation) throws Throwable {
109                                 Sone localSone = sones.get(invocation.getArguments()[0]);
110                                 return ((localSone == null) || (!localSone.isLocal())) ? Optional.<Sone>absent() : of(localSone);
111                         }
112                 });
113                 when(core.getLocalSones()).then(new Answer<Collection<Sone>>() {
114                         @Override
115                         public Collection<Sone> answer(InvocationOnMock invocation) throws Throwable {
116                                 return FluentIterable.from(sones.values()).filter(Sone.LOCAL_SONE_FILTER).toList();
117                         }
118                 });
119                 when(core.postCreated()).thenReturn(Optional.<PostCreated>of(new PostCreated() {
120                         @Override
121                         public void postCreated(Post post) {
122                                 posts.put(post.getId(), post);
123                                 sonePosts.put(post.getSone(), post);
124                         }
125                 }));
126                 Options options = createOptions();
127                 when(core.getPreferences()).thenReturn(new Preferences(options));
128                 when(database.getDirectedPosts(anyString())).then(new Answer<Collection<Post>>() {
129                         @Override
130                         public Collection<Post> answer(InvocationOnMock invocation) throws Throwable {
131                                 return directedPosts.get((String) invocation.getArguments()[0]);
132                         }
133                 });
134         }
135
136         private Options createOptions() {
137                 Options options = new Options();
138                 options.addIntegerOption("InsertionDelay", new DefaultOption<Integer>(60, new IntegerRangePredicate(0, Integer.MAX_VALUE)));
139                 options.addIntegerOption("PostsPerPage", new DefaultOption<Integer>(10, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
140                 options.addIntegerOption("ImagesPerPage", new DefaultOption<Integer>(9, new IntegerRangePredicate(1, Integer.MAX_VALUE)));
141                 options.addIntegerOption("CharactersPerPost", new DefaultOption<Integer>(400, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
142                 options.addIntegerOption("PostCutOffLength", new DefaultOption<Integer>(200, Predicates.<Integer>or(new IntegerRangePredicate(50, Integer.MAX_VALUE), Predicates.equalTo(-1))));
143                 options.addBooleanOption("RequireFullAccess", new DefaultOption<Boolean>(false));
144                 options.addIntegerOption("PositiveTrust", new DefaultOption<Integer>(75, new IntegerRangePredicate(0, 100)));
145                 options.addIntegerOption("NegativeTrust", new DefaultOption<Integer>(-25, new IntegerRangePredicate(-100, 100)));
146                 options.addStringOption("TrustComment", new DefaultOption<String>("Set from Sone Web Interface"));
147                 options.addBooleanOption("ActivateFcpInterface", new DefaultOption<Boolean>(false));
148                 options.addIntegerOption("FcpFullAccessRequired", new DefaultOption<Integer>(2));
149                 return options;
150         }
151
152         private static Core mockCore(Database database) {
153                 Core core = mock(Core.class);
154                 when(core.getDatabase()).thenReturn(database);
155                 when(core.getSone(anyString())).thenReturn(Optional.<Sone>absent());
156                 return core;
157         }
158
159         private Database mockDatabase() {
160                 Database database = mock(Database.class);
161                 when(database.getSone(anyString())).thenReturn(Optional.<Sone>absent());
162                 when(database.getPost(anyString())).then(new Answer<Optional<Post>>() {
163                         @Override
164                         public Optional<Post> answer(InvocationOnMock invocation) throws Throwable {
165                                 return fromNullable(posts.get(invocation.getArguments()[0]));
166                         }
167                 });
168                 when(database.getPostReply(anyString())).thenReturn(Optional.<PostReply>absent());
169                 return database;
170         }
171
172         private static WebInterface mockWebInterface(Core core) {
173                 WebInterface webInterface = mock(WebInterface.class);
174                 when(webInterface.getCore()).thenReturn(core);
175                 return webInterface;
176         }
177
178         public SoneMocker mockSone(String id) {
179                 return new SoneMocker(id);
180         }
181
182         public PostMocker mockPost(Sone sone, String postId) {
183                 return new PostMocker(postId, sone);
184         }
185
186         public PostReplyMocker mockPostReply(Sone sone, String replyId) {
187                 return new PostReplyMocker(replyId, sone);
188         }
189
190         public FreenetRequest mockRequest(String path) {
191                 HTTPRequest httpRequest = mock(HTTPRequest.class);
192                 when(httpRequest.getMethod()).thenReturn("GET");
193                 when(httpRequest.getPath()).thenReturn(path);
194                 FreenetRequest request = mock(FreenetRequest.class);
195                 when(request.getHttpRequest()).thenReturn(httpRequest);
196                 return request;
197         }
198
199         public class SoneMocker {
200
201                 private final Sone mockedSone = mock(Sone.class);
202                 private final String id;
203                 private boolean local;
204                 private Optional<String> name = absent();
205                 private long time;
206                 private Profile profile = new Profile(mockedSone);
207                 private Collection<String> friends = emptySet();
208
209                 private SoneMocker(String id) {
210                         this.id = id;
211                 }
212
213                 public SoneMocker local() {
214                         local = true;
215                         return this;
216                 }
217
218                 public SoneMocker withName(String name) {
219                         this.name = fromNullable(name);
220                         return this;
221                 }
222
223                 public SoneMocker withTime(long time) {
224                         this.time = time;
225                         return this;
226                 }
227
228                 public SoneMocker withProfileName(String firstName, String middleName, String lastName) {
229                         profile.modify().setFirstName(firstName).setMiddleName(middleName).setLastName(lastName).update();
230                         return this;
231                 }
232
233                 public SoneMocker addProfileField(String fieldName, String fieldValue) {
234                         profile.setField(profile.addField(fieldName), fieldValue);
235                         return this;
236                 }
237
238                 public SoneMocker withFriends(Collection<String> friends) {
239                         this.friends = friends;
240                         return this;
241                 }
242
243                 public Sone create() {
244                         when(mockedSone.getId()).thenReturn(id);
245                         when(mockedSone.isLocal()).thenReturn(local);
246                         if (name.isPresent()) {
247                                 when(mockedSone.getName()).thenReturn(name.get());
248                         }
249                         when(mockedSone.getTime()).thenReturn(time);
250                         when(mockedSone.getProfile()).thenReturn(profile);
251                         if (local) {
252                                 when(mockedSone.newPostBuilder()).thenReturn(new DefaultPostBuilder(database, id));
253                                 when(mockedSone.newPostReplyBuilder(anyString())).then(new Answer<PostReplyBuilder>() {
254                                         @Override
255                                         public PostReplyBuilder answer(InvocationOnMock invocation) throws Throwable {
256                                                 return new DefaultPostReplyBuilder(database, id, (String) invocation.getArguments()[0]);
257                                         }
258                                 });
259                                 when(mockedSone.hasFriend(anyString())).thenReturn(false);
260                                 when(mockedSone.getFriends()).thenReturn(friends);
261                                 when(mockedSone.hasFriend(anyString())).then(new Answer<Boolean>() {
262                                         @Override
263                                         public Boolean answer(InvocationOnMock invocation) throws Throwable {
264                                                 return friends.contains(invocation.getArguments()[0]);
265                                         }
266                                 });
267                         } else {
268                                 when(mockedSone.newPostBuilder()).thenThrow(IllegalStateException.class);
269                                 when(mockedSone.newPostReplyBuilder(anyString())).thenThrow(IllegalStateException.class);
270                         }
271                         when(core.getSone(eq(id))).thenReturn(of(mockedSone));
272                         when(database.getSone(eq(id))).thenReturn(of(mockedSone));
273                         when(mockedSone.getPosts()).then(new Answer<List<Post>>() {
274                                 @Override
275                                 public List<Post> answer(InvocationOnMock invocationOnMock) throws Throwable {
276                                         return from(Post.TIME_COMPARATOR).sortedCopy(sonePosts.get(mockedSone));
277                                 }
278                         });
279                         when(mockedSone.toString()).thenReturn(String.format("Sone[%s]", id));
280                         sones.put(id, mockedSone);
281                         return mockedSone;
282                 }
283
284         }
285
286         public class PostMocker {
287
288                 private final Post post = mock(Post.class);
289                 private final String id;
290                 private final Sone sone;
291                 private Optional<String> recipientId = absent();
292                 private long time;
293                 private Optional<String> text = absent();
294
295                 public PostMocker(String id, Sone sone) {
296                         this.id = id;
297                         this.sone = sone;
298                 }
299
300                 public PostMocker withRecipient(String recipientId) {
301                         this.recipientId = fromNullable(recipientId);
302                         return this;
303                 }
304
305                 public PostMocker withTime(long time) {
306                         this.time = time;
307                         return this;
308                 }
309
310                 public PostMocker withText(String text) {
311                         this.text = fromNullable(text);
312                         return this;
313                 }
314
315                 public Post create() {
316                         when(post.getId()).thenReturn(id);
317                         when(post.getSone()).thenReturn(sone);
318                         when(post.getRecipientId()).thenReturn(recipientId);
319                         if (recipientId.isPresent()) {
320                                 directedPosts.put(recipientId.get(), post);
321                         }
322                         when(post.getTime()).thenReturn(time);
323                         if (text.isPresent()) {
324                                 when(post.getText()).thenReturn(text.get());
325                         }
326                         when(database.getPost(eq(id))).thenReturn(of(post));
327                         sonePosts.put(sone, post);
328                         when(post.getReplies()).then(new Answer<List<PostReply>>() {
329                                 @Override
330                                 public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
331                                         return Ordering.from(Reply.TIME_COMPARATOR).sortedCopy(postReplies.get(post));
332                                 }
333                         });
334                         doAnswer(new Answer<Void>() {
335                                 @Override
336                                 public Void answer(InvocationOnMock invocation) throws Throwable {
337                                         postLikingSones.put(post, (Sone) invocation.getArguments()[0]);
338                                         return null;
339                                 }
340                         }).when(post).like(Matchers.<Sone>any());
341                         doAnswer(new Answer<Void>() {
342                                 @Override
343                                 public Void answer(InvocationOnMock invocation) throws Throwable {
344                                         postLikingSones.remove(post, (Sone) invocation.getArguments()[0]);
345                                         return null;
346                                 }
347                         }).when(post).unlike(Matchers.<Sone>any());
348                         when(post.getLikes()).thenAnswer(new Answer<Set<Sone>>() {
349                                 @Override
350                                 public Set<Sone> answer(InvocationOnMock invocation) throws Throwable {
351                                         return postLikingSones.get(post);
352                                 }
353                         });
354                         return post;
355                 }
356
357         }
358
359         public class PostReplyMocker {
360
361                 private final PostReply postReply = mock(PostReply.class);
362                 private final String id;
363                 private final Sone sone;
364                 private Optional<Post> post = absent();
365                 private long time;
366                 private Optional<String> text = absent();
367
368                 public PostReplyMocker(String id, Sone sone) {
369                         this.id = id;
370                         this.sone = sone;
371                 }
372
373                 public PostReplyMocker inReplyTo(Post post) {
374                         this.post = fromNullable(post);
375                         return this;
376                 }
377
378                 public PostReplyMocker withTime(long time) {
379                         this.time = time;
380                         return this;
381                 }
382
383                 public PostReplyMocker withText(String text) {
384                         this.text = fromNullable(text);
385                         return this;
386                 }
387
388                 public PostReply create() {
389                         when(postReply.getId()).thenReturn(id);
390                         when(postReply.getSone()).thenReturn(sone);
391                         when(postReply.getTime()).thenReturn(time);
392                         when(database.getPostReply(eq(id))).thenReturn(of(postReply));
393                         if (post.isPresent()) {
394                                 postReplies.put(post.get(), postReply);
395                         }
396                         if (text.isPresent()) {
397                                 when(postReply.getText()).thenReturn(text.get());
398                         }
399                         doAnswer(new Answer<Void>() {
400                                 @Override
401                                 public Void answer(InvocationOnMock invocation) throws Throwable {
402                                         postReplyLikingSones.put(postReply, (Sone) invocation.getArguments()[0]);
403                                         return null;
404                                 }
405                         }).when(postReply).like(Matchers.<Sone>any());
406                         doAnswer(new Answer<Void>() {
407                                 @Override
408                                 public Void answer(InvocationOnMock invocation) throws Throwable {
409                                         postReplyLikingSones.remove(postReply, invocation.getArguments()[0]);
410                                         return null;
411                                 }
412                         }).when(postReply).unlike(Matchers.<Sone>any());
413                         when(postReply.getLikes()).thenAnswer(new Answer<Set<Sone>>() {
414                                 @Override
415                                 public Set<Sone> answer(InvocationOnMock invocation) throws Throwable {
416                                         return postReplyLikingSones.get(postReply);
417                                 }
418                         });
419                         return postReply;
420                 }
421         }
422
423 }