Parse album:// links
[Sone.git] / src / test / java / net / pterodactylus / sone / text / SoneTextParserTest.java
1 /*
2  * Sone - SoneTextParserTest.java - Copyright © 2011–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.text;
19
20 import static org.hamcrest.MatcherAssert.assertThat;
21 import static org.hamcrest.Matchers.is;
22 import static org.hamcrest.Matchers.notNullValue;
23 import static org.mockito.Mockito.mock;
24 import static org.mockito.Mockito.when;
25
26 import java.io.IOException;
27 import java.io.StringReader;
28 import java.util.Arrays;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.HashMap;
32 import java.util.Map;
33
34 import net.pterodactylus.sone.data.Album;
35 import net.pterodactylus.sone.data.Post;
36 import net.pterodactylus.sone.data.Sone;
37 import net.pterodactylus.sone.data.impl.IdOnlySone;
38 import net.pterodactylus.sone.database.AlbumProvider;
39 import net.pterodactylus.sone.database.PostProvider;
40 import net.pterodactylus.sone.database.SoneProvider;
41
42 import com.google.common.base.Function;
43 import com.google.common.base.Optional;
44 import org.junit.Test;
45
46 /**
47  * JUnit test case for {@link SoneTextParser}.
48  *
49  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50  */
51 public class SoneTextParserTest {
52
53         private final SoneProvider soneProvider = new TestSoneProvider();
54         private final TestPostProvider postProvider = new TestPostProvider();
55         private final TestAlbumProvider albumProvider = new TestAlbumProvider();
56         private final SoneTextParser soneTextParser = new SoneTextParser(soneProvider, postProvider, albumProvider);
57
58         /**
59          * Tests basic plain-text operation of the parser.
60          *
61          * @throws IOException
62          *             if an I/O error occurs
63          */
64         @Test
65         public void testPlainText() throws IOException {
66                 Iterable<Part> parts;
67
68                 /* check basic operation. */
69                 parts = soneTextParser.parse(null, new StringReader("Test."));
70                 assertThat(parts, notNullValue());
71                 assertThat(convertText(parts, PlainTextPart.class), is("Test."));
72
73                 /* check empty lines at start and end. */
74                 parts = soneTextParser.parse(null, new StringReader("\nTest.\n\n"));
75                 assertThat(parts, notNullValue());
76                 assertThat(convertText(parts, PlainTextPart.class), is("Test."));
77
78                 /* check duplicate empty lines in the text. */
79                 parts = soneTextParser.parse(null, new StringReader("\nTest.\n\n\nTest."));
80                 assertThat(parts, notNullValue());
81                 assertThat(convertText(parts, PlainTextPart.class), is("Test.\n\nTest."));
82         }
83
84         /**
85          * Tests parsing of KSK links.
86          *
87          * @throws IOException
88          *             if an I/O error occurs
89          */
90         @Test
91         public void testKSKLinks() throws IOException {
92                 Iterable<Part> parts;
93
94                 /* check basic links. */
95                 parts = soneTextParser.parse(null, new StringReader("KSK@gpl.txt"));
96                 assertThat(parts, notNullValue());
97                 assertThat(convertText(parts, FreenetLinkPart.class), is("[KSK@gpl.txt|gpl.txt|gpl.txt]"));
98
99                 /* check embedded links. */
100                 parts = soneTextParser.parse(null, new StringReader("Link is KSK@gpl.txt\u200b."));
101                 assertThat(parts, notNullValue());
102                 assertThat(convertText(parts, PlainTextPart.class, FreenetLinkPart.class), is("Link is [KSK@gpl.txt|gpl.txt|gpl.txt]\u200b."));
103
104                 /* check embedded links and line breaks. */
105                 parts = soneTextParser.parse(null, new StringReader("Link is KSK@gpl.txt\nKSK@test.dat\n"));
106                 assertThat(parts, notNullValue());
107                 assertThat(convertText(parts, PlainTextPart.class, FreenetLinkPart.class),
108                         is("Link is [KSK@gpl.txt|gpl.txt|gpl.txt]\n[KSK@test.dat|test.dat|test.dat]"));
109         }
110
111         /**
112          * Test case for a bug that was discovered in 0.6.7.
113          *
114          * @throws IOException
115          *             if an I/O error occurs
116          */
117         @Test
118         public void testEmptyLinesAndSoneLinks() throws IOException {
119                 Iterable<Part> parts;
120
121                 /* check basic links. */
122                 parts = soneTextParser.parse(null, new StringReader("Some text.\n\nLink to sone://DAxKQzS48mtaQc7sUVHIgx3fnWZPQBz0EueBreUVWrU and stuff."));
123                 assertThat(parts, notNullValue());
124                 assertThat(convertText(parts, PlainTextPart.class, SonePart.class),
125                         is("Some text.\n\nLink to [Sone|DAxKQzS48mtaQc7sUVHIgx3fnWZPQBz0EueBreUVWrU] and stuff."));
126         }
127
128         /**
129          * Test for a bug discovered in Sone 0.8.4 where a plain “http://” would be
130          * parsed into a link.
131          *
132          * @throws IOException
133          *             if an I/O error occurs
134          */
135         @Test
136         public void testEmpyHttpLinks() throws IOException {
137                 Iterable<Part> parts;
138
139                 /* check empty http links. */
140                 parts = soneTextParser.parse(null, new StringReader("Some text. Empty link: http:// – nice!"));
141                 assertThat(parts, notNullValue());
142                 assertThat(convertText(parts, PlainTextPart.class), is("Some text. Empty link: http:// – nice!"));
143         }
144
145         @Test
146         public void linksToPostAreParsedCorrectly() throws IOException {
147                 postProvider.addValidPostId("foo", "internal", "Post about foo...");
148                 Iterable<Part> parts = soneTextParser.parse(null, new StringReader("This post://foo is awesome."));
149                 assertThat(convertText(parts, PlainTextPart.class, PostPart.class), is("This [post|new|foo|Post about foo...] is awesome."));
150         }
151
152         @Test
153         public void linksToPostsWithOldIdsAreParsedCorrectly() throws IOException {
154                 postProvider.addValidPostId("foo", "internal", "Post about foo...");
155                 Iterable<Part> parts = soneTextParser.parse(null, new StringReader("This post://internal is awesome."));
156                 assertThat(convertText(parts, PlainTextPart.class, PostPart.class), is("This [post|old|foo|Post about foo...] is awesome."));
157         }
158
159         @Test
160         public void linksToAlbumIsParsedCorrectly() throws IOException {
161                 albumProvider.addAlbumTitle("album-id", "Super Album");
162                 Iterable<Part> parts = soneTextParser.parse(null, new StringReader("This album://album-id rocks!"));
163                 assertThat(convertText(parts, PlainTextPart.class, AlbumPart.class), is("This [album|album-id|Super Album] rocks!"));
164         }
165
166         //
167         // PRIVATE METHODS
168         //
169
170         /**
171          * Converts all given {@link Part}s into a string, validating that the
172          * part’s classes match only the expected classes.
173          *
174          * @param parts
175          *            The parts to convert to text
176          * @param validClasses
177          *            The valid classes; if no classes are given, all classes are
178          *            valid
179          * @return The converted text
180          */
181         private static String convertText(Iterable<Part> parts, Class<?>... validClasses) {
182                 StringBuilder text = new StringBuilder();
183                 for (Part part : parts) {
184                         assertThat(part, notNullValue());
185                         boolean classValid = validClasses.length == 0;
186                         for (Class<?> validClass : validClasses) {
187                                 if (validClass.isAssignableFrom(part.getClass())) {
188                                         classValid = true;
189                                         break;
190                                 }
191                         }
192                         assertThat("Part’s Class (" + part.getClass() + ") is not one of " + Arrays.toString(validClasses), classValid, is(true));
193                         if (part instanceof PlainTextPart) {
194                                 text.append(part.getText());
195                         } else if (part instanceof FreenetLinkPart) {
196                                 FreenetLinkPart freenetLinkPart = (FreenetLinkPart) part;
197                                 text.append('[')
198                                         .append(freenetLinkPart.getLink())
199                                         .append('|')
200                                         .append(freenetLinkPart.isTrusted() ? "trusted|" : "")
201                                         .append(freenetLinkPart.getTitle())
202                                         .append('|')
203                                         .append(freenetLinkPart.getText())
204                                         .append(']');
205                         } else if (part instanceof LinkPart) {
206                                 LinkPart linkPart = (LinkPart) part;
207                                 text.append('[')
208                                         .append(linkPart.getLink())
209                                         .append('|')
210                                         .append(linkPart.getTitle())
211                                         .append('|')
212                                         .append(linkPart.getText())
213                                         .append(']');
214                         } else if (part instanceof SonePart) {
215                                 SonePart sonePart = (SonePart) part;
216                                 text.append("[Sone|").append(sonePart.getSone().getId()).append(']');
217                         } else if (part instanceof PostPart) {
218                                 PostPart postPart = (PostPart) part;
219                                 text.append("[post|")
220                                         .append(postPart.usesDeprecatedLink() ? "old" : "new")
221                                         .append('|')
222                                         .append(postPart.getPost().getId())
223                                         .append('|')
224                                         .append(postPart.getPost().getText())
225                                         .append(']');
226                         } else if (part instanceof AlbumPart) {
227                                 Album album = ((AlbumPart) part).getAlbum();
228                                 text.append(String.format("[album|%s|%s]", album.getId(), album.getTitle()));
229                         }
230                 }
231                 return text.toString();
232         }
233
234         /**
235          * Mock Sone provider.
236          *
237          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
238          */
239         private static class TestSoneProvider implements SoneProvider {
240
241                 @Override
242                 public Function<String, Optional<Sone>> soneLoader() {
243                         return new Function<String, Optional<Sone>>() {
244                                 @Override
245                                 public Optional<Sone> apply(String soneId) {
246                                         return getSone(soneId);
247                                 }
248                         };
249                 }
250
251                 /**
252                  * {@inheritDoc}
253                  */
254                 @Override
255                 public Optional<Sone> getSone(final String soneId) {
256                         return Optional.<Sone>of(new IdOnlySone(soneId));
257                 }
258
259                 /**
260                  * {@inheritDocs}
261                  */
262                 @Override
263                 public Collection<Sone> getSones() {
264                         return null;
265                 }
266
267                 /**
268                  * {@inheritDocs}
269                  */
270                 @Override
271                 public Collection<Sone> getLocalSones() {
272                         return null;
273                 }
274
275                 /**
276                  * {@inheritDocs}
277                  */
278                 @Override
279                 public Collection<Sone> getRemoteSones() {
280                         return null;
281                 }
282
283         }
284
285         private static class TestPostProvider implements PostProvider {
286
287                 private final Map<String, String> postTexts = new HashMap<String, String>();
288                 private final Map<String, String> postInternalIds = new HashMap<String, String>();
289                 private final Map<String, String> internalIdPosts = new HashMap<String, String>();
290
291                 private void addValidPostId(String validPostId, String internalId, String text) {
292                         postTexts.put(validPostId, text);
293                         postInternalIds.put(validPostId, internalId);
294                         internalIdPosts.put(internalId, validPostId);
295                 }
296
297                 @Override
298                 public Collection<Post> getDirectedPosts(String recipientId) {
299                         return Collections.emptyList();
300                 }
301
302                 @Override
303                 public Collection<Post> getPosts(String soneId) {
304                         return Collections.emptyList();
305                 }
306
307                 @Override
308                 public Optional<Post> getPost(String postId) {
309                         if (postTexts.containsKey(postId)) {
310                                 Post post = mock(Post.class);
311                                 when(post.getId()).thenReturn(postId);
312                                 when(post.getInternalId()).thenReturn(postInternalIds.get(postId));
313                                 when(post.getText()).thenReturn(postTexts.get(postId));
314                                 return Optional.of(post);
315                         } else if (internalIdPosts.containsKey(postId)) {
316                                 Post post = mock(Post.class);
317                                 when(post.getId()).thenReturn(internalIdPosts.get(postId));
318                                 when(post.getInternalId()).thenReturn(postId);
319                                 when(post.getText()).thenReturn(postTexts.get(internalIdPosts.get(postId)));
320                                 return Optional.of(post);
321                         }
322                         return Optional.absent();
323                 }
324
325         }
326
327         private static class TestAlbumProvider implements AlbumProvider {
328
329                 private final Map<String, String> albumTitles = new HashMap<String, String>();
330
331                 public void addAlbumTitle(String albumId, String albumTitle) {
332                         albumTitles.put(albumId, albumTitle);
333                 }
334
335                 @Override
336                 public Optional<Album> getAlbum(String albumId) {
337                         if (albumTitles.containsKey(albumId)) {
338                                 Album album = mock(Album.class);
339                                 when(album.getId()).thenReturn(albumId);
340                                 when(album.getTitle()).thenReturn(albumTitles.get(albumId));
341                                 return Optional.of(album);
342                         }
343                         return Optional.absent();
344                 }
345
346         }
347
348 }