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