aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/com/juick/tests/ApiTests.java
blob: f72bcc0292b28234680ccc59625e5fb3a90cbfb4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
package com.juick.tests;

import ch.vorburger.exec.ManagedProcessException;
import ch.vorburger.mariadb4j.DB;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.juick.Message;
import com.juick.Tag;
import com.juick.User;
import com.juick.json.MessageSerializer;
import com.juick.server.helpers.TagStats;
import com.juick.server.protocol.JuickProtocol;
import com.juick.server.protocol.ProtocolReply;
import com.juick.service.MessagesService;
import com.juick.service.SubscriptionService;
import com.juick.service.TagService;
import com.juick.service.UserService;
import com.juick.service.search.SearchService;
import com.juick.www.PageTemplates;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONArray;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.inject.Inject;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

/**
 * Created by vt on 14.01.2016.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ApiTests {
    @Configuration
    @ComponentScan(basePackages = {"com.juick.service", "com.juick.server.protocol"})
    static class Config implements TransactionManagementConfigurer {
        @Bean
        public BasicDataSource dataSource() {
            try {
                DB db = DB.newEmbeddedDB(33306);
                db.start();
                db.createDB("juick");
                db.source("schema.sql");
                BasicDataSource dataSource = new BasicDataSource();
                dataSource.setDriverClassName("com.mysql.jdbc.Driver");
                dataSource.setUrl("jdbc:mysql://localhost:33306/juick?autoReconnect=true&user=root");

                dataSource.setValidationQuery("select 1");

                return dataSource;
            } catch (ManagedProcessException e) {
                return null;
            }
        }

        @Bean
        public PlatformTransactionManager transactionManager() {
            return new DataSourceTransactionManager(dataSource());
        }

        @Override
        public PlatformTransactionManager annotationDrivenTransactionManager() {
            return transactionManager();
        }

        @Bean
        @DependsOn("dataSource")
        public JdbcTemplate jdbcTemplate() {
            return new JdbcTemplate(dataSource());
        }
        @Bean
        public SearchService emptySearchService() {
            return new SearchService() {
                @Override
                public void setMaxResult(int maxResult) {
                }

                @Override
                public List<Integer> searchInAllMessages(String searchString, int messageIdBefore) {
                    return Collections.emptyList();
                }

                @Override
                public List<Integer> searchByStringAndUser(String searchString, int userId, int messageIdBefore) {
                    return Collections.emptyList();
                }
            };
        }
        @Bean
        public JuickProtocol juickProtocol() {
            return new JuickProtocol("http://localhost:8080/");
        }
    }

    @Inject
    UserService userService;
    @Inject
    MessagesService messagesService;
    @Inject
    TagService tagService;
    @Inject
    SubscriptionService subscriptionService;
    @Inject
    JdbcTemplate jdbcTemplate;
    @Inject
    JuickProtocol juickProtocol;

    @Before
    public void setup() {
        userService.createUser("ugnich", "secret");
        userService.createUser("juick", "secret");
    }
    @Test
    public void messageTests() {
        int user_id = userService.createUser("mmmme", "secret");
        User user = userService.getUserByUID(user_id).orElse(new User());
        assertEquals("it should be me", "mmmme", user.getName());
        int mid = messagesService.createMessage(user_id, "yo", null, new ArrayList<>());
        Message msg = messagesService.getMessage(mid);
        assertEquals("yo", msg.getText());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(msg.getDate());
        assertEquals(2016, calendar.get(Calendar.YEAR));
        User me = msg.getUser();
        assertEquals("mmmme", me.getName());
        assertEquals("mmmme", messagesService.getMessageAuthor(mid).getName());
        int tagID = tagService.createTag("weather");
        Tag tag = tagService.getTag(tagID);
        List<Tag> tagList = new ArrayList<>();
        tagList.add(tag);
        int mid2 = messagesService.createMessage(user_id, "yo2", null, tagList);
        Message msg2 = messagesService.getMessage(mid2);
        assertEquals(1, msg2.getTags().size());
        assertEquals("we already have ugnich", -1, userService.createUser("ugnich", "x"));
        int ugnich_id = userService.createUser("hugnich", "x");
        User ugnich = userService.getUserByUID(ugnich_id).orElse(new User());
        int rid = messagesService.createReply(msg2.getMid(), 0, ugnich.getUid(), "bla-bla", null);
        assertEquals(1, rid);
        Message msg3 = messagesService.getMessage(mid2);
        assertEquals(1, msg3.getReplies());
        assertEquals("weather", msg3.getTags().get(0).getName());
        assertEquals(ugnich.getUid(), userService.checkPassword(ugnich.getName(), "x"));
        assertEquals(-1, userService.checkPassword(ugnich.getName(), "xy"));
        subscriptionService.subscribeMessage(msg.getMid(), ugnich.getUid());
        assertEquals(1, subscriptionService.getUsersSubscribedToComments(msg.getMid(), user.getUid()).size());
        messagesService.deleteMessage(user_id, mid);
        messagesService.deleteMessage(user_id, mid2);
        String htmlTagName = ">_<";
        Tag htmlTag = tagService.getTag(htmlTagName, true);
        TagStats htmlTagStats = new TagStats();
        htmlTagStats.setTag(htmlTag);
        String dbTagName = jdbcTemplate.queryForObject("select name from tags where name=?", String.class, StringEscapeUtils.escapeHtml4(htmlTagName));
        assertNotEquals("db tags should be escaped", dbTagName, htmlTag.getName());
        assertEquals("object tags should unescaped", htmlTag.getName(), StringEscapeUtils.unescapeHtml4(dbTagName));
        assertEquals("template should encode escaped tag in url and show escaped tag in name",
                "<a href=\"/tag/%3E_%3C\" rel=\"nofollow\">&gt;_&lt;</a>", PageTemplates.formatTags(Collections.singletonList(htmlTagStats)));
    }

    @Test
    public void protocolTests() throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, ParseException, JsonProcessingException {
        MessageSerializer json = new MessageSerializer();
        assertEquals("juick user should have uid 2", 2, userService.getUIDbyName("juick"));
        int uid = userService.createUser("me", "secret");
        User user = userService.getUserByUID(uid).orElse(new User());
        String expectedMessage = "New message posted";
        assertEquals("should be message", true,
                juickProtocol.getReply(user, "*yo yoyo").getDescription().startsWith(expectedMessage));
        int mid = messagesService.getUserBlog(user.getUid(), -1, 0).stream().reduce((first, second) -> second).get();
        assertEquals("text should match", "yoyo",
                messagesService.getMessage(mid).getText());
        assertEquals("tag should match", "yo",
                tagService.getMessageTags(mid).get(0).getTag().getName());
        assertNotEquals("should not be error", "Error", juickProtocol.getReply(user, "#" + mid).getDescription());
        assertEquals("should be PONG", "PONG", juickProtocol.getReply(user, "   ping   \n    ").getDescription());
        int readerUid = userService.createUser("dummyReader", "dummySecret");
        User readerUser = userService.getUserByUID(readerUid).orElse(new User());
        assertEquals("should be subscribed", "Subscribed",
                juickProtocol.getReply(readerUser, "S #" + mid).getDescription());
        assertEquals("number of subscribed users should match", 1,
                subscriptionService.getUsersSubscribedToComments(mid, uid).size());
        assertEquals("should be subscribed", "Subscribed",
                juickProtocol.getReply(readerUser, "S @" + user.getName()).getDescription());
        List<User> friends = userService.getUserFriends(readerUid);
        assertEquals("number of friend users should match", 2,
                friends.size());
        assertEquals("number of reader users should match", 1,
                userService.getUserReaders(uid).size());
        String expectedReply = "Reply posted.\n#" + mid + "/1 "
                + juickProtocol.getBaseUri() + mid + "/1";
        String expectedSecondReply = "Reply posted.\n#" + mid + "/2 "
                + juickProtocol.getBaseUri() + mid + "/2";
        assertEquals("should be reply", expectedReply,
                juickProtocol.getReply(user, "#" + mid + " yoyo").getDescription());
        assertEquals("should be second reply", expectedSecondReply,
                juickProtocol.getReply(user, "#" + mid + "/1 yoyo").getDescription());
        Message reply = messagesService.getReplies(mid).stream().filter(m -> m.getRid() == 2).findFirst()
                .orElse(new Message());
        assertEquals("should be reply to first comment", 1, reply.getReplyto());
        String jsonReply = juickProtocol.getReply(user, "#" + mid).getJson().orElse("");
        JSONArray jsonMessages = new JSONArray(jsonReply);
        Message receivedMsg = json.deserialize(jsonMessages.getJSONObject(0));
        assertEquals("json should match text", "yoyo", receivedMsg.getText());
        assertEquals("array length should match", 1, jsonMessages.length());
        jsonReply = juickProtocol.getReply(user, "#" + mid+"+").getJson().orElse("");
        jsonMessages = new JSONArray(jsonReply);
        assertEquals("array length should match", 3, jsonMessages.length());
        assertNotEquals("tags should NOT be updated", "Tags are updated",
                juickProtocol.getReply(readerUser, "#" + mid + " *yo *there").getDescription());
        assertEquals("tags should be updated", "Tags are updated",
                juickProtocol.getReply(user, "#" + mid + " *there").getDescription());
        assertEquals("number of tags should match", 2,
                tagService.getMessageTags(mid).size());
        assertEquals("tags should be updated", "Tags are updated",
                juickProtocol.getReply(user, "#" + mid + " *there").getDescription());
        assertEquals("number of tags should match", 1,
                tagService.getMessageTags(mid).size());
        int taggerUid = userService.createUser("dummyTagger", "dummySecret");
        User taggerUser = userService.getUserByUID(taggerUid).orElse(new User());
        assertEquals("should be subscribed", "Subscribed",
                juickProtocol.getReply(taggerUser, "S *yo").getDescription());
        assertEquals("number of subscribed users should match", 2,
                subscriptionService.getSubscribedUsers(uid, mid).size());
        assertEquals("should be unsubscribed", "Unsubscribed from yo",
                juickProtocol.getReply(taggerUser, "U *yo").getDescription());
        assertEquals("number of subscribed users should match", 1,
                subscriptionService.getSubscribedUsers(uid, mid).size());
        assertEquals("number of readers should match", 1,
                userService.getUserReaders(uid).size());
        ProtocolReply readerFeed = juickProtocol.getReply(readerUser, "#");
        assertEquals("description should match", true, readerFeed.getDescription().startsWith("Your feed"));
        String readerUserFeed = readerFeed.getJson().orElse("");
        JSONArray readerUserFeedMessages = new JSONArray(readerUserFeed);
        assertEquals("messages count should match", 1, readerUserFeedMessages.length());
        assertEquals("should be unsubscribed", "Unsubscribed from @" + user.getName(),
                juickProtocol.getReply(readerUser, "U @" + user.getName()).getDescription());
        assertEquals("number of readers should match", 0,
                userService.getUserReaders(uid).size());
        assertEquals("number of friends should match", 1,
                userService.getUserFriends(uid).size());
        assertEquals("should be unsubscribed", "Unsubscribed from #" + mid,
                juickProtocol.getReply(readerUser, "u #" + mid).getDescription());
        assertEquals("number of subscribed users should match", 0,
                subscriptionService.getUsersSubscribedToComments(mid, uid).size());
        assertNotEquals("should NOT be deleted", String.format("Message %s deleted", mid),
                juickProtocol.getReply(readerUser, "D #" + mid).getDescription());
        assertEquals("should be deleted", String.format("Message %s deleted", mid),
                juickProtocol.getReply(user, "D #" + mid).getDescription());
        assertEquals("should not have messages", 0, messagesService.getAll(user.getUid(), 0).size());
        String allFeed = juickProtocol.getReply(readerUser, "#").getJson().orElse("");
        JSONArray allFeedMessages = new JSONArray(allFeed);
        assertEquals("messages count should match", 0, allFeedMessages.length());
    }

}