25ec62a2c5f4ef8a0f8c30dcf6df3731304d448f
[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", "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|foo|Post about foo...] is awesome."));
151         }
152
153         //
154         // PRIVATE METHODS
155         //
156
157         /**
158          * Converts all given {@link Part}s into a string, validating that the
159          * part’s classes match only the expected classes.
160          *
161          * @param parts
162          *            The parts to convert to text
163          * @param validClasses
164          *            The valid classes; if no classes are given, all classes are
165          *            valid
166          * @return The converted text
167          */
168         private static String convertText(Iterable<Part> parts, Class<?>... validClasses) {
169                 StringBuilder text = new StringBuilder();
170                 for (Part part : parts) {
171                         assertThat(part, notNullValue());
172                         boolean classValid = validClasses.length == 0;
173                         for (Class<?> validClass : validClasses) {
174                                 if (validClass.isAssignableFrom(part.getClass())) {
175                                         classValid = true;
176                                         break;
177                                 }
178                         }
179                         assertThat("Part’s Class (" + part.getClass() + ") is not one of " + Arrays.toString(validClasses), classValid, is(true));
180                         if (part instanceof PlainTextPart) {
181                                 text.append(part.getText());
182                         } else if (part instanceof FreenetLinkPart) {
183                                 FreenetLinkPart freenetLinkPart = (FreenetLinkPart) part;
184                                 text.append('[')
185                                         .append(freenetLinkPart.getLink())
186                                         .append('|')
187                                         .append(freenetLinkPart.isTrusted() ? "trusted|" : "")
188                                         .append(freenetLinkPart.getTitle())
189                                         .append('|')
190                                         .append(freenetLinkPart.getText())
191                                         .append(']');
192                         } else if (part instanceof LinkPart) {
193                                 LinkPart linkPart = (LinkPart) part;
194                                 text.append('[')
195                                         .append(linkPart.getLink())
196                                         .append('|')
197                                         .append(linkPart.getTitle())
198                                         .append('|')
199                                         .append(linkPart.getText())
200                                         .append(']');
201                         } else if (part instanceof SonePart) {
202                                 SonePart sonePart = (SonePart) part;
203                                 text.append("[Sone|").append(sonePart.getSone().getId()).append(']');
204                         } else if (part instanceof PostPart) {
205                                 PostPart postPart = (PostPart) part;
206                                 text.append("[post|").append(postPart.getPost().getId()).append('|').append(postPart.getPost().getText()).append(']');
207                         }
208                 }
209                 return text.toString();
210         }
211
212         /**
213          * Mock Sone provider.
214          *
215          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
216          */
217         private static class TestSoneProvider implements SoneProvider {
218
219                 @Override
220                 public Function<String, Optional<Sone>> soneLoader() {
221                         return new Function<String, Optional<Sone>>() {
222                                 @Override
223                                 public Optional<Sone> apply(String soneId) {
224                                         return getSone(soneId);
225                                 }
226                         };
227                 }
228
229                 /**
230                  * {@inheritDoc}
231                  */
232                 @Override
233                 public Optional<Sone> getSone(final String soneId) {
234                         return Optional.<Sone>of(new IdOnlySone(soneId));
235                 }
236
237                 /**
238                  * {@inheritDocs}
239                  */
240                 @Override
241                 public Collection<Sone> getSones() {
242                         return null;
243                 }
244
245                 /**
246                  * {@inheritDocs}
247                  */
248                 @Override
249                 public Collection<Sone> getLocalSones() {
250                         return null;
251                 }
252
253                 /**
254                  * {@inheritDocs}
255                  */
256                 @Override
257                 public Collection<Sone> getRemoteSones() {
258                         return null;
259                 }
260
261         }
262
263         private static class TestPostProvider implements PostProvider {
264
265                 private final Map<String, String> posts = new HashMap<String, String>();
266
267                 private void addValidPostId(String validPostId, String text) {
268                         posts.put(validPostId, text);
269                 }
270
271                 @Override
272                 public Collection<Post> getDirectedPosts(String recipientId) {
273                         return Collections.emptyList();
274                 }
275
276                 @Override
277                 public Collection<Post> getPosts(String soneId) {
278                         return Collections.emptyList();
279                 }
280
281                 @Override
282                 public Optional<Post> getPost(String postId) {
283                         if (posts.containsKey(postId)) {
284                                 Post post = mock(Post.class);
285                                 when(post.getId()).thenReturn(postId);
286                                 when(post.getText()).thenReturn(posts.get(postId));
287                                 return Optional.of(post);
288                         }
289                         return Optional.absent();
290                 }
291
292         }
293
294 }