org.springframework.mock.web.MockMultipartFile Java Examples
The following examples show how to use
org.springframework.mock.web.MockMultipartFile.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GrayConfigControllerTest.java From AthenaServing with Apache License 2.0 | 6 votes |
/** * 新增灰度配置 * * @throws Exception */ @Test public void test_quick_start_3_addGrayConfig() throws Exception { ClassPathResource classPathResource1 = new ClassPathResource("1.yml"); MockMultipartFile multipartFile1 = new MockMultipartFile("file", "1.yml", "application/octet-stream", classPathResource1.getInputStream()); ClassPathResource classPathResource2 = new ClassPathResource("2.yml"); MockMultipartFile multipartFile2 = new MockMultipartFile("file", "2.yml", "application/octet-stream", classPathResource2.getInputStream()); ClassPathResource classPathResource3 = new ClassPathResource("3.yml"); MockMultipartFile multipartFile3 = new MockMultipartFile("file", "3.yml", "application/octet-stream", classPathResource3.getInputStream()); String result = this.mockMvc.perform(MockMvcRequestBuilders.fileUpload("/api/v1/grayConfig/addGrayConfig") .file(multipartFile1) .file(multipartFile2) .file(multipartFile3) .param("project", "测试项目") .param("cluster", "测试集群") .param("service", "测试服务") .param("version", "测试版本") .param("versionId", "3776343244166660096") .param("desc", "测试sdk") .param("grayId", "3780699522712207360") .param("name", "test") .contentType(MediaType.MULTIPART_FORM_DATA) .session((MockHttpSession) Utils.getLoginSession(this.mockMvc)) .accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk()) .andReturn().getResponse().getContentAsString(); Utils.assertResult(result); }
Example #2
Source File: OpenRestServiceTest.java From flow-platform-x with Apache License 2.0 | 6 votes |
@Test public void should_save_job_report() { // given: Flow flow = flowService.create("user-test"); Job job = new Job(); job.setId("12345"); job.setFlowId(flow.getId()); job.setBuildNumber(1L); Mockito.when(jobDao.findByKey(Mockito.any())).thenReturn(Optional.of(job)); MockMultipartFile uploadFile = new MockMultipartFile("jacoco-report.zip", "content".getBytes()); CreateJobReport report = new CreateJobReport() .setName("jacoco") .setZipped(true) .setType(ContentType.HTML); // when: openRestService.saveJobReport(flow.getName(), job.getBuildNumber(), report, uploadFile); // then: List<JobReport> reports = jobReportDao.findAllByJobId(job.getId()); Assert.assertNotNull(reports); Assert.assertEquals(1, reports.size()); }
Example #3
Source File: OpenRestServiceTest.java From flow-platform-x with Apache License 2.0 | 6 votes |
@Test public void should_save_job_report() { // given: Flow flow = flowService.create("user-test"); Job job = new Job(); job.setId("12345"); job.setFlowId(flow.getId()); job.setBuildNumber(1L); Mockito.when(jobDao.findByKey(Mockito.any())).thenReturn(Optional.of(job)); MockMultipartFile uploadFile = new MockMultipartFile("jacoco-report.zip", "content".getBytes()); CreateJobReport report = new CreateJobReport() .setName("jacoco") .setZipped(true) .setType(ContentType.HTML); // when: openRestService.saveJobReport(flow.getName(), job.getBuildNumber(), report, uploadFile); // then: List<JobReport> reports = jobReportDao.findAllByJobId(job.getId()); Assert.assertNotNull(reports); Assert.assertEquals(1, reports.size()); }
Example #4
Source File: IndexControllerTest.java From Mahuta with Apache License 2.0 | 6 votes |
@Test public void indexFile() throws Exception { BuilderAndResponse<IndexingRequest, IndexingResponse> builderAndResponse = indexingRequestUtils.generateRandomInputStreamIndexingRequest(); InputStreamIndexingRequest request = (InputStreamIndexingRequest) builderAndResponse.getBuilder().getRequest(); // Create Index mockMvc.perform(post("/config/index/" + request.getIndexName()).contentType(MediaType.APPLICATION_JSON).content(BytesUtils.readFile("index_mapping.json"))) .andExpect(status().isOk()) .andDo(print()); MockMultipartFile mockMultipartFile = new MockMultipartFile("file", "test_file", request.getContentType(), IOUtils.toByteArray(request.getContent())); request.setContent(null); MockMultipartFile mockMultipartRequest = new MockMultipartFile("request", "", "application/json", mapper.writeValueAsBytes((AbstractIndexingRequest)request)); MvcResult response = mockMvc.perform(multipart("/index/file") .file(mockMultipartFile) .file(mockMultipartRequest)) .andDo(print()) .andExpect(status().isOk()) .andReturn(); // Validate IndexingResponse result = mapper.readValue(response.getResponse().getContentAsString(), IndexingResponse.class); MahutaTestAbstract.validateMetadata(builderAndResponse, result); }
Example #5
Source File: ArtifactServiceTest.java From flow-platform-x with Apache License 2.0 | 5 votes |
@Test public void should_get_artifact_with_src_stream() throws IOException { Job job = new Job(); job.setFlowId("1111"); job.setBuildNumber(1L); ByteArrayInputStream content = new ByteArrayInputStream("content".getBytes()); MockMultipartFile file = new MockMultipartFile("file", "test.jar", null, content); Mockito.when(fileManager.save(eq(file.getOriginalFilename()), any(), any())) .thenReturn("artifact/file/path"); Mockito.when(fileManager.read(eq(file.getOriginalFilename()), any())) .thenReturn(content); // when: save artifact artifactService.save(job, "foo/boo", "md5..", file); // then: fetch List<JobArtifact> list = artifactService.list(job); Assert.assertEquals(1, list.size()); JobArtifact fetched = artifactService.fetch(job, list.get(0).getId()); Assert.assertNotNull(fetched); Assert.assertNotNull(fetched.getSrc()); Assert.assertEquals("test.jar", fetched.getFileName()); Assert.assertEquals("artifact/file/path", fetched.getPath()); }
Example #6
Source File: BulkUploadTest.java From Insights with Apache License 2.0 | 5 votes |
@Test(priority = 9, expectedExceptions = InsightsCustomException.class) public void testUploadDataWithNullInsightTimeFieldInDatabase() throws InsightsCustomException, IOException { FileInputStream input = new FileInputStream(fileWithVariedEpochTimes); MultipartFile multipartFile = new MockMultipartFile("file", fileWithVariedEpochTimes.getName(), "text/plain", IOUtils.toByteArray(input)); boolean response = bulkUploadService.uploadDataInDatabase(multipartFile, bulkUploadTestData.toolName, bulkUploadTestData.label, bulkUploadTestData.nullInsightTimeField, bulkUploadTestData.nullInsightTimeFormat); String expectedOutcome = "Insight Time Field not present in the file"; Assert.assertEquals(response, expectedOutcome); Assert.assertFalse(multipartFile.isEmpty()); Assert.assertTrue(multipartFile.getSize() < filesizeMaxValue); }
Example #7
Source File: BulkUploadTest.java From Insights with Apache License 2.0 | 5 votes |
@Test(priority = 3) public void testUploadDataWithVariedEpochTimesInDatabase() throws InsightsCustomException, IOException { FileInputStream input = new FileInputStream(fileWithVariedEpochTimes); MultipartFile multipartFile = new MockMultipartFile("file", fileWithVariedEpochTimes.getName(), "text/plain", IOUtils.toByteArray(input)); boolean response = bulkUploadService.uploadDataInDatabase(multipartFile, bulkUploadTestData.toolName, bulkUploadTestData.label, bulkUploadTestData.insightTimeField, bulkUploadTestData.nullInsightTimeFormat); Assert.assertEquals(response, true); Assert.assertFalse(multipartFile.isEmpty()); Assert.assertTrue(multipartFile.getSize() < filesizeMaxValue); }
Example #8
Source File: AgentControllerTest.java From flow-platform-x with Apache License 2.0 | 5 votes |
@Test public void should_save_log_from_agent() throws Throwable { MockMultipartFile log = new MockMultipartFile("file", "filename.txt", "application/octet-stream", "some xml".getBytes()); mockMvc.perform(MockMvcRequestBuilders.multipart("/agents/logs/upload") .file(log) .header("AGENT-TOKEN", "12345")).andExpect(status().is(200)); }
Example #9
Source File: UploadManagerTest.java From kafka-webview with MIT License | 5 votes |
/** * Tests uploading a Filter file. */ @Test public void testHandleFilterUpload() throws IOException { // Make a temp directory final Path tempDirectory = Files.createTempDirectory(null); // Create a "multi-part" file final String mockContent = "test content"; final MockMultipartFile myFile = new MockMultipartFile( "data", "filename.txt", "text/plain", mockContent.getBytes(StandardCharsets.UTF_8) ); final String outputFilename = "MyUpload.jar"; final String expectedUploadedPath = tempDirectory.toString() + "/filters/" + outputFilename; // Create manager final UploadManager uploadManager = new UploadManager(tempDirectory.toString()); // Handle the "upload" final String result = uploadManager.handleFilterUpload(myFile, outputFilename); // Validate assertEquals("Has expected result filename", expectedUploadedPath, result); // Validate contents final byte[] contentBytes = Files.readAllBytes(new File(result).toPath()); final String contentString = new String(contentBytes, StandardCharsets.UTF_8); assertEquals("Contents are expected", mockContent, contentString); }
Example #10
Source File: UploadEndpointControllerTestIT.java From blackduck-alert with Apache License 2.0 | 5 votes |
public void uploadFile(String targetKey) throws Exception { String url = UploadEndpointManager.UPLOAD_ENDPOINT_URL + "/" + targetKey; MockMultipartFile file = new MockMultipartFile("file", "testfile.txt", "text/plain", "test text".getBytes()); final MockHttpServletRequestBuilder request = MockMvcRequestBuilders.multipart(new URI(url)) .file(file) .with(SecurityMockMvcRequestPostProcessors.user("admin").roles(AlertIntegrationTest.ROLE_ALERT_ADMIN)) .with(SecurityMockMvcRequestPostProcessors.csrf()); mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isCreated()); }
Example #11
Source File: RamlApiImportServiceTest.java From smockin with Apache License 2.0 | 5 votes |
MockMultipartFile buildMockMultiPartFile(final String fileName) throws URISyntaxException, IOException { final URL ramlUrl = this.getClass().getClassLoader().getResource(fileName); final File ramlFile = new File(ramlUrl.toURI()); final FileInputStream ramlInput = new FileInputStream(ramlFile); return new MockMultipartFile(fileName, ramlFile.getName(), "text/plain", IOUtils.toByteArray(ramlInput)); }
Example #12
Source File: BulkUploadTest.java From Insights with Apache License 2.0 | 5 votes |
@Test(priority = 5) public void testUploadDataWithTimeZoneFormatEpochTimesInDatabase() throws InsightsCustomException, IOException { FileInputStream input = new FileInputStream(fileWithTimeZoneFormatEpochTimes); MultipartFile multipartFile = new MockMultipartFile("file", fileWithTimeZoneFormatEpochTimes.getName(), "text/plain", IOUtils.toByteArray(input)); boolean response = bulkUploadService.uploadDataInDatabase(multipartFile, bulkUploadTestData.toolName, bulkUploadTestData.label, bulkUploadTestData.insightTimeField, bulkUploadTestData.insightTimeWithTimeZoneFormat); Assert.assertEquals(response, true); Assert.assertFalse(multipartFile.isEmpty()); Assert.assertTrue(multipartFile.getSize() < filesizeMaxValue); }
Example #13
Source File: ApiImportRouterIntTest.java From smockin with Apache License 2.0 | 5 votes |
private MockMultipartFile buildMockMultipartFile(final String fileName) throws URISyntaxException, IOException { final URL ramlUrl = this.getClass().getClassLoader().getResource(fileName); final File ramlFile = new File(ramlUrl.toURI()); final FileInputStream ramlInput = new FileInputStream(ramlFile); return new MockMultipartFile(fileName, ramlFile.getName(), "text/plain", IOUtils.toByteArray(ramlInput)); }
Example #14
Source File: UserControllerTest.java From imooc-security with Apache License 2.0 | 5 votes |
@Test public void whenUploadSuccess() throws Exception { String result = mockMvc.perform(fileUpload("/file") .file(new MockMultipartFile("file","test.txt","multipart/form-data","hello upload".getBytes("UTF-8")))) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); System.out.println(result); }
Example #15
Source File: BulkUploadTest.java From Insights with Apache License 2.0 | 5 votes |
@Test(priority = 12, expectedExceptions = InsightsCustomException.class) public void testFileFormatException() throws InsightsCustomException, IOException { FileInputStream input = new FileInputStream(fileFormat); MultipartFile multipartFile = new MockMultipartFile("file", fileFormat.getName(), "text/plain", IOUtils.toByteArray(input)); boolean response = bulkUploadService.uploadDataInDatabase(multipartFile, bulkUploadTestData.toolName, bulkUploadTestData.label, bulkUploadTestData.insightTimeField, bulkUploadTestData.nullInsightTimeFormat); }
Example #16
Source File: FileUploadTests.java From spring-guides with Apache License 2.0 | 5 votes |
@Test public void shouldSaveUploadedFile() throws Exception { MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "Spring Framework".getBytes()); this.mvc.perform(fileUpload("/").file(multipartFile)) .andExpect(status().isFound()) .andExpect(header().string("Location", "/")); then(this.storageService).should().store(multipartFile); }
Example #17
Source File: MultipartControllerTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void multipartRequestWithOptionalFileArrayNotPresent() throws Exception { byte[] json = "{\"name\":\"yeeeah\"}".getBytes(StandardCharsets.UTF_8); MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", json); standaloneSetup(new MultipartController()).build() .perform(multipart("/optionalfilearray").file(jsonPart)) .andExpect(status().isFound()) .andExpect(model().attributeDoesNotExist("fileContent")) .andExpect(model().attribute("jsonContent", Collections.singletonMap("name", "yeeeah"))); }
Example #18
Source File: SpringEncoderTests.java From spring-cloud-openfeign with Apache License 2.0 | 5 votes |
@Test(expected = EncodeException.class) public void testMultipartFile1() { Encoder encoder = this.context.getInstance("foo", Encoder.class); assertThat(encoder).isNotNull(); RequestTemplate request = new RequestTemplate(); MultipartFile multipartFile = new MockMultipartFile("test_multipart_file", "hi".getBytes()); encoder.encode(multipartFile, MultipartFile.class, request); }
Example #19
Source File: MessageFormatControllerTest.java From kafka-webview with MIT License | 5 votes |
/** * Test attempting to update an existing message format, but send over a bad Id. * This should be kicked back as an error. */ @Test @Transactional public void testPostUpdate_updatingExistingButWithBadMessageFormatId() throws Exception { final String expectedName = "MyMessageFormat" + System.currentTimeMillis(); final String expectedClassPath = "examples.deserializer.ExampleDeserializer"; final MockMultipartFile jarUpload = new MockMultipartFile("file", "testPlugins.jar", null, "MyContent".getBytes(Charsets.UTF_8)); // Hit page. final MvcResult result = mockMvc .perform(multipart("/configuration/messageFormat/update") .file(jarUpload) .with(user(adminUserDetails)) .with(csrf()) .param("id", "-1000") .param("name", expectedName) .param("classpath", expectedClassPath)) //.andDo(print()) .andExpect(flash().attributeExists("FlashMessage")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/configuration/messageFormat")) .andReturn(); // Grab the flash message final FlashMessage flashMessage = (FlashMessage) result .getFlashMap() .get("FlashMessage"); assertNotNull("Has flash message", flashMessage); assertTrue("Has error message", flashMessage.isWarning()); }
Example #20
Source File: ValidFeignClientTests.java From spring-cloud-openfeign with Apache License 2.0 | 5 votes |
@Test public void testRequestBodyWithMap() { MockMultipartFile file1 = new MockMultipartFile("file1", "hello1.bin", null, "hello".getBytes()); MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null, "hello".getBytes()); Map<String, Object> form = new HashMap<>(); form.put("file1", file1); form.put("file2", file2); form.put("hello", "world"); String response = this.multipartClient.requestBodyMap(form); assertThat(response).contains("file1", "file2", "hello"); }
Example #21
Source File: ValidFeignClientTests.java From spring-cloud-openfeign with Apache License 2.0 | 5 votes |
@Test public void testRequestBodyWithListOfMultipartFiles() { MockMultipartFile file1 = new MockMultipartFile("file1", "hello1.bin", null, "hello".getBytes()); MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null, "hello".getBytes()); String response = this.multipartClient .requestBodyListOfMultipartFiles(Arrays.asList(file1, file2)); assertThat(response).contains("file1", "file2"); }
Example #22
Source File: ValidFeignClientTests.java From spring-cloud-openfeign with Apache License 2.0 | 5 votes |
@Test public void testRequestBodyWithSingleMultipartFile() { String partName = UUID.randomUUID().toString(); MockMultipartFile file1 = new MockMultipartFile(partName, "hello1.bin", null, "hello".getBytes()); String response = this.multipartClient.requestBodySingleMultipartFile(file1); assertThat(response).isEqualTo(partName); }
Example #23
Source File: ValidFeignClientTests.java From spring-cloud-openfeign with Apache License 2.0 | 5 votes |
@Test public void testRequestPartWithListOfPojosAndListOfMultipartFiles() { Hello pojo1 = new Hello(HELLO_WORLD_1); Hello pojo2 = new Hello(OI_TERRA_2); MockMultipartFile file1 = new MockMultipartFile("file1", "hello1.bin", null, "hello".getBytes()); MockMultipartFile file2 = new MockMultipartFile("file2", "hello2.bin", null, "hello".getBytes()); String response = this.multipartClient .requestPartListOfPojosAndListOfMultipartFiles( Arrays.asList(pojo1, pojo2), Arrays.asList(file1, file2)); assertThat(response).isEqualTo("hello world 1oi terra 2hello1.binhello2.bin"); }
Example #24
Source File: ValidFeignClientTests.java From spring-cloud-openfeign with Apache License 2.0 | 5 votes |
@Test public void testRequestPartWithListOfMultipartFiles() { List<MultipartFile> multipartFiles = Arrays.asList( new MockMultipartFile("file1", "hello1.bin", null, "hello".getBytes()), new MockMultipartFile("file2", "hello2.bin", null, "hello".getBytes())); String partNames = this.multipartClient .requestPartListOfMultipartFilesReturnsPartNames(multipartFiles); assertThat(partNames).isEqualTo("files,files"); String fileNames = this.multipartClient .requestPartListOfMultipartFilesReturnsFileNames(multipartFiles); assertThat(fileNames).contains("hello1.bin", "hello2.bin"); }
Example #25
Source File: ValidFeignClientTests.java From spring-cloud-openfeign with Apache License 2.0 | 5 votes |
@Test public void testMultiplePojoRequestParts() { Hello pojo1 = new Hello(HELLO_WORLD_1); Hello pojo2 = new Hello(OI_TERRA_2); MockMultipartFile file = new MockMultipartFile("file", "hello.bin", null, "hello".getBytes()); String response = this.multipartClient.multipartPojo("abc", "123", pojo1, pojo2, file); assertThat(response).isEqualTo("abc123hello world 1oi terra 2hello.bin"); }
Example #26
Source File: BulkUploadTest.java From Insights with Apache License 2.0 | 5 votes |
@Test(priority = 6, expectedExceptions = InsightsCustomException.class) public void testUploadDataWithNullEpochTimesInDatabase() throws InsightsCustomException, IOException { FileInputStream input = new FileInputStream(fileWithNullEpochTime); MultipartFile multipartFile = new MockMultipartFile("file", fileWithNullEpochTime.getName(), "text/plain", IOUtils.toByteArray(input)); boolean response = bulkUploadService.uploadDataInDatabase(multipartFile, bulkUploadTestData.toolName, bulkUploadTestData.label, bulkUploadTestData.insightTimeField, bulkUploadTestData.insightTimeWithTimeZoneFormat); // String expectedOutcome = "Null values in column commitTime"; // Assert.assertEquals(response, expectedOutcome); Assert.assertFalse(multipartFile.isEmpty()); Assert.assertTrue(multipartFile.getSize() < filesizeMaxValue); }
Example #27
Source File: FileUploadTests.java From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
@Test public void shouldSaveUploadedFile() throws Exception { MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", "text/plain", "Spring Framework".getBytes()); this.mvc.perform(fileUpload("/").file(multipartFile)).andExpect(status().isFound()) .andExpect(header().string("Location", "/")); then(this.storageService).should().store(multipartFile); }
Example #28
Source File: BulkUploadTest.java From Insights with Apache License 2.0 | 5 votes |
@Test(priority = 11, expectedExceptions = InsightsCustomException.class) public void testIncorrectFileException() throws InsightsCustomException, IOException { FileInputStream input = new FileInputStream(incorrectDataFile); MultipartFile multipartFile = new MockMultipartFile("file", incorrectDataFile.getName(), "text/plain", IOUtils.toByteArray(input)); boolean response = bulkUploadService.uploadDataInDatabase(multipartFile, bulkUploadTestData.toolName, bulkUploadTestData.label, bulkUploadTestData.insightTimeField, bulkUploadTestData.nullInsightTimeFormat); }
Example #29
Source File: MultipartControllerTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void multipartRequestWithOptionalFileListNotPresent() throws Exception { byte[] json = "{\"name\":\"yeeeah\"}".getBytes(StandardCharsets.UTF_8); MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", json); standaloneSetup(new MultipartController()).build() .perform(multipart("/optionalfilelist").file(jsonPart)) .andExpect(status().isFound()) .andExpect(model().attributeDoesNotExist("fileContent")) .andExpect(model().attribute("jsonContent", Collections.singletonMap("name", "yeeeah"))); }
Example #30
Source File: MessageFormatControllerTest.java From kafka-webview with MIT License | 5 votes |
/** * Test attempting to create a new message format, but don't upload a jar. * This should be kicked back. */ @Test @Transactional public void testPostUpdate_createNewMessageFormatMissingFile() throws Exception { final String expectedName = "MyMessageFormat" + System.currentTimeMillis(); final String expectedClassPath = "examples.deserializer.ExampleDeserializer"; final InputStream fileInputStream = null; final MockMultipartFile jarUpload = new MockMultipartFile("file", "testPlugins.jar", null, fileInputStream); // Hit page. mockMvc .perform(multipart("/configuration/messageFormat/update") .file(jarUpload) .with(user(adminUserDetails)) .with(csrf()) .param("name", expectedName) .param("classpath", expectedClassPath)) //.andDo(print()) .andExpect(model().hasErrors()) .andExpect(model().attributeHasFieldErrors("messageFormatForm", "file")) .andExpect(status().isOk()); // Validate final MessageFormat messageFormat = messageFormatRepository.findByName(expectedName); assertNull("Should NOT have message format", messageFormat); }