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 uploadTest() throws Exception { byte[] data = generateRandomByteArray(rnd, 10 * 1024); byte[] hash = getSHA256Hash(data); String path = CSAR_BASE_URL + "rnd"; MockMultipartHttpServletRequestBuilder builder = buildMockedMultipartUploadRequest(data, path); ResultActions resultActions = mvc.perform( builder ).andDo(print()).andExpect(status().is2xxSuccessful()); resultActions.andReturn(); assertNotNull(dataRead); assertEquals(data.length, dataRead.length); byte[] hashUpload = getSHA256Hash(this.dataRead); assertHashesEqual(hash, hashUpload); }
@Override public ResultActions testUpdateNode(final BaseNode node) throws Exception { // configure request MockMultipartFile file = new MockMultipartFile("uploadFile", "myFile2.txt", "text/plain", "hello2".getBytes()); MockMultipartFile json = new MockMultipartFile("node", "", "application/json", convertObjectToJsonBytes(node)); file = null; MockMultipartHttpServletRequestBuilder req = MockMvcRequestBuilders.fileUpload( "/nodes/update/" + node.getClassName() + "/" + node.getSysUID()); req.file(json); if (file != null) { req.file(file); } ResultActions res = testBaseRequest(req); // check data res.andExpect(jsonPath("$.node.name", is(node.getName()))) .andExpect(jsonPath("$.node.sysUID", is(node.getSysUID()))); return res; }
@Test public void uploadTestArchiveAlreadyExists() throws Exception { //Generate 10 KiB of random data byte[] data = generateRandomByteArray(rnd, 10); String path = CSAR_BASE_URL + "apache"; MockMultipartHttpServletRequestBuilder builder = buildMockedMultipartUploadRequest(data, path); ResultActions resultActions = mvc.perform( builder ).andDo(print()).andExpect(status().is(201)); resultActions.andReturn(); }
@Test public void importWithoutEmail() throws Exception { MockMultipartFile addressList = new MockMultipartFile("file", "postalcode;city;".getBytes()); MockMultipartHttpServletRequestBuilder builder = fileUpload("/staticaddresses/import"); builder.file(addressList); builder.param("email", ""); ResultActions resultActions = perform(builder); resultActions.andExpect(status().is2xxSuccessful()); resultActions.andExpect(model().attribute("message", hasProperty("type", is(ERROR)))); verifyZeroInteractions(staticAddressFileServiceMock); }
@Override public String testCreateNode(final String parentId, final BaseNode node) throws Exception { // configure request MockMultipartFile file = new MockMultipartFile("uploadFile", "myFile.txt", "text/plain", "hello".getBytes()); MockMultipartFile json = new MockMultipartFile("node", "", "application/json", convertObjectToJsonBytes(node)); file = null; MockMultipartHttpServletRequestBuilder req = MockMvcRequestBuilders.fileUpload( "/nodes/create/" + node.getClassName() + "/" + parentId); req.file(json); if (file != null) { req.file(file); } ResultActions res = testBaseRequest(req); // check data res.andExpect(jsonPath("$.node.name", is(node.getName()))) .andExpect(jsonPath("$.node.sysUID", IsNull.notNullValue())); // create JSON from String String response = res.andReturn().getResponse().getContentAsString(); String sysUID = JsonPath.read(response, "$.node.sysUID"); return sysUID; }
@Test public void should_upload_and_download_zipped_log() throws Throwable { // given: ClassLoader classLoader = CmdControllerTest.class.getClassLoader(); URL resource = classLoader.getResource("test-cmd-id.out.zip"); Path path = Paths.get(resource.getFile()); byte[] data = Files.readAllBytes(path); CmdInfo cmdBase = new CmdInfo("test-zone-1", "test-agent-1", CmdType.RUN_SHELL, "~/hello.sh"); Cmd cmd = cmdService.create(cmdBase); String originalFilename = cmd.getId() + ".out.zip"; MockMultipartFile zippedCmdLogPart = new MockMultipartFile("file", originalFilename, "application/zip", data); MockMultipartFile cmdIdPart = new MockMultipartFile("cmdId", "", "text/plain", cmd.getId().getBytes()); // when: upload zipped cmd log MockMultipartHttpServletRequestBuilder content = fileUpload("/cmd/log/upload") .file(zippedCmdLogPart) .file(cmdIdPart); this.mockMvc.perform(content) .andDo(print()) .andExpect(status().isOk()); // then: check upload file path and logging queue Path zippedLogPath = Paths.get(cmdLogDir.toString(), originalFilename); Assert.assertTrue(Files.exists(zippedLogPath)); Assert.assertEquals(data.length, Files.size(zippedLogPath)); // when: download uploaded zipped cmd log MvcResult result = this.mockMvc.perform(get("/cmd/log/download") .param("cmdId", cmd.getId()).param("index", Integer.toString(0))) .andDo(print()) .andExpect(status().isOk()) .andReturn(); // then: MockHttpServletResponse response = result.getResponse(); Assert.assertEquals("application/zip", response.getContentType()); Assert.assertEquals(data.length, response.getContentLength()); Assert.assertTrue(response.getHeader("Content-Disposition").contains(originalFilename)); }
@Test @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) public void testCytobandsManagement() throws Exception { Chromosome chromosome; ResultActions actions; MockMultipartHttpServletRequestBuilder builder; // creates a corresponded test genome 'classpath:templates/reference/hp.genome.fa' final Reference reference = createGenome(); // 1. tries to save cytobands corresponded to the reference registered above final Resource resource = getTemplateResource(FileTemplates.HP_CYTOBANDS.getPath()); final MockMultipartFile multipartFile = new MockMultipartFile(UPLOAD_FILE_PARAM, resource.getFilename(), null, resource.getInputStream()); builder = MockMvcRequestBuilders.fileUpload(SAVE_CYTOBANDS); actions = mvc() .perform(builder .file(multipartFile) .param(REFERENCE_ID_PARAM, String.valueOf(reference.getId())) .contentType(MediaType.MULTIPART_FORM_DATA_VALUE)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE)) .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists()) .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name())) .andExpect(MockMvcResultMatchers.jsonPath(JPATH_MESSAGE).value(getMessage("info.cytobands.upload.done", resource.getFilename()))); actions.andDo(MockMvcResultHandlers.print()); // 2. tries to get a track with cytobands for a particular chromosome chromosome = reference.getChromosomes().stream().filter(e -> e.getName().equals(CHR_A1)) .findAny().get(); actions = mvc() .perform(get(String.format(LOAD_CYTOBANDS, chromosome.getId()))) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE)) .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).exists()) .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.OK.name())); ResponseResult<Track<Cytoband>> result = getObjectMapper() .readValue(actions.andReturn().getResponse().getContentAsByteArray(), getTypeFactory().constructParametrizedType(ResponseResult.class, ResponseResult.class, getTypeFactory().constructParametrizedType(Track.class, Track.class, Cytoband.class))); final Track<Cytoband> track = result.getPayload(); Assert.assertTrue("Unexpected number of bands.", CHR_NUMBER_OF_BANDS == track.getBlocks().size()); Assert.assertTrue("Unexpected a beginning position for a track.", 1 == track.getStartIndex()); ReflectionAssert.assertReflectionEquals("Unexpected chromosome.", chromosome, track.getChromosome()); Assert.assertTrue("Unexpected an ending position for a track.", track.getEndIndex().equals( chromosome.getSize())); actions.andDo(MockMvcResultHandlers.print()); // 3. tries to get a track for a chromosome without cytobands chromosome = reference.getChromosomes().stream().filter(e -> e.getName().equals(CHR_A5)) .findAny().get(); actions = mvc() .perform(get(String.format(LOAD_CYTOBANDS, chromosome.getId()))) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().contentType(EXPECTED_CONTENT_TYPE)) .andExpect(MockMvcResultMatchers.jsonPath(JPATH_PAYLOAD).doesNotExist()) .andExpect(MockMvcResultMatchers.jsonPath(JPATH_STATUS).value(ResultStatus.WARN.name())); actions.andDo(MockMvcResultHandlers.print()); }
public ResultActions postDocuments(String urlTemplate, List<MultipartFile> files, Classifications classification, List<String> roles) { MockMultipartHttpServletRequestBuilder builder = MockMvcRequestBuilders.fileUpload(urlTemplate); builder.param("classification", classification.toString()); files.forEach(f -> builder.file((MockMultipartFile) f)); return translateException(() -> mvc.perform( builder.headers(httpHeaders) )); }
/** * Make a MULTIPART Form POST with authentication for this webservice * * @param path Path to Post * @return MockHttpServletRequestBuilder */ protected MockMultipartHttpServletRequestBuilder fileUploadAuthenticated(String path) { return (MockMultipartHttpServletRequestBuilder) fileUpload(URI.create(path)).header(RequireValidUserTest.HEADER_AUTHORIZATION, getHeaderAuthenticationContent()); }