8da6498c48484132452db175cccff57b63695cf2
[Sone.git] / src / test / java / net / pterodactylus / sone / database / memory / MemoryDatabaseTest.java
1 /*
2  * Sone - MemoryDatabaseTest.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.database.memory;
19
20 import static com.google.common.base.Optional.of;
21 import static java.util.Arrays.asList;
22 import static java.util.UUID.randomUUID;
23 import static net.pterodactylus.sone.Matchers.isAlbum;
24 import static net.pterodactylus.sone.Matchers.isImage;
25 import static net.pterodactylus.sone.Matchers.isPost;
26 import static net.pterodactylus.sone.Matchers.isPostReply;
27 import static org.hamcrest.CoreMatchers.is;
28 import static org.hamcrest.MatcherAssert.assertThat;
29 import static org.hamcrest.Matchers.contains;
30 import static org.hamcrest.Matchers.containsInAnyOrder;
31 import static org.hamcrest.Matchers.empty;
32 import static org.hamcrest.Matchers.hasKey;
33 import static org.hamcrest.Matchers.not;
34 import static org.hamcrest.Matchers.nullValue;
35 import static org.mockito.Matchers.anyString;
36 import static org.mockito.Mockito.mock;
37 import static org.mockito.Mockito.never;
38 import static org.mockito.Mockito.verify;
39 import static org.mockito.Mockito.when;
40
41 import java.util.Collection;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Set;
47
48 import net.pterodactylus.sone.Matchers.IncompletePostMatcher;
49 import net.pterodactylus.sone.TestAlbumBuilder;
50 import net.pterodactylus.sone.TestImageBuilder;
51 import net.pterodactylus.sone.TestPostBuilder;
52 import net.pterodactylus.sone.TestPostReplyBuilder;
53 import net.pterodactylus.sone.TestValue;
54 import net.pterodactylus.sone.data.Album;
55 import net.pterodactylus.sone.data.Image;
56 import net.pterodactylus.sone.data.LocalSone;
57 import net.pterodactylus.sone.data.Post;
58 import net.pterodactylus.sone.data.PostReply;
59 import net.pterodactylus.sone.data.Sone;
60 import net.pterodactylus.sone.data.impl.AlbumImpl;
61 import net.pterodactylus.util.config.Configuration;
62 import net.pterodactylus.util.config.ConfigurationException;
63 import net.pterodactylus.util.config.Value;
64
65 import com.google.common.base.Optional;
66 import org.junit.Before;
67 import org.junit.Test;
68 import org.mockito.Mockito;
69 import org.mockito.invocation.InvocationOnMock;
70 import org.mockito.stubbing.Answer;
71
72 /**
73  * Tests for {@link MemoryDatabase}.
74  *
75  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
76  */
77 public class MemoryDatabaseTest {
78
79         private static final String SONE_ID = "sone";
80         private static final String RECIPIENT_ID = "recipient";
81         private final Configuration configuration = mock(Configuration.class);
82         private final MemoryDatabase memoryDatabase = new MemoryDatabase(null, configuration);
83         private final Sone sone = mock(Sone.class);
84         private final LocalSone localSone = mock(LocalSone.class);
85         private final Map<String, Value<String>> stringValues = new HashMap<String, Value<String>>();
86         private final Map<String, Value<Long>> longValues = new HashMap<String, Value<Long>>();
87
88         @Before
89         public void prepareConfigurationValues() {
90                 when(configuration.getStringValue(anyString())).thenAnswer(new Answer<Value<String>>() {
91                         @Override
92                         public Value<String> answer(InvocationOnMock invocation) throws Throwable {
93                                 final String key = (String) invocation.getArguments()[0];
94                                 if (!stringValues.containsKey(key)) {
95                                         TestValue<String> value = Mockito.spy(new TestValue<String>(null) {
96                                                 @Override
97                                                 public void setValue(String newValue) throws ConfigurationException {
98                                                         super.setValue(newValue);
99                                                         stringValues.put(key, this);
100                                                 }
101                                         });
102                                         stringValues.put(key, value);
103                                 }
104                                 return stringValues.get(key);
105                         }
106                 });
107                 when(configuration.getLongValue(anyString())).thenAnswer(new Answer<Value<Long>>() {
108                         @Override
109                         public Value<Long> answer(InvocationOnMock invocation) throws Throwable {
110                                 final String key = (String) invocation.getArguments()[0];
111                                 if (!longValues.containsKey(key)) {
112                                         TestValue<Long> value = Mockito.spy(new TestValue<Long>(null) {
113                                                 @Override
114                                                 public void setValue(Long newValue) throws ConfigurationException {
115                                                         super.setValue(newValue);
116                                                         longValues.put(key, this);
117                                                 }
118                                         });
119                                         longValues.put(key, value);
120                                 }
121                                 return longValues.get(key);
122                         }
123                 });
124         }
125
126         @Before
127         public void setupSones() {
128                 when(sone.getId()).thenReturn(SONE_ID);
129                 when(localSone.getId()).thenReturn(SONE_ID);
130                 when(localSone.isLocal()).thenReturn(true);
131         }
132
133         @Test
134         public void storedSoneIsMadeAvailable() {
135                 Post firstPost = new TestPostBuilder().withId("post1")
136                                 .from(SONE_ID)
137                                 .withTime(1000L)
138                                 .withText("post1")
139                                 .build();
140                 Post secondPost = new TestPostBuilder().withId("post2")
141                                 .from(SONE_ID)
142                                 .withTime(2000L)
143                                 .withText("post2")
144                                 .to(RECIPIENT_ID)
145                                 .build();
146                 List<Post> posts = asList(firstPost, secondPost);
147                 when(sone.getPosts()).thenReturn(posts);
148                 PostReply firstPostFirstReply =
149                                 new TestPostReplyBuilder().withId("reply1")
150                                                 .from(SONE_ID)
151                                                 .to(firstPost.getId())
152                                                 .withTime(3000L)
153                                                 .withText("reply1")
154                                                 .build();
155                 PostReply firstPostSecondReply =
156                                 new TestPostReplyBuilder().withId("reply3")
157                                                 .from(RECIPIENT_ID)
158                                                 .to(firstPost.getId())
159                                                 .withTime(5000L)
160                                                 .withText("reply3")
161                                                 .build();
162                 PostReply secondPostReply =
163                                 new TestPostReplyBuilder().withId("reply2")
164                                                 .from(SONE_ID)
165                                                 .to(secondPost.getId())
166                                                 .withTime(4000L)
167                                                 .withText("reply2")
168                                                 .build();
169                 Set<PostReply> postReplies = new HashSet<PostReply>(
170                                 asList(firstPostFirstReply, firstPostSecondReply,
171                                                 secondPostReply));
172                 when(sone.getReplies()).thenReturn(postReplies);
173                 Album firstAlbum = new TestAlbumBuilder().withId("album1")
174                                 .by(sone)
175                                 .build()
176                                 .modify()
177                                 .setTitle("album1")
178                                 .setDescription("album-description1")
179                                 .update();
180                 Album secondAlbum = new TestAlbumBuilder().withId("album2").by(
181                                 sone).build().modify().setTitle("album2").setDescription(
182                                 "album-description2").setAlbumImage("image1").update();
183                 Album thirdAlbum = new TestAlbumBuilder().withId("album3").by(
184                                 sone).build().modify().setTitle("album3").setDescription(
185                                 "album-description3").update();
186                 firstAlbum.addAlbum(thirdAlbum);
187                 Album rootAlbum = mock(Album.class);
188                 when(rootAlbum.getAlbums()).thenReturn(
189                                 asList(firstAlbum, secondAlbum));
190                 when(sone.getRootAlbum()).thenReturn(rootAlbum);
191                 Image firstImage = new TestImageBuilder().withId("image1")
192                                 .build()
193                                 .modify()
194                                 .setSone(sone)
195                                 .setCreationTime(1000L)
196                                 .setKey("KSK@image1")
197                                 .setTitle("image1")
198                                 .setDescription("image-description1")
199                                 .setWidth(16)
200                                 .setHeight(9)
201                                 .update();
202                 Image secondImage = new TestImageBuilder().withId("image2")
203                                 .build()
204                                 .modify()
205                                 .setSone(sone)
206                                 .setCreationTime(2000L)
207                                 .setKey("KSK@image2")
208                                 .setTitle("image2")
209                                 .setDescription("image-description2")
210                                 .setWidth(32)
211                                 .setHeight(18)
212                                 .update();
213                 Image thirdImage = new TestImageBuilder().withId("image3")
214                                 .build()
215                                 .modify()
216                                 .setSone(sone)
217                                 .setCreationTime(3000L)
218                                 .setKey("KSK@image3")
219                                 .setTitle("image3")
220                                 .setDescription("image-description3")
221                                 .setWidth(48)
222                                 .setHeight(27)
223                                 .update();
224                 firstAlbum.addImage(firstImage);
225                 firstAlbum.addImage(thirdImage);
226                 secondAlbum.addImage(secondImage);
227                 memoryDatabase.storeSone(sone);
228                 assertThat(memoryDatabase.getPost("post1").get(),
229                                 isPost(firstPost.getId(), 1000L, "post1",
230                                                 Optional.<String>absent()));
231                 assertThat(memoryDatabase.getPost("post2").get(),
232                                 isPost(secondPost.getId(), 2000L, "post2", of(RECIPIENT_ID)));
233                 assertThat(memoryDatabase.getPost("post3").isPresent(), is(false));
234                 assertThat(memoryDatabase.getPostReply("reply1").get(),
235                                 isPostReply("reply1", "post1", 3000L, "reply1"));
236                 assertThat(memoryDatabase.getPostReply("reply2").get(),
237                                 isPostReply("reply2", "post2", 4000L, "reply2"));
238                 assertThat(memoryDatabase.getPostReply("reply3").get(),
239                                 isPostReply("reply3", "post1", 5000L, "reply3"));
240                 assertThat(memoryDatabase.getPostReply("reply4").isPresent(),
241                                 is(false));
242                 assertThat(memoryDatabase.getAlbum("album1").get(),
243                                 isAlbum("album1", null, "album1", "album-description1",
244                                                 null));
245                 assertThat(memoryDatabase.getAlbum("album2").get(),
246                                 isAlbum("album2", null, "album2", "album-description2",
247                                                 "image1"));
248                 assertThat(memoryDatabase.getAlbum("album3").get(),
249                                 isAlbum("album3", "album1", "album3", "album-description3",
250                                                 null));
251                 assertThat(memoryDatabase.getAlbum("album4").isPresent(), is(false));
252                 assertThat(memoryDatabase.getImage("image1").get(),
253                                 isImage("image1", 1000L, "KSK@image1", "image1",
254                                                 "image-description1", 16, 9));
255                 assertThat(memoryDatabase.getImage("image2").get(),
256                                 isImage("image2", 2000L, "KSK@image2", "image2",
257                                                 "image-description2", 32, 18));
258                 assertThat(memoryDatabase.getImage("image3").get(),
259                                 isImage("image3", 3000L, "KSK@image3", "image3",
260                                                 "image-description3", 48, 27));
261                 assertThat(memoryDatabase.getImage("image4").isPresent(), is(false));
262         }
263
264         @Test
265         public void storedAndRemovedSoneIsNotAvailable() {
266                 storedSoneIsMadeAvailable();
267                 memoryDatabase.removeSone(sone);
268                 assertThat(memoryDatabase.getSones(), empty());
269         }
270
271         @Test
272         public void postRecipientsAreDetectedCorrectly() {
273                 Post postWithRecipient = createPost(of(RECIPIENT_ID));
274                 memoryDatabase.storePost(postWithRecipient);
275                 Post postWithoutRecipient = createPost(Optional.<String>absent());
276                 memoryDatabase.storePost(postWithoutRecipient);
277                 assertThat(memoryDatabase.getDirectedPosts(RECIPIENT_ID),
278                                 contains(IncompletePostMatcher.matches().recipient(RECIPIENT_ID)));
279         }
280
281         private Post createPost(Optional<String> recipient) {
282                 Post postWithRecipient = mock(Post.class);
283                 when(postWithRecipient.getId()).thenReturn(randomUUID().toString());
284                 when(postWithRecipient.getSone()).thenReturn(sone);
285                 when(postWithRecipient.getRecipientId()).thenReturn(recipient);
286                 return postWithRecipient;
287         }
288
289         @Test
290         public void postRepliesAreManagedCorrectly() {
291                 Post firstPost = createPost(Optional.<String>absent());
292                 PostReply firstPostFirstReply = createPostReply(firstPost, 1000L);
293                 Post secondPost = createPost(Optional.<String>absent());
294                 PostReply secondPostFirstReply = createPostReply(secondPost, 1000L);
295                 PostReply secondPostSecondReply = createPostReply(secondPost, 2000L);
296                 memoryDatabase.storePost(firstPost);
297                 memoryDatabase.storePost(secondPost);
298                 memoryDatabase.storePostReply(firstPostFirstReply);
299                 memoryDatabase.storePostReply(secondPostFirstReply);
300                 memoryDatabase.storePostReply(secondPostSecondReply);
301                 assertThat(memoryDatabase.getReplies(firstPost.getId()),
302                                 contains(firstPostFirstReply));
303                 assertThat(memoryDatabase.getReplies(secondPost.getId()),
304                                 contains(secondPostFirstReply, secondPostSecondReply));
305         }
306
307         private PostReply createPostReply(Post post, long time) {
308                 PostReply postReply = mock(PostReply.class);
309                 when(postReply.getId()).thenReturn(randomUUID().toString());
310                 when(postReply.getTime()).thenReturn(time);
311                 when(postReply.getPost()).thenReturn(of(post));
312                 final String postId = post.getId();
313                 when(postReply.getPostId()).thenReturn(postId);
314                 return postReply;
315         }
316
317         @Test
318         public void testBasicAlbumFunctionality() {
319                 Album newAlbum = new AlbumImpl(mock(Sone.class));
320                 assertThat(memoryDatabase.getAlbum(newAlbum.getId()), is(Optional.<Album>absent()));
321                 memoryDatabase.storeAlbum(newAlbum);
322                 assertThat(memoryDatabase.getAlbum(newAlbum.getId()), is(of(newAlbum)));
323                 memoryDatabase.removeAlbum(newAlbum);
324                 assertThat(memoryDatabase.getAlbum(newAlbum.getId()), is(Optional.<Album>absent()));
325         }
326
327         private void initializeFriends() {
328                 stringValues.put("Sone/" + SONE_ID + "/Friends/0/ID",
329                                 Mockito.spy(TestValue.from("Friend1")));
330                 stringValues.put("Sone/" + SONE_ID + "/Friends/1/ID",
331                                 Mockito.spy(TestValue.from("Friend2")));
332                 stringValues.put("Sone/" + SONE_ID + "/Friends/2/ID",
333                                 Mockito.spy(TestValue.<String>from(null)));
334         }
335
336         @Test
337         public void friendsAreReturnedCorrectly() {
338                 initializeFriends();
339                 Collection<String> friends = memoryDatabase.getFriends(localSone);
340                 assertThat(friends, containsInAnyOrder("Friend1", "Friend2"));
341         }
342
343         @Test
344         public void friendsAreOnlyLoadedOnceFromConfiguration() {
345                 friendsAreReturnedCorrectly();
346                 memoryDatabase.getFriends(localSone);
347                 verify(configuration).getStringValue("Sone/" + SONE_ID + "/Friends/0/ID");
348         }
349
350         @Test
351         public void checkingForAFriendReturnsTrue() {
352                 initializeFriends();
353                 when(sone.isLocal()).thenReturn(true);
354                 assertThat(memoryDatabase.isFriend(localSone, "Friend1"), is(true));
355         }
356
357         @Test
358         public void checkingForAFriendThatIsNotAFriendReturnsFalse() {
359                 initializeFriends();
360                 when(sone.isLocal()).thenReturn(true);
361                 assertThat(memoryDatabase.isFriend(localSone, "FriendX"), is(false));
362         }
363
364         @Test
365         public void friendIsAddedCorrectlyToLocalSone() throws ConfigurationException {
366                 when(sone.isLocal()).thenReturn(true);
367                 memoryDatabase.addFriend(localSone, "Friend1");
368                 assertThat(stringValues.get("Sone/" + SONE_ID + "/Friends/0/ID").getValue(),
369                                 is("Friend1"));
370                 assertThat(stringValues.get("Sone/" + SONE_ID + "/Friends/1/ID").getValue(),
371                                 nullValue());
372         }
373
374         @Test
375         public void configurationIsWrittenOnceIfFriendIsAddedTwice() throws ConfigurationException {
376                 when(sone.isLocal()).thenReturn(true);
377                 memoryDatabase.addFriend(localSone, "Friend1");
378                 memoryDatabase.addFriend(localSone, "Friend1");
379                 verify(configuration.getStringValue("Sone/" + SONE_ID + "/Friends/0/ID")).setValue(
380                                 anyString());
381         }
382
383         @Test
384         public void friendIsRemovedCorrectlyFromLocalSone() throws ConfigurationException {
385                 when(sone.isLocal()).thenReturn(true);
386                 memoryDatabase.addFriend(localSone, "Friend1");
387                 memoryDatabase.removeFriend(localSone, "Friend1");
388                 assertThat(stringValues.get("Sone/" + SONE_ID + "/Friends/0/ID").getValue(),
389                                 nullValue());
390                 assertThat(stringValues.get("Sone/" + SONE_ID + "/Friends/1/ID").getValue(),
391                                 nullValue());
392         }
393
394         @Test
395         public void configurationIsNotWrittenWhenANonFriendIsRemoved() throws ConfigurationException {
396                 when(sone.isLocal()).thenReturn(true);
397                 memoryDatabase.removeFriend(localSone, "Friend1");
398                 verify(stringValues.get("Sone/" + SONE_ID + "/Friends/0/ID"), never()).setValue(
399                                 anyString());
400         }
401
402         @Test
403         public void newDatabaseKnowsNoSones() {
404                 memoryDatabase.startAndWait();
405                 assertThat(memoryDatabase.isSoneKnown(sone), is(false));
406                 assertThat(stringValues, hasKey("KnownSones/0/ID"));
407                 assertThat(stringValues, not(hasKey("KnownSones/1/ID")));
408         }
409
410         @Test
411         public void databaseLoadsKnownSonesCorrectly() {
412                 stringValues.put("KnownSones/0/ID", TestValue.from(SONE_ID));
413                 memoryDatabase.startAndWait();
414                 assertThat(memoryDatabase.isSoneKnown(sone), is(true));
415         }
416
417         @Test
418         public void databaseStoresKnownSonesCorrectly() throws ConfigurationException {
419                 memoryDatabase.setSoneKnown(sone);
420                 assertThat(stringValues, hasKey("KnownSones/0/ID"));
421                 assertThat(stringValues.get("KnownSones/0/ID").getValue(), is(SONE_ID));
422                 assertThat(stringValues, hasKey("KnownSones/1/ID"));
423                 assertThat(stringValues.get("KnownSones/1/ID").getValue(), nullValue());
424                 assertThat(stringValues, not(hasKey("KnownSones/2/ID")));
425         }
426
427         @Test
428         public void stoppingTheDatabaseSavesTheKnownSones() throws ConfigurationException {
429                 stringValues.put("KnownSones/0/ID", Mockito.spy(TestValue.from(SONE_ID)));
430                 memoryDatabase.startAndWait();
431                 memoryDatabase.stopAndWait();
432                 verify(stringValues.get("KnownSones/0/ID")).setValue(SONE_ID);
433                 verify(stringValues.get("KnownSones/1/ID")).setValue(null);
434         }
435
436         @Test
437         public void soneFollowingTimesAreLoaded() {
438                 stringValues.put("SoneFollowingTimes/0/Sone", TestValue.from(SONE_ID));
439                 longValues.put("SoneFollowingTimes/0/Time", TestValue.from(1000L));
440                 memoryDatabase.startAndWait();
441                 assertThat(memoryDatabase.getSoneFollowingTime(SONE_ID).get(), is(1000L));
442         }
443
444         @Test
445         public void soneFollowingTimeIsSetOnFirstFollowing() {
446                 memoryDatabase.startAndWait();
447                 memoryDatabase.addFriend(localSone, "Friend1");
448                 assertThat(stringValues, hasKey("SoneFollowingTimes/0/Sone"));
449                 assertThat(stringValues, hasKey("SoneFollowingTimes/1/Sone"));
450                 assertThat(stringValues, not(hasKey("SoneFollowingTimes/2/Sone")));
451                 assertThat(longValues, hasKey("SoneFollowingTimes/0/Time"));
452                 assertThat(longValues, not(hasKey("SoneFollowingTimes/1/Time")));
453         }
454
455         @Test
456         public void soneFollowingTimeIsNotSetOnSecondFollowing() throws ConfigurationException {
457                 memoryDatabase.startAndWait();
458                 memoryDatabase.addFriend(localSone, "Friend1");
459                 LocalSone secondLocalSone = mock(LocalSone.class);
460                 when(secondLocalSone.getId()).thenReturn("LocalSone2");
461                 long followingTime = longValues.get("SoneFollowingTimes/0/Time").getValue();
462                 memoryDatabase.addFriend(secondLocalSone, "Friend1");
463                 while (followingTime == System.currentTimeMillis());
464                 assertThat(longValues.get("SoneFollowingTimes/0/Time").getValue(), is(followingTime));
465         }
466
467         @Test
468         public void soneFollowingTimesAreRemovedWhenSoneIsUnfollowedByAll()
469         throws ConfigurationException {
470                 stringValues.put("Sone/" + SONE_ID + "/Friends/0/ID", TestValue.from("Friend1"));
471                 stringValues.put("SoneFollowingTimes/0/Sone", TestValue.from("Friend1"));
472                 longValues.put("SoneFollowingTimes/0/Time", TestValue.from(1000L));
473                 memoryDatabase.startAndWait();
474                 memoryDatabase.removeFriend(localSone, "Friend1");
475                 assertThat(stringValues.get("SoneFollowingTimes/0/Sone").getValue(), nullValue());
476         }
477
478 }