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