@Test public void test_runScript() throws Exception { requestAddModule(); String filename = FilenameUtils.getName(testScriptPath); if (filename == null) { logger.info("No script found - test escape"); } else { MockMultipartFile file = new MockMultipartFile( "file", filename, "application/sql", new FileInputStream(testScriptPath)); String genericModule = NamingUtils.getContainerName(applicationName, module, "johndoe"); ResultActions result = mockMvc.perform( fileUpload("/module/{moduleName}/run-script", genericModule) .file(file) .session(session) .contentType(MediaType.MULTIPART_FORM_DATA)) .andDo(print()); result.andExpect(status().isOk()); } }
@Test public void testCreateFromDocuments() throws Exception { List<MultipartFile> files = Stream.of( new MockMultipartFile("files", "filename.txt", "text/plain", "hello".getBytes(StandardCharsets.UTF_8)), new MockMultipartFile("files", "filename.txt", "text/plain", "hello2".getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); List<StoredDocument> storedDocuments = files.stream().map(f -> new StoredDocument()).collect(Collectors.toList()); when(this.auditedStoredDocumentOperationsService.createStoredDocuments(files)).thenReturn(storedDocuments); restActions .withAuthorizedUser("userId") .withAuthorizedService("divorce") .postDocuments("/documents", files, Classifications.PUBLIC, null) .andExpect(status().isOk()); }
@Test public void testCreateFromDocumentsWithNonWhitelistFile() throws Exception { List<MultipartFile> files = Stream.of( new MockMultipartFile("files", "filename.txt", "text/plain", "hello".getBytes(StandardCharsets.UTF_8)), new MockMultipartFile("files", "filename.txt", "", "hello2".getBytes(StandardCharsets.UTF_8))) .collect(Collectors.toList()); List<StoredDocument> storedDocuments = files.stream().map(f -> new StoredDocument()).collect(Collectors.toList()); when(this.auditedStoredDocumentOperationsService.createStoredDocuments(files)).thenReturn(storedDocuments); restActions .withAuthorizedUser("userId") .withAuthorizedService("divorce") .postDocuments("/documents", files, Classifications.PUBLIC, null) .andExpect(status().is4xxClientError()); }
@Test public void testGetBinary() throws Exception { DocumentContentVersion documentContentVersion = new DocumentContentVersion(new StoredDocument(), new MockMultipartFile("files", "filename.txt", "text/plain", "hello".getBytes(StandardCharsets.UTF_8)), null); documentContentVersion.setCreatedBy("userId"); when(documentContentVersionService.findMostRecentDocumentContentVersionByStoredDocumentId(id)).thenReturn( documentContentVersion ); restActions .withAuthorizedUser("userId") .withAuthorizedService("divorce") .get("/documents/" + id + "/binary") .andExpect(status().isOk()); }
@Test public void testGetThumbnail() throws Exception { DocumentContentVersion documentContentVersion = new DocumentContentVersion(new StoredDocument(), new MockMultipartFile("files", "filename.txt", "text/plain", "hello".getBytes(StandardCharsets.UTF_8)), null); documentContentVersion.setCreatedBy("userId"); when(documentContentVersionService.findMostRecentDocumentContentVersionByStoredDocumentId(id)).thenReturn( documentContentVersion ); restActions .withAuthorizedUser("userId") .withAuthorizedService("divorce") .get("/documents/" + id + "/thumbnail") .andExpect(status().isOk()); }
public ResultActions postDocument(String urlTemplate, MultipartFile file) { return translateException(() -> mvc.perform( MockMvcRequestBuilders.fileUpload(urlTemplate).file((MockMultipartFile)file) .headers(httpHeaders) )); }
public ResultActions postDocumentVersion(String urlTemplate, MockMultipartFile file) { MockMultipartHttpServletRequestBuilder builder = MockMvcRequestBuilders.fileUpload(urlTemplate); builder.with(request -> { request.setMethod("POST"); return request; }); return translateException(() -> mvc.perform( builder .file(file) .headers(httpHeaders) )); }
@Test public void should_write_cmd_log() throws Throwable { // given: String zoneName = defaultZones.get(0).getName(); String agentName = "test-agent-005"; CmdInfo baseInfo = new CmdInfo(zoneName, agentName, CmdType.RUN_SHELL, "/test.sh"); Cmd created = cmdService.create(baseInfo); byte[] mockData = "test".getBytes(); String originalFilename = created.getId() + ".out.zip"; MockMultipartFile mockMultipartFile = new MockMultipartFile("file", originalFilename, "application/zip", mockData); // when: cmdService.saveLog(created.getId(), mockMultipartFile); // then: Assert.assertTrue(Files.exists(Paths.get(cmdLogDir.toString(), originalFilename))); }
@Test public void testMultiPart() throws Exception { MockMultipartFile firstFile = new MockMultipartFile("data", "filename.txt", "text/plain", "some xml".getBytes()); MockMultipartFile secondFile = new MockMultipartFile("data", "other-file-name.data", "text/plain", "some other type".getBytes()); MockMultipartFile jsonFile = new MockMultipartFile("json", "", "application/json", "{\"json\": \"someValue\"}".getBytes()); this.requestMockMvc.perform(MockMvcRequestBuilders.fileUpload("/post/multiPart") .file(firstFile) .file(secondFile).file(jsonFile) .param("some-random", "4")) .andExpect(status().is(200)) .andReturn(); this.bothMockMvc.perform(MockMvcRequestBuilders.fileUpload("/post/multiPart") .file(firstFile) .file(secondFile).file(jsonFile) .param("some-random", "4")) .andExpect(status().is(200)) .andReturn(); }
@Test public void classifyImageOk() throws Exception { byte[] bytes = Files.readAllBytes(Paths.get(resourceLoader.getResource("classpath:boat.jpg").getURI())); MockMultipartFile file = new MockMultipartFile("file", "boat.jpg", "image/jpeg", bytes); String blowfish = this.mockMvc.perform( fileUpload("/api/classify") .file(file)) .andDo(document("classify-image-ok/{step}", preprocessRequest(prettyPrint(), replacePattern(Pattern.compile(".*"), "...boat.jpg multipart binary contents...")), preprocessResponse(prettyPrint()))) .andExpect(status().isOk()) .andExpect(jsonPath("label", notNullValue())) .andExpect(jsonPath("probability", notNullValue())) .andReturn().getResponse().getContentAsString(); }
@Test public void saveOneWithMultipartFile() { Picture picture = pictures.getFirst(); byte[] file = new byte[1]; file[0] = ' '; MultipartFile multipartFile = new MockMultipartFile(picture.getName(), file); service.save(picture, multipartFile); assertTrue(picture.equals(service.findOne(picture.getId()))); Path f = Paths.get(picture.getPath() + picture.getName() + picture.getFileType()); if (Files.exists(f)) service.delete(picture); else fail("the picture wasn't created"); }
@Test public void saveOneWithMultipartFileExistNameInDirectory() { Picture picture = pictures.getFirst(); Picture secondPicture = new Picture(picture.getPath(), picture.getName(), picture.getFileType()); byte[] file = new byte[1]; file[0] = ' '; MultipartFile multipartFile = new MockMultipartFile(picture.getName(), file); service.save(picture, multipartFile); service.save(secondPicture, multipartFile); assertTrue(picture.equals(service.findOne(picture.getId()))); assertNull("Error\n(Check your directory, and delete picture with name \"name0\" if exist from last test?)", service.findOne(secondPicture)); File f = new File(picture.getPath() + picture.getName() + picture.getFileType()); if (f.exists() && !f.isDirectory()) service.delete(picture); else fail("the picture wasn't created"); }
@Test public void uploadFile() throws Exception { Picture picture = new Picture(ApplicationProperties.PICTURE_PATH, "name", "jpg"); pictureSaver.deletePicture(picture); byte[] file = new byte[1]; file[0] = ' '; MultipartFile multipartFile = new MockMultipartFile(picture.getName(), file); pictureSaver.uploadFile(picture, multipartFile); Path existPicture = Paths.get(picture.getPath() + picture.getName() + picture.getFileType()); if (Files.exists(existPicture)) pictureSaver.deletePicture(picture); else fail("the picture wasn't created"); existPicture = Paths.get(picture.getPath() + picture.getName() + picture.getFileType()); if (Files.exists(existPicture)) fail("picture still exists"); }
@Test public void failedWebToUnknownMimeType() throws Exception { final long previousRevision = revisionService.getLatest(); final long previousSize = mediaService.getAll().size(); final MediaType newMediaType = MediaType.IMAGE; final MediaType mediaType = MediaType.IMAGE; final MockMultipartFile jsonFile = new MockMultipartFile("file", "texte.jpeg", "sdfsdf", "{json:null}".getBytes()); formMediaMetadataDto.setMediaType(newMediaType.toString()); mockMvc.perform(fileUploadAuthenticated("/media/" + formMediaMetadataDto.getUuid() + "/file") .file(jsonFile) ) .andDo(MockMvcResultHandlers.print()) .andExpect(status().isBadRequest()) .andExpect(content().string(MediaController.MESSAGE_MEDIA_TYPE_NOT_SUPPORTED)) .andReturn(); Assert.assertEquals(previousSize, mediaService.getAll().size()); Assert.assertEquals(previousRevision, revisionService.getLatest()); }
@Test public void failedPutFileWithWrongUuid() throws Exception { final long previousRevision = revisionService.getLatest(); final long previousSize = mediaService.getAll().size(); final MediaType newMediaType = MediaType.IMAGE; final MediaType mediaType = MediaType.IMAGE; final MockMultipartFile jsonFile = new MockMultipartFile("file", "texte.jpeg", "sdfsdf", "{json:null}".getBytes()); formMediaMetadataDto.setMediaType(newMediaType.toString()); mockMvc.perform(fileUploadAuthenticated("/media/sdpfosdfiosd/file") .file(jsonFile) ) .andDo(MockMvcResultHandlers.print()) .andExpect(status().isNotFound()) .andReturn(); Assert.assertEquals(previousSize, mediaService.getAll().size()); Assert.assertEquals(previousRevision, revisionService.getLatest()); }
@Test public void testAddAndDeleteImage() throws IOException { final UUID imageId = UUID.randomUUID(); final byte[] imageData = Files.readAllBytes(new File("frontend/app/assets/images/select2.png").toPath()); final MultipartFile file = new MockMultipartFile("test.png", "//test/test.png", "image/png", imageData); withPerson(person -> { final SrvaEvent srvaEvent = model().newSrvaEvent(person); onSavedAndAuthenticated(createUser(person), () -> { //add try { mobileSrvaCrudFeature.addImage(srvaEvent.getId(), imageId, file); assertEquals(1, gameDiaryImageRepo.findBySrvaEvent(srvaEvent).size()); assertEquals(imageId, gameDiaryImageRepo.findBySrvaEvent(srvaEvent).get(0).getFileMetadata().getId()); } catch (IOException e) { e.printStackTrace(); fail(); } //delete mobileSrvaCrudFeature.deleteImage(imageId); assertEquals(0, gameDiaryImageRepo.findBySrvaEvent(srvaEvent).size()); }); }); }
@Test public void testSaveImageTwice() throws IOException { final SystemUser user = createUserWithPerson(); final Harvest harvest = model().newHarvest(user.getPerson()); persistInNewTransaction(); authenticate(user); final long harvestId = harvest.getId(); final UUID imageId = UUID.randomUUID(); final byte[] imageData = Files.readAllBytes(new File("frontend/app/assets/images/select2.png").toPath()); final MultipartFile file = new MockMultipartFile("test.png", "//test/test.png", "image/png", imageData); feature.addGameDiaryImageForDiaryEntry(harvestId, GameDiaryEntryType.HARVEST, imageId, file); feature.addGameDiaryImageForDiaryEntry(harvestId, GameDiaryEntryType.HARVEST, imageId, file); assertNotNull(feature.getGameDiaryImageBytes(imageId, false)); }
@Test public void shouldCreateDeviceFirmwareMD5() throws Exception { when(deviceConfigSetupService.save(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(DeviceFirmware.class))) .thenReturn(ServiceResponseBuilder.<DeviceFirmware>ok() .withResult(deviceFirmware).build()); getMockMvc().perform(MockMvcRequestBuilders .fileUpload(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, deviceModel.getName())) .file(new MockMultipartFile("firmware", "00000".getBytes())) .file(new MockMultipartFile("checksum", "dcddb75469b4b4875094e14561e573d8 file.bin".getBytes())) .param("version", deviceFirmware.getVersion()) .contentType(MediaType.MULTIPART_FORM_DATA) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.code", is(HttpStatus.CREATED.value()))) .andExpect(jsonPath("$.status", is("success"))) .andExpect(jsonPath("$.timestamp",greaterThan(1400000000))) .andExpect(jsonPath("$.messages").doesNotExist()) .andExpect(jsonPath("$.result").isMap()) .andExpect(jsonPath("$.result.version", is(deviceFirmware.getVersion()))) .andExpect(jsonPath("$.result.uploadTimestamp", notNullValue())) ; }
@Test public void shouldCreateDeviceFirmwareSHA1() throws Exception { when(deviceConfigSetupService.save(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(DeviceFirmware.class))) .thenReturn(ServiceResponseBuilder.<DeviceFirmware>ok() .withResult(deviceFirmware).build()); getMockMvc().perform(MockMvcRequestBuilders .fileUpload(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, deviceModel.getName())) .file(new MockMultipartFile("firmware", "00000".getBytes())) .file(new MockMultipartFile("checksum", "6934105ad50010b814c933314b1da6841431bc8b".getBytes())) .param("version", deviceFirmware.getVersion()) .contentType(MediaType.MULTIPART_FORM_DATA) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.code", is(HttpStatus.CREATED.value()))) .andExpect(jsonPath("$.status", is("success"))) .andExpect(jsonPath("$.timestamp",greaterThan(1400000000))) .andExpect(jsonPath("$.messages").doesNotExist()) .andExpect(jsonPath("$.result").isMap()) .andExpect(jsonPath("$.result.version", is(deviceFirmware.getVersion()))) .andExpect(jsonPath("$.result.uploadTimestamp", notNullValue())) ; }
@Test public void shouldTryCreateDeviceFirmwareWithInvalidChecksum() throws Exception { when(deviceConfigSetupService.save(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(DeviceFirmware.class))) .thenReturn(ServiceResponseBuilder.<DeviceFirmware>error() .withMessage(DeviceFirmwareService.Validations.FIRMWARE_ALREADY_REGISTERED.getCode()) .withResult(deviceFirmware).build()); getMockMvc().perform(MockMvcRequestBuilders .fileUpload(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, deviceModel.getName())) .file(new MockMultipartFile("firmware", "00000".getBytes())) .file(new MockMultipartFile("checksum", "00000".getBytes())) .param("version", deviceFirmware.getVersion()) .contentType(MediaType.MULTIPART_FORM_DATA) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is4xxClientError()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.code", is(HttpStatus.BAD_REQUEST.value()))) .andExpect(jsonPath("$.status", is("error"))) .andExpect(jsonPath("$.timestamp", greaterThan(1400000000))) .andExpect(jsonPath("$.messages[0]", is("Invalid checksum (MD5 or SHA1)"))) .andExpect(jsonPath("$.result").doesNotExist()) ; }
@Test public void shouldTryCreateDeviceFirmwareWithBadRequest() throws Exception { when(deviceConfigSetupService.save(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(DeviceFirmware.class))) .thenReturn(ServiceResponseBuilder.<DeviceFirmware>error() .withMessage(DeviceFirmwareService.Validations.FIRMWARE_ALREADY_REGISTERED.getCode()) .withResult(deviceFirmware).build()); getMockMvc().perform(MockMvcRequestBuilders .fileUpload(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, deviceModel.getName())) .file(new MockMultipartFile("firmware", "00000".getBytes())) .file(new MockMultipartFile("checksum", "dcddb75469b4b4875094e14561e573d8".getBytes())) .param("version", deviceFirmware.getVersion()) .contentType(MediaType.MULTIPART_FORM_DATA) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is4xxClientError()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.code", is(HttpStatus.BAD_REQUEST.value()))) .andExpect(jsonPath("$.status", is("error"))) .andExpect(jsonPath("$.timestamp", greaterThan(1400000000))) .andExpect(jsonPath("$.messages[0]", is("Firmware already registered"))) .andExpect(jsonPath("$.result").doesNotExist()) ; }
@Test public void shouldTryCreateDeviceFirmwareWithBadDeviceModel() throws Exception { when(deviceModelService.getByTenantApplicationAndName(tenant, application, "invalid model")) .thenReturn(ServiceResponseBuilder.<DeviceModel> error() .withMessage(DeviceModelService.Validations.DEVICE_MODEL_NOT_FOUND.getCode()) .withResult(deviceModel).build()); getMockMvc().perform(MockMvcRequestBuilders .fileUpload(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, "invalid model")) .file(new MockMultipartFile("firmware", "00000".getBytes())) .file(new MockMultipartFile("checksum", "dcddb75469b4b4875094e14561e573d8".getBytes())) .param("version", deviceFirmware.getVersion()) .contentType(MediaType.MULTIPART_FORM_DATA) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is4xxClientError()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.code", is(HttpStatus.NOT_FOUND.value()))) .andExpect(jsonPath("$.status", is("error"))) .andExpect(jsonPath("$.timestamp", greaterThan(1400000000))) .andExpect(jsonPath("$.messages[0]", is("Device model not found"))) .andExpect(jsonPath("$.result").doesNotExist()) ; }
@Test public void createShouldThrowException() throws Exception { final MockMultipartFile multipartFile = new MockMultipartFile("assetData", this.getClass().getResourceAsStream("/eu/euregjug/site/assets/asset.png")); when(this.gridFsTemplate.findOne(any(Query.class))).thenReturn(mock(GridFSDBFile.class)); mvc .perform( fileUpload("/api/assets") .file(multipartFile) ) .andExpect(status().isConflict()) .andExpect(content().string("")); verify(this.gridFsTemplate).findOne(any(Query.class)); verifyNoMoreInteractions(this.gridFsTemplate); }
@Test public void createShouldWork() throws Exception { final MockMultipartFile multipartFile = new MockMultipartFile("assetData", "asset.png", null, this.getClass().getResourceAsStream("/eu/euregjug/site/assets/asset.png")); when(this.gridFsTemplate.findOne(any(Query.class))).thenReturn(null); mvc .perform( fileUpload("/api/assets") .file(multipartFile) ) .andExpect(status().isCreated()) .andExpect(content().string("asset.png")) .andDo(document("api/assets/create", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()) )); verify(this.gridFsTemplate).findOne(any(Query.class)); verify(this.gridFsTemplate).store(any(InputStream.class), eq("asset.png"), eq("image/png")); verifyNoMoreInteractions(this.gridFsTemplate); }
@Test @DirtiesContext public void failedMimetypeDetectionShouldWork() throws Exception { final Reflect controllerReflect = Reflect.on(this.controller); // Much more evil isn't possible, i guess... DirtiesContext!!!! Tika tika = controllerReflect.field("tika").get(); tika = spy(tika); when(tika.detect(any(InputStream.class), any(String.class))).thenThrow(IOException.class); controllerReflect.set("tika", tika); final MockMultipartFile multipartFile = new MockMultipartFile("assetData", "asset.png", null, this.getClass().getResourceAsStream("/eu/euregjug/site/assets/asset.png")); when(this.gridFsTemplate.findOne(any(Query.class))).thenReturn(null); mvc .perform( fileUpload("/api/assets") .file(multipartFile) ) .andExpect(status().isCreated()) .andExpect(content().string("asset.png")); verify(this.gridFsTemplate).findOne(any(Query.class)); verify(this.gridFsTemplate).store(any(InputStream.class), eq("asset.png"), isNull(String.class)); verifyNoMoreInteractions(this.gridFsTemplate); }
@Test @UsingDataSet(locations={"AttachControllerTests.json", "UserControllerTests.json"}, loadStrategy=LoadStrategyEnum.CLEAN_INSERT) public void updateWithImageTEST() throws Exception { FileInputStream fis = new FileInputStream("src/main/resources/static/flavio.jpeg"); MockMultipartFile data = new MockMultipartFile("file","flavio.jpeg", "image/jpeg", fis); UsernamePasswordAuthenticationToken principal = this.getPrincipal("flavio"); User user = userService.findOne(new ObjectId("56fab17ee4b074b1e6b6cb01")); ObjectId photoId = user.getMember() == null ? null : user.getMember().getPhotoId(); String result = mvc.perform(MockMvcRequestBuilders.fileUpload("/api/member/56fab17ee4b074b1e6b6cb01/image").file(data) .accept(MediaType.APPLICATION_JSON).principal(principal)) .andDo(print()) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); JSONObject json = new JSONObject(result); JSONObject member = json.getJSONObject("member"); assertTrue(member.get("photoId")!=photoId.toString()); }
@Test @UsingDataSet(locations={"AttachControllerTests.json", "UserControllerTests.json"}, loadStrategy=LoadStrategyEnum.CLEAN_INSERT) public void updateWithImageTEST2() throws Exception { FileInputStream fis = new FileInputStream("src/main/resources/static/flavio2.jpg"); MockMultipartFile data = new MockMultipartFile("file","flavio2.jpg", "image/jpeg", fis); UsernamePasswordAuthenticationToken principal = this.getPrincipal("flavio"); User user = userService.findOne(new ObjectId("56fab17ee4b074b1e6b6cb01")); ObjectId photoId = user.getMember() == null ? null : user.getMember().getPhotoId(); String result = mvc.perform(MockMvcRequestBuilders.fileUpload("/api/member/56fab17ee4b074b1e6b6cb01/image").file(data) .accept(MediaType.APPLICATION_JSON).principal(principal)) .andDo(print()) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); JSONObject json = new JSONObject(result); JSONObject member = json.getJSONObject("member"); assertTrue(member.get("photoId")!=photoId.toString()); }
@Test @UsingDataSet(locations={"AttachControllerTests.json", "UserControllerTests.json"}, loadStrategy=LoadStrategyEnum.CLEAN_INSERT) public void updateWithImageTEST3() throws Exception { FileInputStream fis = new FileInputStream("src/main/resources/static/flavio2.jpg"); MockMultipartFile data = new MockMultipartFile("file","flavio2.jpg", "image/jpeg", fis); UsernamePasswordAuthenticationToken principal = this.getPrincipal("flavio"); User silvio = userService.findOne(new ObjectId("56fab17ee4b074b1e6b6cb02")); ObjectId photoId = silvio.getMember() == null ? null : silvio.getMember().getPhotoId(); String result = mvc.perform(MockMvcRequestBuilders.fileUpload("/api/member/56fab17ee4b074b1e6b6cb02/image").file(data) .accept(MediaType.APPLICATION_JSON).principal(principal)) .andDo(print()) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); JSONObject json = new JSONObject(result); JSONObject member = json.getJSONObject("member"); assertTrue(member.get("photoId")!=photoId.toString()); }
@Test @UsingDataSet(locations={"AttachControllerTests.json", "UserControllerTests.json", "ClubControllerTests.json"}, loadStrategy=LoadStrategyEnum.CLEAN_INSERT) public void updateWithImageTEST() throws Exception { FileInputStream fis = new FileInputStream("src/main/resources/static/logo.jpg"); MockMultipartFile data = new MockMultipartFile("file","logo.jpg", "image/jpeg", fis); UsernamePasswordAuthenticationToken principal = this.getPrincipal("flavio"); String result = mvc.perform(MockMvcRequestBuilders.fileUpload("/api/club/56fab17ee4b074b1e6b6ca80/image").file(data) .accept(MediaType.APPLICATION_JSON).principal(principal)) .andDo(print()) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); JSONObject json = new JSONObject(result); assertTrue(json.get("logoId")!=null); }
@Test public void testSplitAndSaveFile() throws Exception { final Path path = get(resourceUrl.toURI()); try (InputStream inputStream = newInputStream(path)) { final MockMultipartFile file = new MockMultipartFile("file3", "test.mp3", null, inputStream); assertTrue(manager.saveTrack(file).isPresent()); final File[] files = get(testTrackDirectory.getAbsolutePath(), "test.mp3") .toFile() .listFiles((dir, name) -> name.matches("\\d+")); long chunks = file.getSize() / FileManager.CHUNK_SIZE; long left = file.getSize() % FileManager.CHUNK_SIZE; assertEquals(left > 0 ? chunks + 1 : chunks, files.length); final File newFile = new File(testTrackDirectory, "new music.mp3"); mergeFiles(files, newFile); assertEquals(file.getSize(), newFile.length()); } }
/** * Perform a POST request to check the {@link SpringletsImageFileConverter} works. * * Only the needed autoconfiguration is loaded in order to create * the Spring Web MVC artifacts to handle the HTTP request. * * @see MockServletContext * @see MockMvc */ @Test public void checkConverter() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "springlets.image.management:true"); this.context.setServletContext(new MockServletContext()); this.context.register(TestConfiguration.class); this.context.refresh(); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); // Mock a multipart file to be sended MockMultipartFile imageFile = new MockMultipartFile("image", "image1.jpg", "image/jpg", "image1.jpg".getBytes()); mockMvc .perform(MockMvcRequestBuilders.fileUpload("/persons").file(imageFile) .param("name", "TESTNAME").param("surname", "TESTSURNAME")) .andExpect(status().isOk()).andDo(print()); }
@Test public void testPutResultsForJava() throws Exception { // when(travisClient.getBuild(anyLong())).thenReturn() MockMultipartFile multipartFile = new MockMultipartFile("samples", "java-profiler-result.jandy", MediaType.APPLICATION_OCTET_STREAM_VALUE, ClassLoader.getSystemResourceAsStream("java-profiler-result.jandy")); MockMvcBuilders.standaloneSetup(controller).build() .perform(MockMvcRequestBuilders.fileUpload("/rest/travis") .file(multipartFile) .contentType(MediaType.MULTIPART_FORM_DATA) .param("ownerName", "jcooky") .param("repoName", "jandy") .param("buildId", "1") .param("branchName", "master") .param("buildNum", "1") .param("language", "java") ) .andExpect(MockMvcResultMatchers.status().is2xxSuccessful()) .andDo(MockMvcResultHandlers.print()); }
@Test public void testStore() throws Exception { MultipartFile objectFile = new MockMultipartFile("content.zip", "original-content.zip", "application/zip", new byte[]{(byte) 0xFE, (byte) 0xED}); assetObjectService.store(objectFile, "parent-1", AssetObjectPurpose.SOURCE); final ArgumentCaptor<AssetObject> savedCaptor = ArgumentCaptor.forClass(AssetObject.class); verify(assetObjectRepo).save(savedCaptor.capture()); final AssetObject saved = savedCaptor.getValue(); assertThat(saved.getId(), startsWith(SimpleUUIDGenerator.PREFIX)); assertThat(saved.getAssetId(), equalTo("parent-1")); assertThat(saved.getPurpose(), equalTo(AssetObjectPurpose.SOURCE)); assertThat(saved.getOriginalFileName(), equalTo("original-content.zip")); final File[] files = storageDir.listFiles(); assertThat(files, arrayWithSize(1)); assertThat(files[0].length(), equalTo(2L)); final byte[] content = Files.readAllBytes(files[0].toPath()); assertThat(content, Matchers.equalTo(new byte[]{(byte) 0xFE, (byte) 0xED})); }
@Test public void should_upload_a_local_asset() throws Exception { //We construct a mockfile (the first arg is the name of the property expected in the controller MockMultipartFile file = new MockMultipartFile("file", "myfile.js", "application/javascript", "foo".getBytes()); Page page = mockPageOfId("my-page"); Asset expectedAsset = anAsset().withId("assetId").active().withName("myfile.js").withOrder(2).withScope(PAGE) .withType(AssetType.JAVASCRIPT).build(); when(pageAssetService.upload(file, page, "js")).thenReturn(expectedAsset); mockMvc.perform(fileUpload("/rest/pages/my-page/assets/js").file(file)) .andExpect(status().isCreated()) .andExpect(jsonPath("$.id").value("assetId")) .andExpect(jsonPath("$.name").value("myfile.js")) .andExpect(jsonPath("$.scope").value(PAGE.toString())) .andExpect(jsonPath("$.type").value("js")) .andExpect(jsonPath("$.order").value(2)); verify(pageAssetService).upload(file, page, "js"); }
@Test public void testAddParagraphImage() throws Exception { _dbInjecter.injectUser("manager"); Article article = _dbInjecter.injectArticle("title", "intro", ArticleType.BLOG, "manager", 1000000L); _dbInjecter.injectParagraphToArticle(article, "paragraph title", "paragraph text"); FileInputStream fileInputStream = new FileInputStream("src/test/resources/images/" + "article1.jpg"); MockMultipartFile image = new MockMultipartFile("file", "file.jpg","image/jpg", fileInputStream); MediaType mediaType = new MediaType("multipart", "form-data"); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/paragraph/upload/image") .file(image) .contentType(mediaType) .param("articleId", "1") .param("paragraphId", "1")) .andExpect(status().isOk()); assertThat(_paragraphRepository.findOne(1L) .getImageFileName()).isEqualTo("article_1_paragraph_1.jpg"); TestUtil.deleteFilesInDirectory(new File(FileSystemInjector.getArticleFolder())); }
@Test public void should_import_a_page_with_its_dependencies() throws Exception { //We construct a mockfile (the first arg is the name of the property expected in the controller MockMultipartFile file = new MockMultipartFile("file", "myfile.zip", "application/zip", "foo".getBytes()); ImportReport expectedReport = anImportReportFor(aPage().withId("aPage").withName("thePage")).withUUID("UUIDZipFile").withStatus(ImportReport.Status.CONFLICT) .withAdded(aWidget().id("addedWidget").name("newWidget")) .withOverridden(aWidget().id("overriddenWidget").name("oldWidget")).build(); when(pathImporter.importFromPath(unzipedPath, pageImporter)).thenReturn(expectedReport); mockMvc.perform(fileUpload("/import/page").file(file)) .andExpect(content().contentType(MediaType.TEXT_PLAIN)) .andExpect(status().isCreated()) .andExpect(jsonPath("uuid").value("UUIDZipFile")) .andExpect(jsonPath("extractedDirName").doesNotExist()) .andExpect(jsonPath("element.id").value("aPage")) .andExpect(jsonPath("status").value("conflict")) .andExpect(jsonPath("element.name").value("thePage")) .andExpect(jsonPath("dependencies.added.widget[0].id").value("addedWidget")) .andExpect(jsonPath("dependencies.added.widget[0].name").value("newWidget")) .andExpect(jsonPath("dependencies.overridden.widget[0].id").value("overriddenWidget")) .andExpect(jsonPath("dependencies.overridden.widget[0].name").value("oldWidget")); }
@Test public void should_force_a_page_import() throws Exception { //We construct a mockfile (the first arg is the name of the property expected in the controller MockMultipartFile file = new MockMultipartFile("file", "myfile.zip", "application/zip", "foo".getBytes()); ImportReport expectedReport = anImportReportFor(aPage().withId("aPage").withName("thePage")).withUUID("UUIDZipFile").withStatus(ImportReport.Status.IMPORTED) .withAdded(aWidget().id("addedWidget").name("newWidget")) .withOverridden(aWidget().id("overriddenWidget").name("oldWidget")).build(); when(pathImporter.forceImportFromPath(unzipedPath, pageImporter)).thenReturn(expectedReport); mockMvc.perform(fileUpload("/import/page?force=true").file(file)) .andExpect(content().contentType(MediaType.TEXT_PLAIN)) .andExpect(status().isCreated()) .andExpect(jsonPath("uuid").value("UUIDZipFile")) .andExpect(jsonPath("extractedDirName").doesNotExist()) .andExpect(jsonPath("element.id").value("aPage")) .andExpect(jsonPath("status").value("imported")) .andExpect(jsonPath("element.name").value("thePage")) .andExpect(jsonPath("dependencies.added.widget[0].id").value("addedWidget")) .andExpect(jsonPath("dependencies.added.widget[0].name").value("newWidget")) .andExpect(jsonPath("dependencies.overridden.widget[0].id").value("overriddenWidget")) .andExpect(jsonPath("dependencies.overridden.widget[0].name").value("oldWidget")); }
@Test public void should_respond_an_error_with_ok_code_when_import_exception_occurs_while_zip_file_could_not_be_opened() throws Exception { MockMultipartFile file = new MockMultipartFile("file", "myfile.zip", "application/zip", "foo".getBytes()); when(unzipper.unzipInTempDir(any(InputStream.class), anyString())).thenThrow(ZipException.class); mockMvc.perform(fileUpload("/import/widget").file(file)) .andExpect(content().contentType(MediaType.TEXT_PLAIN)) .andExpect(status().isAccepted()) .andExpect(jsonPath("type").value("CANNOT_OPEN_ZIP")) .andExpect(jsonPath("message").value("Cannot open zip file")); mockMvc.perform(fileUpload("/import/page").file(file)) .andExpect(content().contentType(MediaType.TEXT_PLAIN)) .andExpect(status().isAccepted()) .andExpect(jsonPath("type").value("CANNOT_OPEN_ZIP")) .andExpect(jsonPath("message").value("Cannot open zip file")); }
@Test public void should_respond_an_error_with_ok_code_when_import_exception_occurs_while_unzipping() throws Exception { MockMultipartFile file = new MockMultipartFile("file", "myfile.zip", "application/zip", "foo".getBytes()); when(unzipper.unzipInTempDir(any(InputStream.class), anyString())).thenThrow(IOException.class); mockMvc.perform(fileUpload("/import/widget").file(file)) .andExpect(content().contentType(MediaType.TEXT_PLAIN)) .andExpect(status().isAccepted()) .andExpect(jsonPath("type").value("SERVER_ERROR")) .andExpect(jsonPath("message").value("Error while unzipping zip file")); mockMvc.perform(fileUpload("/import/page").file(file)) .andExpect(content().contentType(MediaType.TEXT_PLAIN)) .andExpect(status().isAccepted()) .andExpect(jsonPath("type").value("SERVER_ERROR")) .andExpect(jsonPath("message").value("Error while unzipping zip file")); }