Make it possible to mock a Sone’s insert URI.
[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.freenet.wot.OwnIdentity;
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 String insertUrI;
222                 private boolean local;
223                 private boolean current;
224                 private Optional<String> name = absent();
225                 private long time;
226                 private Profile profile = new Profile(mockedSone);
227                 private Collection<String> friends = emptySet();
228
229                 private SoneMocker(String id) {
230                         this.id = id;
231                 }
232
233                 public SoneMocker local() {
234                         local = true;
235                         return this;
236                 }
237
238                 public SoneMocker insertUri(String insertUri) {
239                         this.insertUrI = insertUri;
240                         return this;
241                 }
242
243                 public SoneMocker current() {
244                         current = true;
245                         return this;
246                 }
247
248                 public SoneMocker withName(String name) {
249                         this.name = fromNullable(name);
250                         return this;
251                 }
252
253                 public SoneMocker withTime(long time) {
254                         this.time = time;
255                         return this;
256                 }
257
258                 public SoneMocker withProfileName(String firstName, String middleName, String lastName) {
259                         profile.modify().setFirstName(firstName).setMiddleName(middleName).setLastName(lastName).update();
260                         return this;
261                 }
262
263                 public SoneMocker addProfileField(String fieldName, String fieldValue) {
264                         profile.setField(profile.addField(fieldName), fieldValue);
265                         return this;
266                 }
267
268                 public SoneMocker withFriends(Collection<String> friends) {
269                         this.friends = friends;
270                         return this;
271                 }
272
273                 public Sone create() {
274                         when(mockedSone.getId()).thenReturn(id);
275                         when(mockedSone.isLocal()).thenReturn(local);
276                         if (local) {
277                                 OwnIdentity ownIdentity = mock(OwnIdentity.class);
278                                 when(ownIdentity.getInsertUri()).thenReturn(insertUrI);
279                                 when(mockedSone.getIdentity()).thenReturn(ownIdentity);
280                         }
281                         if (current) {
282                                 currentSone = of(mockedSone);
283                         }
284                         if (name.isPresent()) {
285                                 when(mockedSone.getName()).thenReturn(name.get());
286                         }
287                         when(mockedSone.getTime()).thenReturn(time);
288                         when(mockedSone.getProfile()).thenReturn(profile);
289                         if (local) {
290                                 when(mockedSone.newPostBuilder()).thenReturn(new DefaultPostBuilder(database, id));
291                                 when(mockedSone.newPostReplyBuilder(anyString())).then(new Answer<PostReplyBuilder>() {
292                                         @Override
293                                         public PostReplyBuilder answer(InvocationOnMock invocation) throws Throwable {
294                                                 return new DefaultPostReplyBuilder(database, id, (String) invocation.getArguments()[0]);
295                                         }
296                                 });
297                                 when(mockedSone.hasFriend(anyString())).thenReturn(false);
298                                 when(mockedSone.getFriends()).thenReturn(friends);
299                                 when(mockedSone.hasFriend(anyString())).then(new Answer<Boolean>() {
300                                         @Override
301                                         public Boolean answer(InvocationOnMock invocation) throws Throwable {
302                                                 return friends.contains(invocation.getArguments()[0]);
303                                         }
304                                 });
305                         } else {
306                                 when(mockedSone.newPostBuilder()).thenThrow(IllegalStateException.class);
307                                 when(mockedSone.newPostReplyBuilder(anyString())).thenThrow(IllegalStateException.class);
308                         }
309                         when(core.getSone(eq(id))).thenReturn(of(mockedSone));
310                         when(database.getSone(eq(id))).thenReturn(of(mockedSone));
311                         when(mockedSone.getPosts()).then(new Answer<List<Post>>() {
312                                 @Override
313                                 public List<Post> answer(InvocationOnMock invocationOnMock) throws Throwable {
314                                         return from(Post.TIME_COMPARATOR).sortedCopy(sonePosts.get(mockedSone));
315                                 }
316                         });
317                         when(mockedSone.toString()).thenReturn(String.format("Sone[%s]", id));
318                         sones.put(id, mockedSone);
319                         return mockedSone;
320                 }
321
322         }
323
324         public class PostMocker {
325
326                 private final Post post = mock(Post.class);
327                 private final String id;
328                 private final Sone sone;
329                 private Optional<String> recipientId = absent();
330                 private long time;
331                 private Optional<String> text = absent();
332
333                 public PostMocker(String id, Sone sone) {
334                         this.id = id;
335                         this.sone = sone;
336                 }
337
338                 public PostMocker withRecipient(String recipientId) {
339                         this.recipientId = fromNullable(recipientId);
340                         return this;
341                 }
342
343                 public PostMocker withTime(long time) {
344                         this.time = time;
345                         return this;
346                 }
347
348                 public PostMocker withText(String text) {
349                         this.text = fromNullable(text);
350                         return this;
351                 }
352
353                 public Post create() {
354                         when(post.getId()).thenReturn(id);
355                         when(post.getSone()).thenReturn(sone);
356                         when(post.getRecipientId()).thenReturn(recipientId);
357                         if (recipientId.isPresent()) {
358                                 directedPosts.put(recipientId.get(), post);
359                         }
360                         when(post.getTime()).thenReturn(time);
361                         if (text.isPresent()) {
362                                 when(post.getText()).thenReturn(text.get());
363                         }
364                         when(database.getPost(eq(id))).thenReturn(of(post));
365                         sonePosts.put(sone, post);
366                         when(post.getReplies()).then(new Answer<List<PostReply>>() {
367                                 @Override
368                                 public List<PostReply> answer(InvocationOnMock invocation) throws Throwable {
369                                         return Ordering.from(Reply.TIME_COMPARATOR).sortedCopy(postReplies.get(post));
370                                 }
371                         });
372                         doAnswer(new Answer<Void>() {
373                                 @Override
374                                 public Void answer(InvocationOnMock invocation) throws Throwable {
375                                         postLikingSones.put(post, (Sone) invocation.getArguments()[0]);
376                                         return null;
377                                 }
378                         }).when(post).like(Matchers.<Sone>any());
379                         doAnswer(new Answer<Void>() {
380                                 @Override
381                                 public Void answer(InvocationOnMock invocation) throws Throwable {
382                                         postLikingSones.remove(post, (Sone) invocation.getArguments()[0]);
383                                         return null;
384                                 }
385                         }).when(post).unlike(Matchers.<Sone>any());
386                         when(post.getLikes()).thenAnswer(new Answer<Set<Sone>>() {
387                                 @Override
388                                 public Set<Sone> answer(InvocationOnMock invocation) throws Throwable {
389                                         return postLikingSones.get(post);
390                                 }
391                         });
392                         return post;
393                 }
394
395         }
396
397         public class PostReplyMocker {
398
399                 private final PostReply postReply = mock(PostReply.class);
400                 private final String id;
401                 private final Sone sone;
402                 private Optional<Post> post = absent();
403                 private long time;
404                 private Optional<String> text = absent();
405
406                 public PostReplyMocker(String id, Sone sone) {
407                         this.id = id;
408                         this.sone = sone;
409                 }
410
411                 public PostReplyMocker inReplyTo(Post post) {
412                         this.post = fromNullable(post);
413                         return this;
414                 }
415
416                 public PostReplyMocker withTime(long time) {
417                         this.time = time;
418                         return this;
419                 }
420
421                 public PostReplyMocker withText(String text) {
422                         this.text = fromNullable(text);
423                         return this;
424                 }
425
426                 public PostReply create() {
427                         when(postReply.getId()).thenReturn(id);
428                         when(postReply.getSone()).thenReturn(sone);
429                         when(postReply.getTime()).thenReturn(time);
430                         when(database.getPostReply(eq(id))).thenReturn(of(postReply));
431                         if (post.isPresent()) {
432                                 postReplies.put(post.get(), postReply);
433                         }
434                         if (text.isPresent()) {
435                                 when(postReply.getText()).thenReturn(text.get());
436                         }
437                         doAnswer(new Answer<Void>() {
438                                 @Override
439                                 public Void answer(InvocationOnMock invocation) throws Throwable {
440                                         postReplyLikingSones.put(postReply, (Sone) invocation.getArguments()[0]);
441                                         return null;
442                                 }
443                         }).when(postReply).like(Matchers.<Sone>any());
444                         doAnswer(new Answer<Void>() {
445                                 @Override
446                                 public Void answer(InvocationOnMock invocation) throws Throwable {
447                                         postReplyLikingSones.remove(postReply, invocation.getArguments()[0]);
448                                         return null;
449                                 }
450                         }).when(postReply).unlike(Matchers.<Sone>any());
451                         when(postReply.getLikes()).thenAnswer(new Answer<Set<Sone>>() {
452                                 @Override
453                                 public Set<Sone> answer(InvocationOnMock invocation) throws Throwable {
454                                         return postReplyLikingSones.get(postReply);
455                                 }
456                         });
457                         return postReply;
458                 }
459         }
460
461 }