List of usage examples for org.springframework.mock.web MockMultipartFile MockMultipartFile
public MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream) throws IOException
From source file:org.jtalks.jcommune.service.nontransactional.ImageServiceTest.java
@DataProvider public Object[][] validFormatValues() { Set<String> validFormats = new HashSet<String>(); validFormats.add("image/jpeg"); validFormats.add("image/png"); validFormats.add("image/gif"); List<MultipartFile> files = new ArrayList<MultipartFile>(validFormats.size()); for (String contentType : validFormats) { files.add(new MockMultipartFile("test_image", "test_image", contentType, new byte[10])); }//from w w w .ja v a 2s . com Object[][] result = new Object[files.size()][]; for (int i = 0; i < result.length; i++) { result[i] = new Object[] { files.get(i) }; } return result; }
From source file:org.kuali.mobility.shared.controllers.FileControllerTest.java
@Test public void testHandleFormUpload() { MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); String viewName;/*w ww.ja v a 2 s . co m*/ try { InputStream in = this.getClass().getClassLoader().getResourceAsStream(FILE_NAME); MockMultipartFile mockFile = new MockMultipartFile(FORM_FILE_NAME, FILE_NAME, CONTENT_TYPE, in); request.addFile(mockFile); File file = new File(mockFile); when(getFileService().saveFile(file)).thenReturn(Long.valueOf(42)); viewName = getController().handleFormUpload(request); } catch (IOException ioe) { LOG.error(ioe.getLocalizedMessage(), ioe); viewName = null; } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); viewName = null; } assertTrue("Failed to handle form upload.", viewName.contains(FILE_NAME)); }
From source file:org.kuali.mobility.shared.controllers.FileControllerTest.java
@Test public void testGetFile() { String viewName;//from w w w .ja va2 s . c om MockHttpServletRequest request = new MockHttpServletRequest(servletContext); MockHttpServletResponse response = new MockHttpServletResponse(); try { InputStream in = this.getClass().getClassLoader().getResourceAsStream(FILE_NAME); MockMultipartFile mockFile = new MockMultipartFile(FORM_FILE_NAME, FILE_NAME, CONTENT_TYPE, in); File file = new File(mockFile); when(getFileService().findFileById(file.getId())).thenReturn(file); getController().getFile(file.getId(), request, response); assertTrue("Content type of response is not text/plain.", CONTENT_TYPE.equals(response.getContentType())); assertTrue("Response content length does not match file length.", file.getFileSize() == response.getContentLength()); String responseText = IOUtils.toString(response.getContentAsByteArray(), CONTENT_ENCODING); String fileContent = IOUtils.toString(file.getBytes(), CONTENT_ENCODING); assertTrue("Response content does not match file content.", fileContent.equals(responseText)); } catch (IOException ioe) { LOG.error(ioe.getLocalizedMessage(), ioe); fail("Could not get file because of an IOException."); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); fail("Could not get file because of an Exception."); } }
From source file:org.kuali.mobility.shared.controllers.FileControllerTest.java
@Test public void testGetFileThrowIOException() { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); HttpServletResponse response = mock(HttpServletResponse.class); try {/*from ww w . j a v a2 s. c o m*/ InputStream in = this.getClass().getClassLoader().getResourceAsStream(FILE_NAME); MockMultipartFile mockFile = new MockMultipartFile(FORM_FILE_NAME, FILE_NAME, CONTENT_TYPE, in); File file = new File(mockFile); when(getFileService().findFileById(file.getId())).thenReturn(file); when(response.getOutputStream()).thenThrow(new IOException()); getController().getFile(file.getId(), request, response); } catch (IOException ioe) { LOG.error(ioe.getLocalizedMessage(), ioe); fail("Could not get file because of an IOException."); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); fail("Could not get file because of an Exception."); } }
From source file:org.openmrs.module.radiology.legacyui.report.template.web.RadiologyDashboardReportTemplatesTabControllerTest.java
@Before public void setUp() throws IOException { inputStream = IOUtils.toInputStream(MOCK_TEMPLATE_CONTENT); multipartFile = new MockMultipartFile("mrrtReportTemplate", "mrrtReportTemplate.html", "html", inputStream); request = new MockHttpServletRequest(); }
From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_9.ClobDatatypeStorageControllerTest.java
@Test public void shouldAcceptAndStoreClobDataViaPost() throws Exception { long before = getAllCount(); byte[] fileData = IOUtils.toByteArray( getClass().getClassLoader().getResourceAsStream(RestTestConstants1_9.TEST_RESOURCE_FILE)); MockMultipartFile toUpload = new MockMultipartFile("file", "formresource.txt", "text/plain", fileData); MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); request.setRequestURI(getBaseRestURI() + getURI()); request.setMethod(RequestMethod.POST.name()); request.addHeader("Content-Type", "multipart/form-data"); request.addFile(toUpload);/*from w w w.j a v a 2s.com*/ MockHttpServletResponse response = handle(request); Assert.assertEquals(HttpServletResponse.SC_CREATED, response.getStatus()); Assert.assertEquals(before + 1, getAllCount()); }
From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_9.FormResourceController1_9Test.java
@Test public void shouldPostFormResourceValue() throws Exception { byte[] fileData = IOUtils.toByteArray( getClass().getClassLoader().getResourceAsStream(RestTestConstants1_9.TEST_RESOURCE_FILE)); String valueReferenceBefore = formService.getFormResourceByUuid(getUuid()).getValueReference(); MockMultipartFile toUpload = new MockMultipartFile("value", "formresource.txt", "text/plain", fileData); MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); //Posting to uri of the form /ws/rest/v1/form/{uuid}/resource/{uuid}/value String uri = getBaseRestURI() + getURI() + "/" + getUuid() + "/value"; request.setRequestURI(uri);// w w w . j a v a 2s. c o m request.setMethod(RequestMethod.POST.name()); request.addHeader("Content-Type", "multipart/form-data"); request.addFile(toUpload); MockHttpServletResponse response = handle(request); String valueReferenceAfter = formService.getFormResourceByUuid(getUuid()).getValueReference(); Assert.assertNotEquals(valueReferenceBefore, valueReferenceAfter); Assert.assertNotNull(datatypeService.getClobDatatypeStorageByUuid(valueReferenceAfter)); Assert.assertEquals(HttpServletResponse.SC_CREATED, response.getStatus()); }
From source file:org.owasp.dependencytrack.dao.LibraryVersionDaoTest.java
private MultipartFile readLicense(File file) throws IOException { FileInputStream input = new FileInputStream(file); return new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input)); }
From source file:org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilterTests.java
public void contentLengthTest(Long expectedContentLength, SimpleHostRoutingFilter filter, MockMultipartHttpServletRequest request) throws IOException { byte[] data = "poprqwueproqiwuerpoqweiurpo".getBytes(); MockMultipartFile file = new MockMultipartFile("test.zip", "test.zip", "application/zip", data); String boundary = "q1w2e3r4t5y6u7i8o9"; request.setContentType("multipart/form-data; boundary=" + boundary); request.setContent(createFileContent(data, boundary, "application/zip", "test.zip")); request.addFile(file);//from w ww .j av a 2 s . co m request.setMethod("POST"); request.setParameter("variant", "php"); request.setParameter("os", "mac"); request.setParameter("version", "3.4"); request.setRequestURI("/app/echo"); MockHttpServletResponse response = new MockHttpServletResponse(); RequestContext.getCurrentContext().setRequest(request); RequestContext.getCurrentContext().setResponse(new MockHttpServletResponse()); URL url = new URL("http://localhost:" + this.port); RequestContext.getCurrentContext().set("routeHost", url); filter.run(); String responseString = IOUtils.toString( new GZIPInputStream(((CloseableHttpResponse) RequestContext.getCurrentContext().get("zuulResponse")) .getEntity().getContent())); assertTrue(!responseString.isEmpty()); if (expectedContentLength < 0) { assertThat(responseString, containsString("\"" + HttpHeaders.TRANSFER_ENCODING.toLowerCase() + "\":\"chunked\"")); assertThat(responseString, not(containsString(HttpHeaders.CONTENT_LENGTH.toLowerCase()))); } else { assertThat(responseString, containsString( "\"" + HttpHeaders.CONTENT_LENGTH.toLowerCase() + "\":\"" + expectedContentLength + "\"")); } }
From source file:us.fatehi.schemacrawler.webapp.SchemaCrawlerControllerHappyPathTest.java
@Test public void happyPath() throws Exception { final InputStreamSource testDbStreamSource = new ClassPathResource("/test.db"); final MockMultipartFile multipartFile = new MockMultipartFile("file", "test.db", "application/octet-stream", testDbStreamSource.getInputStream()); final MvcResult result1 = mvc .perform(fileUpload("/schemacrawler").file(multipartFile).param("name", "Sualeh").param("email", "sualeh@hotmail.com")) .andExpect(view().name("SchemaCrawlerDiagramResult")).andExpect(status().is2xxSuccessful()) .andReturn();//from www . j a v a 2s. co m final SchemaCrawlerDiagramRequest diagramRequest = (SchemaCrawlerDiagramRequest) result1.getModelAndView() .getModel().get("diagramRequest"); final String key = diagramRequest.getKey(); final Optional<Path> sqlitePathOptional = storageService.resolve(key, FileExtensionType.SQLITE_DB); assertThat(sqlitePathOptional.isPresent(), is(equalTo(true))); final Optional<Path> pngPathOptional = storageService.resolve(key, FileExtensionType.PNG); assertThat(pngPathOptional.isPresent(), is(equalTo(true))); final Optional<Path> jsonPathOptional = storageService.resolve(key, FileExtensionType.JSON); assertThat(jsonPathOptional.isPresent(), is(equalTo(true))); final SchemaCrawlerDiagramRequest schemaCrawlerDiagramRequestFromJson = SchemaCrawlerDiagramRequest .fromJson(IOUtils.toString(new FileReader(jsonPathOptional.get().toFile()))); assertThat(diagramRequest, is(equalTo(schemaCrawlerDiagramRequestFromJson))); final MvcResult result2 = mvc.perform(get("/schemacrawler/" + key)) .andExpect(view().name("SchemaCrawlerDiagram")).andExpect(status().is2xxSuccessful()).andReturn(); assertThat(result2.getResponse().getContentAsString(), containsString("/schemacrawler/images/" + key)); final MvcResult result3 = mvc.perform(get("/schemacrawler/images/" + key).accept(MediaType.IMAGE_PNG)) .andExpect(status().isOk()).andReturn(); final int contentLength = result3.getResponse().getContentLength(); assertThat(contentLength, is(greaterThan(0))); // assertThat(contentLength, is(greaterThan(14_500))); // assertThat(contentLength, is(lessThan(15_500))); }