From 82bfc234f7451c96a648145a103a127195cc73ee Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 25 Nov 2021 23:12:41 +0300 Subject: Fix tests on Windows --- .../java/com/juick/server/tests/ServerTests.java | 109 ++++++++++++--------- 1 file changed, 63 insertions(+), 46 deletions(-) (limited to 'src') diff --git a/src/test/java/com/juick/server/tests/ServerTests.java b/src/test/java/com/juick/server/tests/ServerTests.java index 9bc945d6..1ef8fe7f 100644 --- a/src/test/java/com/juick/server/tests/ServerTests.java +++ b/src/test/java/com/juick/server/tests/ServerTests.java @@ -67,6 +67,7 @@ import java.io.StringWriter; import java.io.Writer; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -399,7 +400,11 @@ public class ServerTests { @AfterEach public void teardown() throws IOException { String imgDir = storageService.getImageDirectory(); - FileSystemUtils.deleteRecursively(Paths.get(imgDir)); + try { + FileSystemUtils.deleteRecursively(Paths.get(imgDir)); + } catch (FileSystemException e) { + // Skip Windows exceptions when files are in use + } } @Test @@ -808,12 +813,14 @@ public class ServerTests { assertThat(messagesService.getPopularCandidates().isEmpty(), is(true)); tagService.updateTags(topmid, Collections.singletonList(juickTag)); assertThat(messagesService.getPopularCandidates().isEmpty(), is(false)); - CommandResult resultRecommend = commandsManager.commandRecommend(serviceUser, URI.create(""), String.valueOf(topmid)); + CommandResult resultRecommend = commandsManager.commandRecommend(serviceUser, URI.create(""), + String.valueOf(topmid)); List msgs = messagesService.getUserRecommendations(serviceUser.getUid(), 0); assertThat(msgs.get(0), is(topmid)); List allMsgs = messagesService.getUserBlogWithRecommendations(serviceUser, ugnich, 0, 0); assertThat(allMsgs.contains(topmid), is(true)); - CommandResult resultUndo = commandsManager.commandRecommend(serviceUser, URI.create(""), String.valueOf(topmid)); + CommandResult resultUndo = commandsManager.commandRecommend(serviceUser, URI.create(""), + String.valueOf(topmid)); assertThat(messagesService.getPopularCandidates().isEmpty(), is(false)); jdbcTemplate.update("INSERT INTO tags(tag_id, name) VALUES(805, 'NSFW')"); Tag nsfw = tagService.getTag("NSFW", false); @@ -1095,8 +1102,8 @@ public class ServerTests { assertThat(lastRead.apply(ugnich, mid), is(freefdrid)); privacyQueriesService.blacklistUser(ugnich, freefd); int newfreefdrid = messagesService.createReply(mid, 0, freefd, "from ban", null); - serverManager.processSystemEvent(new SystemEvent(this, - SystemActivity.message(serviceUser, messagesService.getReply(mid, newfreefdrid), Collections.emptyList()))); + serverManager.processSystemEvent(new SystemEvent(this, SystemActivity.message(serviceUser, + messagesService.getReply(mid, newfreefdrid), Collections.emptyList()))); assertThat(userService.isReplyToBL(ugnich, messagesService.getReply(mid, newfreefdrid)), is(true)); // TODO: test event listeners correctly Thread.sleep(2000L); @@ -1122,9 +1129,13 @@ public class ServerTests { assertFalse(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getPhotos(ugnich.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); messagesService.recommendMessage(mid, serviceUser.getUid()); - assertThat(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getUserBlogWithRecommendations(serviceUser, freefd, 0, 0)) + assertThat(messagesService + .getMessages(AnonymousUser.INSTANCE, + messagesService.getUserBlogWithRecommendations(serviceUser, freefd, 0, 0)) .stream().noneMatch(m -> m.getTags().contains(banned)), is(true)); - assertFalse(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getUserBlogWithRecommendations(serviceUser, ugnich, 0, 0)) + assertFalse(messagesService + .getMessages(AnonymousUser.INSTANCE, + messagesService.getUserBlogWithRecommendations(serviceUser, ugnich, 0, 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); assertThat( messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getMyFeed(freefd.getUid(), 0, true)) @@ -1218,13 +1229,15 @@ public class ServerTests { @Test public void emptyAuthenticatedPostShouldThrowBadRequest() throws Exception { - mockMvc.perform(post("/api/post").with(httpBasic(serviceUser.getName(), "password"))).andExpect(status().isBadRequest()); + mockMvc.perform(post("/api/post").with(httpBasic(serviceUser.getName(), "password"))) + .andExpect(status().isBadRequest()); } @Test public void attachmentSizeTests() throws IOException { String tmpPng = "tmp.png"; - Files.copy(defaultAvatar.getFile().toPath(), Paths.get(storageService.getTemporaryDirectory(), tmpPng), StandardCopyOption.REPLACE_EXISTING); + Files.copy(defaultAvatar.getFile().toPath(), Paths.get(storageService.getTemporaryDirectory(), tmpPng), + StandardCopyOption.REPLACE_EXISTING); storageService.saveAvatar(tmpPng, serviceUser); Attachment attachment = storageService.getAvatarMetadata(serviceUser); assertThat(attachment.getHeight(), is(96)); @@ -1282,7 +1295,8 @@ public class ServerTests { assertThat(messagesService.getTag(tag.TID, freefd.getUid(), 0, 10).size(), is(1)); assertThat(messagesService.getTag(tag.TID, ugnich.getUid(), 0, 10).size(), is(0)); messagesService.recommendMessage(freefdMsg, serviceUser.getUid()); - assertThat(messagesService.getUserBlogWithRecommendations(serviceUser, ugnich, 0, 0).contains(freefdMsg), is(false)); + assertThat(messagesService.getUserBlogWithRecommendations(serviceUser, ugnich, 0, 0).contains(freefdMsg), + is(false)); commandsManager.processCommand(ugnich, "BL @freefd", emptyUri); } @@ -1410,20 +1424,26 @@ public class ServerTests { .getNewMessage().get(); assertThat(editedComment.getText(), is("HEY, JOE")); assertThat(editedComment.getUpdatedAt(), greaterThan(editedComment.getCreated())); - jdbcTemplate.update("UPDATE replies SET updated_at='1990-05-05 00:00:00' WHERE message_id=? AND reply_id=?", editedComment.getMid(), editedComment.getRid()); + jdbcTemplate.update("UPDATE replies SET updated_at='1990-05-05 00:00:00' WHERE message_id=? AND reply_id=?", + editedComment.getMid(), editedComment.getRid()); Message updatedComment = comment.getNewMessage().get(); result = mockMvc - .perform(post("/api/update").with(httpBasic(freefdName, freefdPassword)) - .param("mid", String.valueOf(updatedComment.getMid())) - .param("rid", String.valueOf(updatedComment.getRid())).param("body", "HEY, JOE AGAIN")) - .andExpect(status().isBadRequest()).andReturn(); - assertThat(messagesService.deleteReply(ugnich.getUid(), updatedComment.getMid(), updatedComment.getRid()), is(false)); - assertThat(messagesService.deleteReply(freefd.getUid(), updatedComment.getMid(), updatedComment.getRid()), is(true)); - assertThat(messagesService.getReply(updatedComment.getMid(), updatedComment.getRid()).getUser(), is(archiveUser)); - jdbcTemplate.update("UPDATE messages_txt SET updated_at='1990-05-05 00:00:00' WHERE message_id=?", original.getMid()); + .perform(post("/api/update").with(httpBasic(freefdName, freefdPassword)) + .param("mid", String.valueOf(updatedComment.getMid())) + .param("rid", String.valueOf(updatedComment.getRid())).param("body", "HEY, JOE AGAIN")) + .andExpect(status().isBadRequest()).andReturn(); + assertThat(messagesService.deleteReply(ugnich.getUid(), updatedComment.getMid(), updatedComment.getRid()), + is(false)); + assertThat(messagesService.deleteReply(freefd.getUid(), updatedComment.getMid(), updatedComment.getRid()), + is(true)); + assertThat(messagesService.getReply(updatedComment.getMid(), updatedComment.getRid()).getUser(), + is(archiveUser)); + jdbcTemplate.update("UPDATE messages_txt SET updated_at='1990-05-05 00:00:00' WHERE message_id=?", + original.getMid()); assertThat(messagesService.deleteMessage(ugnich.getUid(), original.getMid()), is(true)); assertThat(messagesService.getMessageAuthor(original.getMid()), is(archiveUser)); - jdbcTemplate.update("UPDATE messages_txt SET updated_at=? WHERE message_id=?", Instant.now(), original.getMid()); + jdbcTemplate.update("UPDATE messages_txt SET updated_at=? WHERE message_id=?", Instant.now(), + original.getMid()); assertThat(messagesService.deleteMessage(ugnich.getUid(), original.getMid()), is(false)); assertThat(messagesService.deleteMessage(archiveUser.getUid(), original.getMid()), is(true)); } @@ -2045,17 +2065,14 @@ public class ServerTests { testSignatureString = signatureManager.addSignature(testapp, "localhost", "POST", inboxUri, testRequestDate, digestHeader, testKeystoreManager); mockMvc.perform(post(inboxUri).header("Host", testHost).header("Date", testRequestDate) - .header("Signature", testSignatureString) - .header("Digest", digestHeader) - .contentType(Context.LD_JSON_MEDIA_TYPE).content(payload)) - .andExpect(status().isAccepted()); + .header("Signature", testSignatureString).header("Digest", digestHeader) + .contentType(Context.LD_JSON_MEDIA_TYPE).content(payload)).andExpect(status().isAccepted()); apClient.setRequestFactory(originalRequestFactory); } @Test public void serviceUserProfileIsApplicationProfile() throws Exception { - MvcResult response = mockMvc.perform(get("/u/juick") - .accept(Context.ACTIVITY_MEDIA_TYPE)).andReturn(); + MvcResult response = mockMvc.perform(get("/u/juick").accept(Context.ACTIVITY_MEDIA_TYPE)).andReturn(); Actor actor = jsonMapper.readValue(response.getResponse().getContentAsString(), Actor.class); assertThat(actor, is(instanceOf(Application.class))); } @@ -2135,7 +2152,8 @@ public class ServerTests { messagesService.likeMessage(msg.getMid(), freefd.getUid(), Reaction.LIKE); messagesService.likeMessage(msg.getMid(), 0, Reaction.LIKE, "http://localhost:8080/u/test"); messagesService.recommendMessage(msg.getMid(), serviceUser.getUid()); - List top = messagesService.getMessages(ugnich, messagesService.getUserBlogWithRecommendations(serviceUser, ugnich, 0, 0)); + List top = messagesService.getMessages(ugnich, + messagesService.getUserBlogWithRecommendations(serviceUser, ugnich, 0, 0)); assertThat(top.size(), is(1)); } @@ -2152,7 +2170,7 @@ public class ServerTests { String imgDir = storageService.getImageDirectory(); ClassPathResource defaultAvatar = new ClassPathResource("static/av-96.png"); String hash = DigestUtils.md5DigestAsHex(IOUtils.toByteArray(defaultAvatar.getInputStream())); - + assertThat(webApp.getAvatarUrl(userService.getUserByName(freefdName)), is(String.format("http://localhost:8080/av-96-%s.png", hash))); @@ -2166,10 +2184,9 @@ public class ServerTests { assertThat(DigestUtils.md5DigestAsHex(IOUtils.toByteArray(newUri)), is(newHash)); URI convertedAvatarUri = Paths.get(imgDir, "a", String.format("%d.png", freefd.getUid())).toUri(); String convertedAvatarHash = DigestUtils.md5DigestAsHex(IOUtils.toByteArray(convertedAvatarUri)); - mockMvc.perform(get("/api/me").with(httpBasic(freefdName, freefdPassword))) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.avatar", - is(String.format("http://localhost:8080/i/a/%d-%s.png", freefd.getUid(), convertedAvatarHash)))); + mockMvc.perform(get("/api/me").with(httpBasic(freefdName, freefdPassword))).andExpect(status().isOk()) + .andExpect(jsonPath("$.avatar", is( + String.format("http://localhost:8080/i/a/%d-%s.png", freefd.getUid(), convertedAvatarHash)))); mockMvc.perform(post("/api/me").with(httpBasic(ugnichName, ugnichPassword)).param("password", "newPassword")) .andExpect(status().isOk()); mockMvc.perform(get("/api/me").with(httpBasic(ugnichName, ugnichPassword))) @@ -2244,7 +2261,9 @@ public class ServerTests { ClientHttpRequestFactory originalRequestFactory = apClient.getRequestFactory(); MockRestServiceServer restServiceServer = MockRestServiceServer.createServer(apClient); restServiceServer.expect(times(2), requestTo(delete.getObject().getId())) - .andRespond(withSuccess(IOUtils.toString(testSuspendedUserResponse.getInputStream(), StandardCharsets.UTF_8), MediaType.APPLICATION_JSON)); + .andRespond(withSuccess( + IOUtils.toString(testSuspendedUserResponse.getInputStream(), StandardCharsets.UTF_8), + MediaType.APPLICATION_JSON)); Person testuser = (Person) signatureManager.getContext(URI.create(delete.getObject().getId())).get(); Instant now = Instant.now(); String testRequestDate = DateFormattersHolder.getHttpDateFormatter().format(now); @@ -2254,11 +2273,8 @@ public class ServerTests { String testSignatureString = signatureManager.addSignature(testuser, "localhost", "POST", inboxUri, testRequestDate, digestHeader, testKeystoreManager); mockMvc.perform(post(inboxUri).contentType(ACTIVITY_MEDIA_TYPE).content(deleteJsonStr) - .header("Host", "localhost") - .header("Date", testRequestDate) - .header("Digest", digestHeader) - .header("Signature", testSignatureString)) - .andExpect(status().isAccepted()); + .header("Host", "localhost").header("Date", testRequestDate).header("Digest", digestHeader) + .header("Signature", testSignatureString)).andExpect(status().isAccepted()); apClient.setRequestFactory(originalRequestFactory); Mockito.verify(deleteListener, Mockito.times(1)).onApplicationEvent(deleteEventCaptor.capture()); DeleteUserEvent receivedEvent = deleteEventCaptor.getValue(); @@ -2298,12 +2314,11 @@ public class ServerTests { Create create = jsonMapper.readValue(noteString, Create.class); Note note = (Note) create.getObject(); String markdown = remarkConverter.convertFragment((String) note.getContent()); - String commandBody = note.getContent() == null ? markdown - : note.getAttachment().stream().map(attachment -> { - String attachmentUrl = attachment.getUrl(); - String attachmentName = attachment.getName(); - return PlainTextFormatter.markdownUrl(attachmentUrl, attachmentName); - }).reduce(markdown, (current, next) -> String.format("%s\n%s", current, next)); + String commandBody = note.getContent() == null ? markdown : note.getAttachment().stream().map(attachment -> { + String attachmentUrl = attachment.getUrl(); + String attachmentName = attachment.getName(); + return PlainTextFormatter.markdownUrl(attachmentUrl, attachmentName); + }).reduce(markdown, (current, next) -> String.format("%s\n%s", current, next)); } @Test @@ -2397,7 +2412,8 @@ public class ServerTests { public void topEventShouldNotLossUser() { Message topMessage = MockUtils.mockMessage(1000, ugnich, "top message"); topMessage.setTo(AnonymousUser.INSTANCE); - SystemEvent event = new SystemEvent(this, SystemActivity.like(serviceUser, topMessage, Collections.emptyList())); + SystemEvent event = new SystemEvent(this, + SystemActivity.like(serviceUser, topMessage, Collections.emptyList())); applicationEventPublisher.publishEvent(event); Mockito.verify(notificationListener, Mockito.times(1)).onApplicationEvent(topEventCaptor.capture()); SystemEvent receivedEvent = topEventCaptor.getValue(); @@ -2515,8 +2531,9 @@ public class ServerTests { @Test public void invalidMediaTypeTest() throws Exception { mockMvc.perform(get("/api/messages").header("Accept", "application/xml")).andExpect(status().isBadRequest()) - .andExpect(content().string("Invalid media type")); + .andExpect(content().string("Invalid media type")); } + @Test public void emptyContextShouldNotSerializeType() throws Exception { Context context = new Context("http://juick.com/u/ermine"); -- cgit v1.2.3