/* * Copyright (C) 2008-2017, Juick * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ package com.juick.server.tests; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.jayway.jsonpath.JsonPath; import com.juick.*; import com.juick.server.*; import com.juick.server.component.MessageEvent; import com.juick.server.helpers.AnonymousUser; import com.juick.server.helpers.CommandResult; import com.juick.server.helpers.TagStats; import com.juick.server.util.HttpUtils; import com.juick.server.util.ImageUtils; import com.juick.service.*; import com.juick.util.DateFormattersHolder; import com.juick.util.MessageUtils; import org.apache.commons.codec.CharEncoding; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.http.*; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.util.FileSystemUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.xml.sax.SAXException; import rocks.xmpp.addr.Jid; import rocks.xmpp.core.session.Extension; import rocks.xmpp.core.session.XmppSession; import rocks.xmpp.core.session.XmppSessionConfiguration; import rocks.xmpp.core.stanza.model.StanzaError; import rocks.xmpp.core.stanza.model.client.ClientMessage; import rocks.xmpp.core.stanza.model.errors.Condition; import javax.inject.Inject; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Timestamp; import java.time.Instant; import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.IntStream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Created by vitalyster on 25.11.2016. */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @TestPropertySource(properties = {"broken_ssl_hosts=localhost,serverstorageisfull.tld"}) @AutoConfigureMockMvc public class ServerTests { @Inject private MockMvc mockMvc; @Inject private TestRestTemplate rest; @Inject private MessagesService messagesService; @Inject private UserService userService; @Inject private TagService tagService; @Inject private ObjectMapper jsonMapper; @Inject private WebApplicationContext wac; @Inject private XMPPServer server; @Inject private CommandsManager commandsManager; @Inject private XMPPConnection router; @Inject private SubscriptionService subscriptionService; @Inject private PrivacyQueriesService privacyQueriesService; @Inject private JdbcTemplate jdbcTemplate; @Inject private EmailService emailService; @Inject private PMQueriesService pmQueriesService; @Inject private TelegramService telegramService; @Inject private CrosspostService crosspostService; @Inject private ImagesService imagesService; @Inject private ServerManager serverManager; @Value("${hostname:localhost}") private Jid jid; @Value("${xmppbot_jid:juick@localhost}") private Jid botJid; @Value("${upload_tmp_dir:#{systemEnvironment['TEMP'] ?: '/tmp'}}") private String tmpDir; @Value("${img_path:#{systemEnvironment['TEMP'] ?: '/tmp'}}") private String imgDir; private static User ugnich, freefd, juick; static String ugnichName, ugnichPassword, freefdName, freefdPassword, juickName, juickPassword; URI emptyUri = URI.create(StringUtils.EMPTY); private static boolean isSetUp = false; @Before public void setUp() throws Exception { Files.createDirectory(Paths.get(imgDir, "p")); Files.createDirectory(Paths.get(imgDir, "photos-1024")); Files.createDirectory(Paths.get(imgDir, "photos-512")); Files.createDirectory(Paths.get(imgDir, "ps")); if (!isSetUp) { ugnichName = "ugnich"; ugnichPassword = "secret"; freefdName = "freefd"; freefdPassword = "MyPassw0rd!"; juickName = "juick"; juickPassword = "demo"; ugnich = userService.createUser(ugnichName, ugnichPassword); assertThat(ugnich, not(AnonymousUser.INSTANCE)); freefd = userService.createUser(freefdName, freefdPassword); assertThat(freefd, not(AnonymousUser.INSTANCE)); juick = userService.createUser(juickName, juickPassword); assertThat(juick, not(AnonymousUser.INSTANCE)); isSetUp = true; } } @After public void teardown() throws IOException { FileSystemUtils.deleteRecursively(Paths.get(imgDir, "p")); FileSystemUtils.deleteRecursively(Paths.get(imgDir, "photos-1024")); FileSystemUtils.deleteRecursively(Paths.get(imgDir, "photos-512")); FileSystemUtils.deleteRecursively(Paths.get(imgDir, "ps")); } @Test public void getMyFeed() { Message msg0 = messagesService.createMessage(ugnich, "test", null, null); Message msg2 = messagesService.createMessage(ugnich, "test2", null, null); subscriptionService.subscribeUser(userService.getUserByUID(freefd.getUid()).orElse(AnonymousUser.INSTANCE), userService.getUserByUID(ugnich.getUid()).orElse(AnonymousUser.INSTANCE)); List freefdFeed = messagesService.getMyFeed(freefd.getUid(), 0, false); assertThat(freefdFeed.get(0), equalTo(msg2.getMid())); User tonya = userService.createUser("Tonya", "secret"); assertThat(tonya, not(AnonymousUser.INSTANCE)); Message msg3 = messagesService.createMessage(tonya, "test3", null, null); messagesService.recommendMessage(msg3.getMid(), ugnich.getUid()); assertThat(messagesService.getMyFeed(freefd.getUid(), 0, false).get(0), equalTo(msg2.getMid())); assertThat(messagesService.getMyFeed(freefd.getUid(), 0, true).get(0), equalTo(msg3.getMid())); assertThat(messagesService.getMyFeed(freefd.getUid(), msg2.getMid(), true).get(0), equalTo(msg0.getMid())); assertThat(messagesService.recommendMessage(msg0.getMid(), ugnich.getUid()), equalTo(MessagesService.RecommendStatus.Added)); assertThat(msg0.getLikes(), equalTo(1)); assertThat(messagesService.recommendMessage(msg0.getMid(), ugnich.getUid()), equalTo(MessagesService.RecommendStatus.Deleted)); assertThat(msg0.getLikes(), equalTo(0)); assertThat(messagesService.getAll(ugnich.getUid(), 0).get(0), equalTo(msg3.getMid())); Tag yoTag = tagService.getTag("yoyo", true); assertThat(tagService.getTag("YOYO", false), equalTo(yoTag)); Message msg = messagesService.createMessage(ugnich, "yo", null, Collections.singletonList(yoTag)); List subscribers = subscriptionService.getSubscribedUsers(ugnich.getUid(), msg.getMid()); telegramService.createTelegramUser(12345, "freefd"); String loginhash = jdbcTemplate.queryForObject("SELECT loginhash FROM telegram where tg_id=?", String.class, 12345); crosspostService.setTelegramUser(loginhash, freefd); List telegramSubscribers = telegramService.getTelegramIdentifiers(subscribers); assertThat(subscribers.size(), equalTo(1)); assertThat(subscribers.size(), equalTo(telegramSubscribers.size())); assertThat(subscribers.get(0).getUid(), equalTo(freefd.getUid())); tagService.blacklistTag(freefd, yoTag); List subscribers2 = subscriptionService.getSubscribedUsers(ugnich.getUid(), msg.getMid()); assertThat(subscribers2.size(), equalTo(0)); assertThat(telegramService.getTelegramIdentifiers(subscribers2).size(), equalTo(0)); tagService.blacklistTag(freefd, yoTag); assertThat(subscriptionService.getSubscribedUsers(ugnich.getUid(), msg.getMid()).size(), equalTo(1)); subscriptionService.unSubscribeUser(freefd, ugnich); assertThat(subscriptionService.getSubscribedUsers(ugnich.getUid(), msg.getMid()).size(), equalTo(0)); } @Test public void pmTests() { pmQueriesService.createPM(freefd, ugnich, "hello"); Message pm = pmQueriesService.getPMMessages(ugnich, freefd).get(0); assertThat(pm.getText(), equalTo("hello")); assertThat(pm.getUser().getUid(), equalTo(freefd.getUid())); } @Test public void messageTests() { User mmmme = userService.createUser("mmmme", "secret"); assertEquals("it should be me", "mmmme", mmmme.getName()); Message msg = messagesService.createMessage(mmmme, "yo", null, new ArrayList<>()); assertEquals("yo", msg.getText()); User me = msg.getUser(); assertEquals("mmmme", me.getName()); assertEquals("mmmme", messagesService.getMessageAuthor(msg.getMid()).getName()); int tagID = tagService.createTag("weather"); Tag tag = tagService.getTag(tagID); List tagList = new ArrayList<>(); tagList.add(tag); Message msg2 = messagesService.createMessage(mmmme, "yo2", null, tagList); assertEquals(1, msg2.getTags().size()); assertEquals("we already have ugnich", AnonymousUser.INSTANCE, userService.createUser("ugnich", "x")); User hugnich = userService.createUser("hugnich", "x"); int rid = messagesService.createReply(msg2.getMid(), 0, hugnich, "bla-bla", null); assertEquals(1, rid); assertThat(msg2.getTo(), equalTo(null)); Message reply = messagesService.getReply(msg2.getMid(), rid); assertThat(reply.getTo().getName(), equalTo(mmmme.getName())); List replies = messagesService.getReplies(mmmme, msg2.getMid()); assertThat(replies.size(), equalTo(1)); assertThat(replies.get(0), equalTo(reply)); int ridToReply = messagesService.createReply(msg2.getMid(), 1, ugnich, "blax2", null); Message reply2 = messagesService.getReply(msg2.getMid(), ridToReply); assertThat(reply.getTo().getName(), equalTo(mmmme.getName())); List replies2 = messagesService.getReplies(mmmme, msg2.getMid()); assertThat(replies2.size(), equalTo(2)); assertThat(replies2.get(1), equalTo(reply2)); assertEquals(2, msg2.getReplies()); assertEquals("weather", msg2.getTags().get(0).getName()); assertEquals(hugnich, userService.checkPassword(hugnich.getName(), "x")); assertEquals(AnonymousUser.INSTANCE, userService.checkPassword(hugnich.getName(), "xy")); subscriptionService.subscribeMessage(msg, mmmme); subscriptionService.subscribeMessage(msg, ugnich); int reply_id = messagesService.createReply(msg.getMid(), 0, ugnich, "comment", null); assertEquals(1, subscriptionService.getUsersSubscribedToComments(msg, messagesService.getReply(msg.getMid(), reply_id)).size()); assertThat(messagesService.getDiscussions(ugnich.getUid(), 0L).get(0), equalTo(msg.getMid())); messagesService.deleteMessage(mmmme.getUid(), msg.getMid()); messagesService.deleteMessage(mmmme.getUid(), msg2.getMid()); 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, htmlTagName); assertEquals("db tags should not be escaped", dbTagName, htmlTag.getName()); Message msg4 = messagesService.createMessage(mmmme, "yoyoyo", null, null); assertEquals("tags string should be empty", StringUtils.EMPTY, MessageUtils.getTagsString(msg4)); messagesService.deleteMessage(mmmme.getUid(), msg4.getMid()); } public ExpectedException exception = ExpectedException.none(); @Test public void likeTypeStatsTests(){ User dsdss = userService.createUser("dsdss", "secret"); final int freefdId = freefd.getUid(); Message msg4 = messagesService.createMessage(dsdss, "yo", null, new ArrayList<>()); messagesService.likeMessage(msg4.getMid(), freefdId , 2); messagesService.likeMessage(msg4.getMid(), freefdId,2); messagesService.likeMessage(msg4.getMid(), freefdId,3); messagesService.likeMessage(msg4.getMid(), freefdId,1); assertThat(msg4.getLikes(), equalTo(1)); Assert.assertEquals(2, msg4.getReactions().stream().filter(r -> r.getId() == 2) .findFirst().orElseThrow(IllegalStateException::new).getCount()); Assert.assertEquals(1,msg4.getReactions().stream().filter(r -> r.getId() == 3) .findFirst().orElseThrow(IllegalStateException::new).getCount()); } @Test public void lastJidShouldNotBeDeleted() { User hugnich2 = userService.createUser("hugnich2", "x"); jdbcTemplate.update("INSERT INTO jids(user_id,jid,active) VALUES(?,?,?)", hugnich2.getUid(), "firstjid@localhost", 1); jdbcTemplate.update("INSERT INTO jids(user_id,jid,active) VALUES(?,?,?)", hugnich2.getUid(), "secondjid@localhost", 1); assertThat(userService.deleteJID(hugnich2.getUid(), "secondjid@localhost"), equalTo(true)); assertThat(userService.deleteJID(hugnich2.getUid(), "firstjid@localhost"), equalTo(false)); } @Test public void lastEmailShouldNotBeDeleted() { User hugnich3 = userService.createUser("hugnich3", "x"); jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", hugnich3.getUid(), "first@localhost"); jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", hugnich3.getUid(), "second@localhost"); assertThat(emailService.deleteEmail(hugnich3, "second@localhost"), equalTo(true)); assertThat(emailService.deleteEmail(hugnich3, "first@localhost"), equalTo(false)); } @Test public void messageUpdatedTimeShouldMatchLastReplyTime() throws InterruptedException { User hugnich4 = userService.createUser("hugnich4", "x"); Message msg = messagesService.createMessage(hugnich4, "yo", null, null); Instant ts = jdbcTemplate.queryForObject("SELECT updated FROM messages WHERE message_id=?", Timestamp.class, msg.getMid()).toInstant(); Thread.sleep(1000); int rid = messagesService.createReply(msg.getMid(), 0, ugnich, "people", null); Instant rts = jdbcTemplate.queryForObject("SELECT updated FROM messages WHERE message_id=?", Timestamp.class, msg.getMid()).toInstant(); assertThat(rts, greaterThan(ts)); Message reply = messagesService.getReply(msg.getMid(), rid); assertThat(rts, equalTo(reply.getTimestamp())); messagesService.deleteMessage(hugnich4.getUid(), msg.getMid()); } @Test public void testAllUnAuthorized() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isMovedPermanently()); mockMvc.perform(get("/auth")) .andExpect(status().isUnauthorized()); mockMvc.perform(get("/home")) .andExpect(status().isUnauthorized()); mockMvc.perform(get("/messages/recommended")) .andExpect(status().isUnauthorized()); mockMvc.perform(get("/messages/set_privacy")) .andExpect(status().isUnauthorized()); } @Test public void homeTestWithMessages() throws Exception { String msgText = "Привет, я - Угнич"; CommandResult result = commandsManager.processCommand(ugnich, msgText, URI.create("http://static.juick.com/settings/facebook.png")); int mid = result.getNewMessage().get().getMid(); Message msg = messagesService.getMessage(mid); tagService.createTag("тест"); mockMvc.perform( get("/home") .with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$[0].mid", is(msg.getMid()))) .andExpect(jsonPath("$[0].timestamp", is(DateFormattersHolder.getMessageFormatterInstance().format(msg.getTimestamp())))) .andExpect(jsonPath("$[0].body", is(msg.getText()))) .andExpect(jsonPath("$[0].attachment.url", is(String.format("https://i.juick.com/p/%d.png", msg.getMid())))) .andExpect(jsonPath("$[0].attachment.small.url", is(String.format("https://i.juick.com/photos-512/%d.png", msg.getMid())))) .andExpect(jsonPath("$[0].user.avatar").doesNotExist()); } @Test public void homeTestWithMessagesAndRememberMe() throws Exception { String ugnichHash = userService.getHashForUser(ugnich); mockMvc.perform( get("/home") .with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isOk()) .andReturn(); mockMvc.perform(get("/home") .param("hash", ugnichHash)) .andExpect(status().isOk()); } @Test public void homeTestWithMessagesAndSimpleCors() throws Exception { mockMvc.perform( get("/home") .with(httpBasic(ugnichName, ugnichPassword)) .header("Origin", "http://api.example.net")) .andExpect(status().isOk()) .andExpect(header().string("Access-Control-Allow-Origin", "*")); } @Test public void homeTestWithPreflightCors() throws Exception { mockMvc.perform( options("/home") .with(httpBasic(ugnichName, ugnichPassword)) .header("Origin", "http://api.example.net") .header("Access-Control-Request-Method", "POST") .header("Access-Control-Request-Headers", "X-PINGOTHER, Content-Type")) .andExpect(status().isOk()) .andExpect(header().string("Access-Control-Allow-Origin", "*")) .andExpect(header().string("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE")) .andExpect(header().string("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type")); } @Test public void anonymousApis() throws Exception { mockMvc.perform(get("/messages")) .andExpect(status().isOk()); mockMvc.perform(get("/users") .param("uname", "ugnich") .param("uname", "freefd")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$", hasSize(2))); } @Test public void messagesUrlTest() throws Exception { User dsds4345 = userService.createUser("dsds4345", "secret"); String freefdHash = userService.getHashForUser(freefd); System.out.println("user_id"+ dsds4345.getUid()); String userIdHash = userService.getHashForUser(dsds4345); final int freefdId = freefd.getUid(); Message msg = messagesService.createMessage(dsds4345, "yo", null, new ArrayList<>()); messagesService.likeMessage(msg.getMid(), freefdId, 2 ); messagesService.likeMessage(msg.getMid(), freefdId, 2 ); messagesService.likeMessage(msg.getMid(), freefdId, 3 ); mockMvc.perform(get("/messages?"+ "hash=" + userIdHash)) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect((jsonPath("$[0].reactions[?(@.id == 3)].count", is(Collections.singletonList(1))))) .andExpect((jsonPath("$[0].reactions[?(@.id == 2)].count", is(Collections.singletonList(2))))); mockMvc.perform(get("/reactions?hash=" + userIdHash)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.length()", is(7))); } @Test public void tags() throws Exception { Tag weather = tagService.getTag("weather", true); Tag yo = tagService.getTag("yo", true); messagesService.createMessage(ugnich, "text", null, Arrays.asList(yo, weather)); messagesService.createMessage(freefd, "text2", null, Collections.singletonList(yo)); MvcResult result = mockMvc.perform(get("/tags")) .andExpect(status().isOk()) .andReturn(); List tagsFromApi = jsonMapper.readValue(result.getResponse().getContentAsString(), new TypeReference>(){}); TagStats yoStats = tagsFromApi.stream().filter(t -> t.getTag().getName().equals("yo")).findFirst().get(); assertThat(yoStats.getUsageCount(), is(2)); MvcResult result2 = mockMvc.perform(get("/tags") .param("user_id", String.valueOf(ugnich.getUid()))) .andExpect(status().isOk()) .andReturn(); List ugnichTagsFromApi = jsonMapper.readValue(result2.getResponse().getContentAsString(), new TypeReference>(){}); TagStats yoUgnichStats = ugnichTagsFromApi.stream().filter(t -> t.getTag().getName().equals("yo")).findFirst().get(); assertThat(yoUgnichStats.getUsageCount(), is(1)); } @Test public void postWithReferer() throws Exception { mockMvc.perform(post("/post") .param("body", "yo") .with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isOk()); } @Test public void threadWithEphemeralNumberShouldReturn404() throws Exception { mockMvc.perform(get("/thread").param("mid", "999999999") .with(httpBasic(ugnichName, ugnichPassword))).andExpect(status().is4xxClientError()); } @Test public void performRequestsWithIssuedToken() throws Exception { String ugnichHash = userService.getHashForUser(ugnich); mockMvc.perform(get("/home")).andExpect(status().isUnauthorized()); mockMvc.perform(get("/auth")) .andExpect(status().isUnauthorized()); mockMvc.perform(get("/auth").with(httpBasic(ugnichName, "wrongpassword"))) .andExpect(status().isUnauthorized()); MvcResult result = mockMvc.perform(get("/auth").with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isOk()) .andReturn(); String authHash = result.getResponse().getContentAsString(); assertThat(authHash, equalTo(ugnichHash)); mockMvc.perform(get("/home").param("hash", ugnichHash)).andExpect(status().isOk()); } @Test public void registerForNotificationsTests() throws Exception { String token = "123456"; ExternalToken registration = new ExternalToken(null, "apns", token, null); mockMvc.perform(put("/notifications").with(httpBasic(ugnichName, ugnichPassword)) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(jsonMapper.writeValueAsBytes(Collections.singletonList(registration)))) .andExpect(status().isOk()); MvcResult result = mockMvc.perform(get("/notifications") .param("uid", String.valueOf(ugnich.getUid())) .with(httpBasic(juickName, juickPassword))) .andExpect(status().isOk()) .andReturn(); List user = jsonMapper.readValue(result.getResponse().getContentAsString(), new TypeReference>() { }); assertThat(user.get(0).getTokens().get(0).getToken(), equalTo(token)); } @Test public void tg2juickLinks() { UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://juick.com/m/123456#23").build(); assertThat(uriComponents.getPath().substring(3), is("123456")); assertThat(uriComponents.getFragment(), is("23")); } @Test public void notificationsTokensTest() throws Exception { List tokens = Collections.singletonList(new ExternalToken(null, "gcm", "123456", null)); mockMvc.perform(delete("/notifications").with(httpBasic(ugnichName, ugnichPassword)) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(jsonMapper.writeValueAsBytes(tokens))).andExpect(status().isForbidden()); mockMvc.perform(delete("/notifications").with(httpBasic(juickName, juickPassword)) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(jsonMapper.writeValueAsBytes(tokens))).andExpect(status().isOk()); } @Test public void notificationsSettingsAllowedOnlyForServiceUser() throws Exception { CommandResult result = commandsManager.processCommand(ugnich, "yo", emptyUri); String stringValueOfMid = String.valueOf(result.getNewMessage().get().getMid()); mockMvc.perform(get("/notifications").with(httpBasic(juickName, juickPassword)) .param("mid", stringValueOfMid).param("uid", String.valueOf(ugnich.getUid()))).andExpect(status().isOk()); mockMvc.perform(get("/notifications") .param("mid", stringValueOfMid).param("uid", String.valueOf(ugnich.getUid()))).andExpect(status().isUnauthorized()); } @Test public void topTest() { Message topmsg = messagesService.createMessage(ugnich, "top message", null, null); IntStream.rangeClosed(6, 12).forEach(i -> { User next = new User(); next.setUid(i); messagesService.createReply(topmsg.getMid(), 0, next, "yo", null); }); List topCandidates = messagesService.getPopularCandidates(); assertThat(topCandidates.size(), is(1)); assertThat(topCandidates.get(0), is(topmsg.getMid())); Tag juickTag = tagService.getTag("juick", false); assertThat(juickTag.TID, is(2)); tagService.updateTags(topmsg.getMid(), Collections.singletonList(juickTag)); assertThat(messagesService.getPopularCandidates().isEmpty(), is(true)); tagService.updateTags(topmsg.getMid(), Collections.singletonList(juickTag)); assertThat(messagesService.getPopularCandidates().isEmpty(), is(false)); jdbcTemplate.update("INSERT INTO tags(tag_id, name) VALUES(805, 'NSFW')"); Tag nsfw = tagService.getTag("NSFW", false); assertThat(nsfw.TID, equalTo(805)); tagService.updateTags(topmsg.getMid(), Collections.singletonList(nsfw)); assertThat(messagesService.getPopularCandidates().isEmpty(), is(true)); } @Test public void inReplyToScannerTest() { String header = "<123456.56@juick.com>"; Scanner headerScanner = new Scanner(header).useDelimiter(EmailManager.MSGID_PATTERN); int mid = Integer.parseInt(headerScanner.next()); int rid = Integer.parseInt(headerScanner.next()); assertThat(mid, equalTo(123456)); assertThat(rid, equalTo(56)); } @Test public void lastMessagesTest() throws Exception { mockMvc.perform( get("/rss/")) .andExpect(status().isOk()) .andExpect(content().contentType("application/rss+xml;charset=UTF-8")) .andExpect(xpath("/rss/channel/description").string("The latest messages at Juick")); } @Test public void statusPageIsUp() throws Exception { mockMvc.perform(get("/api/status").with(httpBasic(ugnichName, ugnichPassword))).andExpect(status().isOk()); assertThat(server.getJid(), equalTo(jid)); } @Test public void botIsUpAndProcessingResourceConstraints() throws Exception { User renha = userService.createUser("renha", "umnnbt"); Jid from = Jid.of("renha@serverstorageisfull.tld"); jdbcTemplate.update("INSERT INTO jids(user_id,jid,active) VALUES(?,?,?)", renha.getUid(), from.toEscapedString(), 1); rocks.xmpp.core.stanza.model.Message xmppMessage = new rocks.xmpp.core.stanza.model.Message(); xmppMessage.setType(rocks.xmpp.core.stanza.model.Message.Type.ERROR); xmppMessage.setFrom(from); xmppMessage.setTo(botJid); StanzaError err = new StanzaError(StanzaError.Type.CANCEL, Condition.RESOURCE_CONSTRAINT); xmppMessage.setError(err); Function isActive = f -> jdbcTemplate.queryForObject("SELECT active FROM jids WHERE user_id=?", Integer.class, f) == 1; assertThat(isActive.apply(renha.getUid()), equalTo(true)); ClientMessage result = router.incomingMessage(xmppMessage); assertNull(result); assertThat(isActive.apply(renha.getUid()), equalTo(false)); xmppMessage.setError(null); xmppMessage.setType(rocks.xmpp.core.stanza.model.Message.Type.CHAT); xmppMessage.setBody("On"); result = router.incomingMessage(xmppMessage); assertThat(result.getBody(), equalTo("XMPP notifications are activated")); assertTrue(isActive.apply(renha.getUid())); xmppMessage.setBody("*test test"); result = router.incomingMessage(xmppMessage); assertThat(result.getBody(), startsWith("New message posted")); xmppMessage.setFrom(from); xmppMessage.setBody("PING"); result = router.incomingMessage(xmppMessage); assertThat(result.getBody(), equalTo("PONG")); User secretlySad = userService.createUser("secretlysad", "bbk"); xmppMessage.setTo(botJid.withLocal("secretlysad")); xmppMessage.setBody("What's up?"); result = router.incomingMessage(xmppMessage); assertThat(result.getBody(), startsWith("Private message sent")); String xml = "@yo:\n" + "343432434\n" + "\n" + "#2 http://juick.com/2juick-2343432434@yo"; result = router.incomingMessage((rocks.xmpp.core.stanza.model.Message)server.parse(xml)); String active = ""; result = router.incomingMessage((rocks.xmpp.core.stanza.model.Message)server.parse(active)); xmppMessage.setFrom(botJid); // TODO: assert events } @Test public void botCommandsTests() throws Exception { assertThat(commandsManager.processCommand(AnonymousUser.INSTANCE, "PING", emptyUri).getText(), is("PONG")); // subscription commands have two lines, others have 1 assertThat(commandsManager.processCommand(AnonymousUser.INSTANCE, "help", emptyUri).getText().split("\n").length, is(32)); } @Test public void protocolTests() throws Exception { User user = userService.createUser("me", "secret"); Tag yo = tagService.getTag("yo", true); Message msg = commandsManager.processCommand(user, "*yo yoyo", URI.create("http://static.juick.com/settings/facebook.png")).getNewMessage().get(); assertThat(msg.getAttachmentType(), is("png")); Message msgreply = commandsManager.processCommand(user, "#" + msg.getMid() + " yyy", HttpUtils.downloadImage(URI.create("http://static.juick.com/settings/xmpp.png").toURL(), tmpDir)).getNewMessage().get(); assertThat(msgreply.getAttachmentType(), equalTo("png")); assertEquals("text should match", "yoyo", messagesService.getMessage(msg.getMid()).getText()); assertEquals("tag should match", "yo", tagService.getMessageTags(msg.getMid()).get(0).getTag().getName()); CommandResult yoyoMsg = commandsManager.processCommand(user, "*yo", URI.create("http://static.juick.com/settings/facebook.png")); assertTrue(yoyoMsg.getNewMessage().isPresent()); assertThat(yoyoMsg.getNewMessage().get().getTags().get(0), is(yo)); int mid = yoyoMsg.getNewMessage().get().getMid(); Timestamp last = jdbcTemplate.queryForObject("SELECT lastmessage FROM users WHERE id=?", Timestamp.class, user.getUid()); assertThat(last.toInstant(), equalTo(yoyoMsg.getNewMessage().get().getTimestamp())); assertEquals("should be message", true, commandsManager.processCommand(user, String.format("#%d", mid), emptyUri).getText().startsWith("@me")); User readerUser = userService.createUser("dummyReader", "dummySecret"); assertThat(commandsManager.processCommand(readerUser, "s", emptyUri).getText().startsWith("You are subscribed to"), is(true)); assertThat(commandsManager.processCommand(readerUser, "S", emptyUri).getText().startsWith("You are subscribed to"), is(true)); assertEquals("should be subscribed", "Subscribed", commandsManager.processCommand(readerUser, "S #" + mid, emptyUri).getText()); assertEquals("should be favorited", "Message is added to your recommendations", commandsManager.processCommand(readerUser, "! #" + mid, emptyUri).getText()); int rid = messagesService.createReply(mid, 0, user, "comment", null); assertEquals("number of subscribed users should match", 1, subscriptionService.getUsersSubscribedToComments( messagesService.getMessage(mid), messagesService.getReply(mid, rid)).size()); privacyQueriesService.blacklistUser(user, readerUser); assertEquals("number of subscribed users should match", 0, subscriptionService.getUsersSubscribedToComments( messagesService.getMessage(mid), messagesService.getReply(mid, rid)).size()); assertEquals("number of subscribed users should match", 1, subscriptionService.getUsersSubscribedToComments( messagesService.getMessage(mid), messagesService.getReply(mid, rid), true).size()); assertEquals("should be subscribed", "Subscribed to @" + user.getName(), commandsManager.processCommand(readerUser, "S @" + user.getName(), emptyUri) .getText()); List friends = userService.getUserFriends(readerUser.getUid()); assertEquals("number of friend users should match", 2, friends.size()); assertEquals("number of reader users should match", 1, userService.getUserReaders(user.getUid()).size()); String expectedSecondReply = "Reply posted.\n#" + mid + "/2 " + "https://juick.com/m/" + mid + "#2"; String expectedThirdReply = "Reply posted.\n#" + mid + "/3 " + "https://juick.com/m/" + mid + "#3"; assertEquals("should be second reply", expectedSecondReply, commandsManager.processCommand(user, "#" + mid + " yoyo", URI.create("http://static.juick.com/settings/facebook.png")).getText()); assertEquals("should be third reply", expectedThirdReply, commandsManager.processCommand(user, " \t\n #" + mid + "/2 ", URI.create("http://static.juick.com/settings/facebook.png")).getText()); Message reply = messagesService.getReplies(user, mid).stream().filter(m -> m.getRid() == 3).findFirst() .orElse(new Message()); Timestamp lastreply = jdbcTemplate.queryForObject("SELECT lastmessage FROM users WHERE id=?", Timestamp.class, user.getUid()); assertThat(lastreply.toInstant(), equalTo(reply.getTimestamp())); assertEquals("should be reply to second comment", 2, reply.getReplyto()); assertEquals("tags should NOT be updated", "It is not your message", commandsManager.processCommand(readerUser, "#" + mid + " *yo *there", emptyUri) .getText()); assertEquals("tags should be updated", "Tags are updated", commandsManager.processCommand(user, "#" + mid + " *there", emptyUri).getText()); assertEquals("number of tags should match", 2, tagService.getMessageTags(mid).size()); assertThat(messagesService.getMessage(mid).getTags().size(), is(2)); assertEquals("should be blacklisted", "Tag added to your blacklist", commandsManager.processCommand(readerUser, "BL *there", emptyUri).getText()); assertEquals("number of subscribed users should match", 0, subscriptionService.getSubscribedUsers(user.getUid(), mid).size()); assertEquals("tags should be updated", "Tags are updated", commandsManager.processCommand(user, "#" + mid + " *there", emptyUri).getText()); assertEquals("number of tags should match", 1, tagService.getMessageTags(mid).size()); User taggerUser = userService.createUser("dummyTagger", "dummySecret"); assertEquals("should be subscribed", "Subscribed", commandsManager.processCommand(taggerUser, "S *yo", emptyUri).getText()); assertEquals("number of subscribed users should match", 2, subscriptionService.getSubscribedUsers(user.getUid(), mid).size()); assertEquals("should be unsubscribed", "Unsubscribed from yo", commandsManager.processCommand(taggerUser, "U *yo", emptyUri).getText()); assertEquals("number of subscribed users should match", 1, subscriptionService.getSubscribedUsers(user.getUid(), mid).size()); assertEquals("number of readers should match", 1, userService.getUserReaders(user.getUid()).size()); String readerFeed = commandsManager.processCommand(readerUser, "#", emptyUri).getText(); assertTrue("description should match", readerFeed.startsWith("Your feed")); assertEquals("should be unsubscribed", "Unsubscribed from @" + user.getName(), commandsManager.processCommand(readerUser, "U @" + user.getName(), emptyUri) .getText()); assertEquals("number of readers should match", 0, userService.getUserReaders(user.getUid()).size()); assertEquals("number of friends should match", 1, userService.getUserFriends(user.getUid()).size()); assertEquals("should be unsubscribed", "Unsubscribed from #" + mid, commandsManager.processCommand(readerUser, "u #" + mid, emptyUri).getText()); assertEquals("number of subscribed users should match", 0, subscriptionService.getUsersSubscribedToComments(messagesService.getMessage(mid), messagesService.getReply(mid, rid)).size()); assertNotEquals("should NOT be deleted", String.format("Message %s deleted", mid), commandsManager.processCommand(readerUser, "D #" + mid, emptyUri).getText()); assertEquals("should be deleted", "Message deleted", commandsManager.processCommand(user, "D #" + mid, emptyUri).getText()); assertEquals("should be not found", "Message not found", commandsManager.processCommand(user, "#" + mid, emptyUri).getText()); String expectedCodeMessage = "some smelly code goes here\n" + "> void main(void** args) {\n" + "> }"; String codeAndTags = "*code\n" + expectedCodeMessage; Message codeAndTagsMessage = commandsManager.processCommand(user, codeAndTags, emptyUri).getNewMessage().get(); List codeAndTagsTags = codeAndTagsMessage.getTags(); assertEquals("expected single tag", 1, codeAndTagsTags.size()); assertEquals("the single tag should be the 'code'", "code", codeAndTagsTags.get(0).getName()); assertEquals("and the message should be with a C-code and without tags", expectedCodeMessage, codeAndTagsMessage.getText()); CommandResult result = commandsManager.processCommand(user, "*one *two *three *four *five *six test", emptyUri); assertThat(result.getNewMessage(), is(Optional.empty())); assertThat(result.getText(), is("Sorry, 5 tags maximum.")); result = commandsManager.processCommand(user, String.format("#%d *one *two *three *four *five *six", msg.getMid()), emptyUri); assertThat(result.getNewMessage(), is(Optional.empty())); assertThat(result.getText(), is("Tags are NOT updated (5 tags maximum?)")); result = commandsManager.processCommand(user, "I'm very smart to post my login url there" + "", emptyUri); assertThat(result.getNewMessage().isPresent(), is(true)); assertFalse(result.getNewMessage().get().getText().contains("VTYZkKV8FWkmu6g1")); result = commandsManager.processCommand(user, "*корм *juick_ppl *рационализм *? *мюсли а сколько микроморт в дневной порции сверхмюслей?", emptyUri); assertTrue(result.getNewMessage().isPresent()); String tags = "*Juick *Google *Google Play"; String data = "Вчера отправлял *NSFW постинг в топ :)"; result = commandsManager.processCommand(user, String.format("%s %s", tags, data), emptyUri); assertThat(result.getNewMessage().get().getTags().size(), equalTo(3)); assertThat(result.getNewMessage().get().getText(), equalTo(data)); tags = "*\u041a\u0438\u0435\u0432 *\u044d\u043a\u043e\u043b\u043e\u0433\u0438\u044f"; data = "* \u043c\u0443\u0441\u043e\u0440\\n\u0423 \u043c\u0435\u043d\u044f \u043a\u0430\u0436\u0434\u0443\u044e \u043d\u0435\u0434\u0435\u043b\u044e \u0441\u043e\u0431\u0438\u0440\u0430\u0435\u0442\u0441\u044f \u043f\u043e 4-5 \u0431\u0443\u0442\u044b\u043b\u043e\u043a 1,5\u043b \u041f\u0415\u0422. \u041c\u043d\u0435 \u0433\u0435\u043c\u043e\u0440\u043d\u043e \u0441\u043e\u0431\u0438\u0440\u0430\u0442\u044c \u043f\u043e \u043a\u0438\u043b\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0438\u043b\u0438 \u043f\u043e 5\u043a\u0433 \u044d\u0442\u043e\u0433\u043e \u043c\u0443\u0441\u043e\u0440\u0430, \u0447\u0442\u043e\u0431\u044b \u0432\u0435\u0437\u0442\u0438 \u0435\u0433\u043e \u0435\u0449\u0435 \u043a\u0443\u0434\u0430-\u0442\u043e.\\n\u041d\u0435, \u043d\u0443 \u0435\u0441\u0442\u044c \u043b\u044e\u0434\u0438, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0441\u043e\u0431\u0438\u0440\u0430\u044e\u0442 \u0432\u0442\u043e\u0440\u0441\u044b\u0440\u044c\u0435 \u043f\u043e \u043c\u0443\u0441\u043e\u0440\u043a\u0430\u043c, \u0441\u0432\u0430\u043b\u043a\u0430\u043c, \u043f\u043e\u0442\u043e\u043c\u0443 \u0447\u0442\u043e \u0434\u0435\u043d\u044c\u0433\u0438 \u043d\u0443\u0436\u043d\u044b. \u0418 \u0431\u044b\u0432\u0430\u044e\u0442 \u0441\u0442\u043e\u044f\u0442 \u043a\u043e\u043d\u0442\u0435\u0439\u043d\u0435\u0440\u044b-\u043a\u043b\u0435\u0442\u043a\u0438 \u0434\u043b\u044f \u043f\u043b\u0430\u0441\u0442\u0438\u043a\u0430, \u043d\u043e \u0442\u0430\u043a \u043a\u0430\u043a \u043c\u0443\u0441\u043e\u0440 \u0432\u044b\u0432\u043e\u0437\u044f\u0442 \u043d\u0435 \u0447\u0430\u0441\u0442\u043e \u0438\u043b\u0438 \u043b\u044e\u0434\u0438 \u0432\u043d\u0435\u0437\u0430\u043f\u043d\u043e \u0432\u044b\u043a\u0438\u0434\u044b\u0432\u0430\u044e\u0442 \u043c\u043d\u043e\u0433\u043e \u043c\u0443\u0441\u043e\u0440\u0430, \u0442\u043e \u0432 \u0442\u043e\u0439 \u043a\u043b\u0435\u0442\u043a\u0435 \u0442\u043e\u0442 \u043c\u0443\u0441\u043e\u0440, \u0447\u0442\u043e \u043d\u0435 \u043f\u043e\u043c\u0435\u0441\u0442\u0438\u043b\u0441\u044f \u0432 \u043e\u0431\u044b\u0447\u043d\u044b\u0445 \u043a\u043e\u043d\u0442\u0435\u0439\u043d\u0435\u0440\u0430\u0445."; result = commandsManager.processCommand(user, String.format("%s %s", tags, data), emptyUri); assertThat(result.getNewMessage().get().getTags().size(), equalTo(2)); assertThat(result.getNewMessage().get().getTags().get(0).getName(), equalTo("Киев")); assertThat(result.getNewMessage().get().getText(), equalTo(data)); result = commandsManager.processCommand(user, "S @unknown-user", emptyUri); assertThat(result.getNewMessage(), is(Optional.empty())); assertThat(result.getText(), is("User not found")); } @Test public void mailParserTest() throws Exception { String mail = "MIME-Version: 1.0\n" + "Received: by 10.176.0.242 with HTTP; Fri, 16 Mar 2018 05:31:50 -0700 (PDT)\n" + "In-Reply-To: <2891710.100@juick.com>\n" + "References: <2891710.0@juick.com> <2891710.100@juick.com>\n" + "Date: Fri, 16 Mar 2018 15:31:50 +0300\n" + "Delivered-To: vitalyster@gmail.com\n" + "Message-ID: \n" + "Subject: Re: New reply to TJ\n" + "From: Vitaly Takmazov \n" + "To: Juick \n" + "Content-Type: multipart/alternative; boundary=\"001a11454886e42be5056786ca70\"\n" + "\n" + "--001a11454886e42be5056786ca70\n" + "Content-Type: text/plain; charset=\"UTF-8\"\n" + "\n" + "s2313334\n" + "\n" + "--001a11454886e42be5056786ca70\n" + "Content-Type: text/html; charset=\"UTF-8\"\n" + "\n" + "
s2313334
\n" + "\n" + "--001a11454886e42be5056786ca70--"; mockMvc.perform(post("/mail").with(httpBasic(juickName, juickPassword)).content(mail)) .andExpect(status().isOk()); } @Test public void websocketsTest() throws Exception { ConfigurableApplicationContext context = new SpringApplicationBuilder( WebsocketClientConfig.class, PropertyPlaceholderAutoConfiguration.class) .run("--spring.main.web_environment=false"); long count = context.getBean(WebsocketClientConfig.class).getLatch().getCount(); WebsocketClientHandler handler = context.getBean(WebsocketClientHandler.class); assertThat(handler.getLastMessage(), is("Authorization required")); context.close(); Assert.assertThat(count, equalTo(0L)); mockMvc.perform(get("/ws/_all")).andExpect(status().isBadRequest()); } @Test public void recommendTests() throws Exception { Message msg = messagesService.createMessage(ugnich, "to be liked", null, null); String freefdHash = userService.getHashForUser(freefd); Message freefdMsg = messagesService.createMessage(freefd, "to be not liked", null, null); mockMvc.perform(post("/like?mid=" + msg.getMid() + "&hash=" + freefdHash)) .andExpect(status().isOk()) .andExpect(jsonPath("$.status", is("Message is added to your recommendations"))); mockMvc.perform(get("/thread?mid=" + msg.getMid() + "&hash=" + freefdHash)) .andExpect(status().isOk()) .andExpect(jsonPath("$[0].recommendations.length()", is(1))) .andExpect(jsonPath("$[0].recommendations[0]", is(freefdName))); mockMvc.perform(post("/like?mid=" + freefdMsg.getMid() + "&hash=" + freefdHash)) .andExpect(status().isForbidden()); } @Test public void likesTests() throws Exception{ User dsds = userService.createUser("dsds", "secret"); String freefdHash = userService.getHashForUser(freefd); Message msg1 = messagesService.createMessage(dsds, "yo", null, new ArrayList<>()); mockMvc.perform(post("/react?mid=" + msg1.getMid() + "&hash=" + freefdHash+ "&reactionId=2")) .andExpect(status().isOk()); assertThat(msg1.getLikes(), is(0)); assertThat(messagesService.getMessages(Collections.singletonList(msg1.getMid())).get(0).getLikes(), is(0)); Assert.assertEquals(1, msg1.getReactions().stream().filter(r -> r.getId() == 2) .findFirst().orElseThrow(IllegalStateException::new).getCount()); mockMvc.perform(post("/react?mid=" + msg1.getMid() + "&hash=" + freefdHash+ "&reactionId=1")) .andExpect(status().isOk()); mockMvc.perform(post("/react?mid=" + msg1.getMid() + "&hash=" + freefdHash+ "&reactionId=1")) .andExpect(status().isOk()); assertThat(msg1.getLikes(), is(1)); } @Test public void lastReadTests() throws Exception { assertThat(userService.isInBLAny(ugnich.getUid(), freefd.getUid()), is(false)); Message msg = messagesService.createMessage(ugnich, "to be watched", null, null); subscriptionService.subscribeMessage(msg, ugnich); messagesService.createReply(msg.getMid(), 0, freefd, "new reply", null); BiFunction lastRead = (user, m) -> jdbcTemplate.queryForObject( "SELECT last_read_rid FROM subscr_messages WHERE suser_id=? AND message_id=?", Integer.class, user.getUid(), m); assertThat(lastRead.apply(ugnich, msg.getMid()), is(0)); assertThat(messagesService.getUnread(ugnich).size(), is(1)); assertThat(messagesService.getUnread(ugnich).get(0), is(msg.getMid())); messagesService.getReplies(ugnich, msg.getMid()); assertThat(lastRead.apply(ugnich, msg.getMid()), is(1)); assertThat(messagesService.getUnread(ugnich).size(), is(0)); messagesService.setLastReadComment(ugnich, msg.getMid(), 0); assertThat(lastRead.apply(ugnich, msg.getMid()), is(1)); String ugnichHash = userService.getHashForUser(ugnich); int freefdrid = messagesService.createReply(msg.getMid(), 0, freefd, "again", null); mockMvc.perform(get(String.format("/thread/mark_read/%d-%d.gif?hash=%s", msg.getMid(), freefdrid, ugnichHash))) .andExpect(status().isOk()) .andExpect(content().bytes(IOUtils.toByteArray( Objects.requireNonNull(getClass().getClassLoader().getResource("Transparent.gif"))))); assertThat(lastRead.apply(ugnich, msg.getMid()), is(freefdrid)); privacyQueriesService.blacklistUser(ugnich, freefd); int newfreefdrid = messagesService.createReply(msg.getMid(), 0, freefd, "from ban", null); serverManager.processMessageEvent(new MessageEvent(this, messagesService.getReply(msg.getMid(), newfreefdrid), Collections.emptyList())); assertThat(userService.isReplyToBL(ugnich, messagesService.getReply(msg.getMid(), newfreefdrid)), is(true)); assertThat(lastRead.apply(ugnich, msg.getMid()), is(newfreefdrid)); privacyQueriesService.blacklistUser(ugnich, freefd); newfreefdrid = messagesService.createReply(msg.getMid(), 0, freefd, "after ban", null); assertThat(lastRead.apply(ugnich, msg.getMid()), lessThan(newfreefdrid)); mockMvc.perform(get(String.format("/thread?mid=%d&hash=%s", msg.getMid(), ugnichHash))) .andExpect(status().isOk()); assertThat(lastRead.apply(ugnich, msg.getMid()), is(newfreefdrid)); } @Test public void feedsShouldNotContainMessagesWithBannedTags() { Tag banned = tagService.getTag("banned", true); Message msg = messagesService.createMessage(ugnich, "yo", "jpg", Collections.singletonList(banned)); privacyQueriesService.blacklistTag(freefd, banned); assertTrue(messagesService.getMessages(messagesService.getAll(freefd.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); assertFalse(messagesService.getMessages(messagesService.getAll(ugnich.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); assertTrue(messagesService.getMessages(messagesService.getPhotos(freefd.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); assertFalse(messagesService.getMessages(messagesService.getPhotos(ugnich.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); jdbcTemplate.update("UPDATE messages SET popular=1 WHERE message_id=?", msg.getMid()); assertTrue(messagesService.getMessages(messagesService.getPopular(freefd.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); assertFalse(messagesService.getMessages(messagesService.getPopular(ugnich.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); } @Test public void tagsShouldBeDeserializedFromXml() throws JAXBException { XmppSessionConfiguration configuration = XmppSessionConfiguration.builder() .extensions(Extension.of(com.juick.Message.class)) .build(); XmppSession xmpp = new XmppSession("juick.com", configuration) { @Override public void connect(Jid from) { } @Override public Jid getConnectedResource() { return null; } }; String tag = "yo"; String xml = "yoyoyopeople"; Unmarshaller unmarshaller = xmpp.createUnmarshaller(); rocks.xmpp.core.stanza.model.Message xmppMessage = (rocks.xmpp.core.stanza.model.Message) unmarshaller.unmarshal(new StringReader(xml)); Tag xmlTag = (Tag) unmarshaller.unmarshal(new StringReader(tag)); assertThat(xmlTag.getName(), equalTo("yo")); Message juickMessage = xmppMessage.getExtension(Message.class); assertThat(juickMessage.getTags().get(0).getName(), equalTo("yo")); } @Test public void messageParserSerializer() throws ParserConfigurationException, IOException, SAXException, JAXBException { Message msg = new Message(); msg.setTags(MessageUtils.parseTags("test test" + (char) 0xA0 + "2 test3")); assertEquals("First tag must be", "test", msg.getTags().get(0).getName()); assertEquals("Third tag must be", "test3", msg.getTags().get(2).getName()); assertEquals("Count of tags must be", 3, msg.getTags().size()); Instant currentDate = Instant.now(); msg.setTimestamp(currentDate); String jsonMessage = jsonMapper.writeValueAsString(msg); assertEquals("date should be in timestamp field", DateFormattersHolder.getMessageFormatterInstance().format(currentDate), JsonPath.read(jsonMessage, "$.timestamp")); JAXBContext context = JAXBContext .newInstance(Message.class); Marshaller m = context.createMarshaller(); StringWriter sw = new StringWriter(); m.marshal(msg, sw); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new ByteArrayInputStream(sw.toString().getBytes(CharEncoding.UTF_8))); Node juickNode = doc.getElementsByTagName("juick").item(0); NamedNodeMap attrs = juickNode.getAttributes(); assertEquals("date should be in ts field", DateFormattersHolder.getMessageFormatterInstance().format(currentDate), attrs.getNamedItem("ts").getNodeValue()); } @Test public void restTemplateTests() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap map= new LinkedMultiValueMap<>(); HttpEntity> request = new HttpEntity<>(map, headers); map.add("body", "yo"); map.add("hash", userService.getHashForUser(ugnich)); ResponseEntity result = rest.postForEntity( "/post", request, CommandResult.class); assertThat(result.getStatusCode(), is(HttpStatus.OK)); } @Test public void emptyAuthenticatedPostShouldThrowBadRequest() throws Exception { mockMvc.perform(post("/post") .with(httpBasic(juickName, juickPassword))) .andExpect(status().isBadRequest()); } @Test public void attachmentSizeTests() throws URISyntaxException, IOException { ImageUtils imageUtils = new ImageUtils(StringUtils.EMPTY, StringUtils.EMPTY); Attachment attachment = imageUtils.getAttachment(new File(getClass().getClassLoader().getResource("Transparent.gif").toURI())); assertThat(attachment.getHeight(), is(1)); assertThat(attachment.getWidth(), is(1)); } @Test public void meContainsAllInfo() throws Exception { jdbcTemplate.update("DELETE FROM subscr_users"); assertThat(userService.getUserReaders(ugnich.getUid()).size(), is(0)); assertThat(userService.getUserFriends(ugnich.getUid()).size(), is(0)); commandsManager.processCommand(freefd, "S @ugnich", emptyUri); commandsManager.processCommand(ugnich, "S @freefd", emptyUri); assertThat(userService.getUserReaders(ugnich.getUid()).size(), is(1)); String hash = userService.getHashForUser(ugnich); mockMvc.perform(get("/me") .with(httpBasic(ugnichName, ugnichPassword))) .andExpect(jsonPath("$.hash", is(hash))) .andExpect(jsonPath("$.readers.length()", is(1))) .andExpect(jsonPath("$.read.length()", is(1))); } @Test public void feedsShouldNotContainBannedUsers() throws Exception { commandsManager.processCommand(ugnich, "BL @freefd", emptyUri); CommandResult result = commandsManager.processCommand(ugnich, "freefd - dick", emptyUri); int mid = result.getNewMessage().get().getMid(); commandsManager.processCommand(freefd, String.format("#%d ugnich - dick too", mid), emptyUri); commandsManager.processCommand(juick, String.format("#%d/1 ban for a hour!", mid), emptyUri); commandsManager.processCommand(juick, String.format("#%d freefd is here but it is hidden from you", mid), emptyUri); assertThat(messagesService.getMessage(mid).getReplies(), is(3)); Message reply = messagesService.getReply(mid, 3); assertThat(userService.isReplyToBL(ugnich, reply), is(false)); List replies = messagesService.getReplies(ugnich, mid); assertThat(replies.size(), is(1)); commandsManager.processCommand(freefd, String.format("#%d/3 hahaha!", mid), emptyUri); assertThat(messagesService.getMessage(mid).getReplies(), is(4)); replies = messagesService.getReplies(ugnich, mid); assertThat(replies.size(), is(1)); commandsManager.processCommand(juick, String.format("#%d/4 mmm?!", mid), emptyUri); assertThat(messagesService.getMessage(mid).getReplies(), is(5)); replies = messagesService.getReplies(ugnich, mid); reply = messagesService.getReply(mid, 5); assertThat(userService.isReplyToBL(ugnich, reply), is(true)); assertThat(replies.size(), is(1)); commandsManager.processCommand(ugnich, "BL @freefd", emptyUri); messagesService.setLastReadComment(ugnich, mid, 5); } @Test public void cmykJpegShouldBeProcessedCorrectly() throws Exception { CommandResult postJpgCmyk = commandsManager.processCommand(ugnich, "YO", URI.create("classpath:cmyk.jpg")); assertThat(postJpgCmyk.getNewMessage().isPresent(), is(true)); int mid = postJpgCmyk.getNewMessage().get().getMid(); File originalFile = Paths.get(imgDir, "p", String.format("%d.jpg", mid)).toFile(); assertThat(originalFile.exists(), is(true)); File mediumFile = Paths.get(imgDir, "photos-1024", String.format("%d.jpg", mid)).toFile(); assertThat(mediumFile.exists(), is(true)); assertThat(postJpgCmyk.getNewMessage().get().getAttachment().getWidth(), is(2585)); assertThat(postJpgCmyk.getNewMessage().get().getAttachment().getHeight(), is(3335)); assertThat(postJpgCmyk.getNewMessage().get().getAttachment().getMedium().getHeight(), is(1024)); assertThat(postJpgCmyk.getNewMessage().get().getAttachment().getSmall().getHeight(), is(512)); } @Test public void changeExtensionWhenReceiveFileWithWrongContentType() throws Exception { Path pngOutput = Paths.get(tmpDir, "cmyk.png"); Files.delete(pngOutput); Files.copy(getClass().getClassLoader().getResourceAsStream("cmyk.jpg"), pngOutput); assertThat(pngOutput.toFile().exists(), is(true)); CommandResult postJpgCmyk = commandsManager.processCommand(ugnich, "YO", pngOutput.toUri()); assertThat(postJpgCmyk.getNewMessage().isPresent(), is(true)); assertThat(postJpgCmyk.getNewMessage().get().getAttachmentType(), is("jpg")); CommandResult replyJpgCmyk = commandsManager.processCommand(ugnich, String.format("#%d YO", postJpgCmyk.getNewMessage().get().getMid()), pngOutput.toUri()); assertThat(replyJpgCmyk.getNewMessage().isPresent(), is(true)); assertThat(replyJpgCmyk.getNewMessage().get().getAttachmentType(), is("jpg")); } @Test public void emailTest() { User tezzt = userService.createUser("tezzt", "12346"); jdbcTemplate.update("INSERT INTO emails(user_id, email) VALUES(?, 'yo@example.com')", tezzt.getUid()); User user = userService.getUserByEmail("yo@example.com"); assertThat(user, is(tezzt)); } }