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