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