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