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