List of usage examples for org.springframework.mock.web MockMultipartFile MockMultipartFile
public MockMultipartFile(String name, InputStream contentStream) throws IOException
From source file:com.silverpeas.util.web.servlet.FileUploadUtilTest.java
@Test public void testGetFile() throws Exception { MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); request.setMethod("POST"); request.setContentType(FileUploadBase.MULTIPART_FORM_DATA); request.addParameter("champ1", "valeur1"); byte[] content = IOUtils .toByteArray(this.getClass().getClassLoader().getResourceAsStream("FrenchScrum.odp")); assertNotNull(content);//from www. jav a 2s .co m request.addFile(new MockMultipartFile("FrenchScrum.odp", content)); assertNotNull(content); }
From source file:ch.silviowangler.dox.web.ImportControllerTest.java
@Test public void importDocumentDuplicateDocument() throws DocumentClassNotFoundException, DocumentDuplicationException, ValidationException { when(request.getParameterNames()).thenReturn(Lists.asList("a", new String[] { "b", "c" }).iterator()); when(request.getParameter("a")).thenReturn("A"); when(request.getParameter("b")).thenReturn("B"); when(request.getParameter("c")).thenReturn("C"); when(documentService.importDocument(any(PhysicalDocument.class))) .thenThrow(new DocumentDuplicationException(1L, "hash")); ResponseEntity responseEntity = controller.importDocument( new MockMultipartFile("test.pdf", "this is just a test".getBytes()), request, "Client"); assertThat(responseEntity.getStatusCode(), is(CONFLICT)); verify(documentService).importDocument(any(PhysicalDocument.class)); }
From source file:org.openlmis.fulfillment.service.TemplateServiceTest.java
@Test public void shouldThrowErrorIfFileNotOfTypeJasperXml() throws Exception { expectedException.expect(ReportingException.class); expectedException.expectMessage(REPORTING_FILE_INCORRECT_TYPE); MockMultipartFile file = new MockMultipartFile("report.pdf", new byte[1]); templateService.validateFileAndInsertTemplate(new Template(), file); }
From source file:com.carlos.projects.billing.ExcelToMySQLImporterTest.java
@Test public void shouldImportNComponentsAndNFamiliesFromFileWithNComponentsAndNFamiliesWithFamilyCodeValueAndSomeOtherComponentsAndFamiliesWithNoFamilyCodeValue() throws Exception { //given/* ww w. ja v a 2s . c om*/ ExcelToMySQLImporter importer = new ExcelToMySQLImporter(familyDAO, componentDAO); MultipartFile file = new MockMultipartFile("dataWithMissingFamilyCodes.xlsx", getClass().getResourceAsStream("/dataWithMissingFamilyCodes.xlsx")); Family family = createFamily("36", "CONTADORES"); Component component = createComponent("KITAZUL162212", "KIT AZUL BATERIA 16-2-21/2 BAHISA", 33.0, 0.0, 383.2065, family); //when Long importedComponents = importer.importData(file); //then assertThat("The number of components imported is not 1", importedComponents, is(1L)); InOrder inOrder = inOrder(familyDAO, componentDAO); inOrder.verify(familyDAO).getById(Family.class, family.getCode()); inOrder.verify(componentDAO).getById(Component.class, component.getCode()); inOrder.verify(familyDAO).save(family); verifyNoMoreInteractions(familyDAO, componentDAO); }
From source file:edu.purdue.cybercenter.dm.web.GlobusControllerTest.java
@Test @Ignore//ww w.jav a 2 s. com public void shouldBeAbleToRunWorkflowWithGlobusTransfer() throws Exception { useTestWorkspace("brouder_sylvie"); login("george.washington", "1234"); /* * upload the test workflow */ MockMultipartFile mockMultipartFile = new MockMultipartFile(WORKFLOW_ZIP_FILE, new FileInputStream(WORKFLOW_FILES_DIR + WORKFLOW_ZIP_FILE)); MockMultipartHttpServletRequestBuilder mockMultipartHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload( "/workflows/import").accept(MediaType.ALL).session(httpSession); mockMultipartHttpServletRequestBuilder.file(mockMultipartFile); ResultActions resultActions = mockMvc.perform(mockMultipartHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); String content = extractTextarea(resultActions.andReturn().getResponse().getContentAsString()); Map<String, Object> workflow = Helper.deserialize(content, Map.class); assertNotNull("workflow is null", workflow); Integer workflowId = (Integer) workflow.get("id"); /* * create a project and an experiment to associate the job for the workflow with * while doing that, make sure we save all the IDs associated to post it with the job */ MockHttpServletRequestBuilder mockHttpServletRequestBuilder = post("/projects") .content("{\"description\":\"This is a project\",\"name\":\"Project 1\"}") .accept(MediaType.APPLICATION_JSON).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); content = resultActions.andReturn().getResponse().getContentAsString(); Map<String, Object> map = Helper.deserialize(content, Map.class); Integer projectId = (Integer) map.get("id"); mockHttpServletRequestBuilder = post("/experiments") .content("{\"projectId\":{\"$ref\":\"/projects/" + projectId + "\"},\"name\":\"Experiment 1\",\"description\":\"This is an experiment\"}") .accept(MediaType.APPLICATION_JSON).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isCreated()); content = resultActions.andReturn().getResponse().getContentAsString(); map = Helper.deserialize(content, Map.class); Integer experimentId = (Integer) map.get("id"); /* * create a job associated with the project, experiment and workflow we just created */ mockHttpServletRequestBuilder = post("/jobs").param("projectId", projectId.toString()) .param("experimentId", experimentId.toString()).param("workflowId", workflowId.toString()) .param("name", "Just a job").accept(MediaType.TEXT_HTML).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); /* * forwarded to job/submit/jobId */ String forwardedUrl = resultActions.andReturn().getResponse().getForwardedUrl(); mockHttpServletRequestBuilder = post(forwardedUrl).accept(MediaType.TEXT_HTML_VALUE).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); /* * redirected to jobs/task/jobId */ String redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); mockHttpServletRequestBuilder = get(redirectedUrl).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); /* * we're at UT1 in the workflow */ String jobId = redirectedUrl.substring(redirectedUrl.lastIndexOf('/') + 1); TaskEntity task = (TaskEntity) resultActions.andReturn().getModelAndView().getModel().get("task"); String taskId = task.getId(); String templateId = "305b0f27-e829-424e-84eb-7a8a9ed93e28"; String templateVersion = "db719406-f665-45cb-a8fb-985b6082b654"; // For buttton 1 UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("multiple", false); System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize"); uriBuilder.queryParam("response_type", "code"); //uriBuilder.queryParam("redirect_uri", "code"); uriBuilder.queryParam("client_id", username); URL url = new URL(uriBuilder.build(true).toUriString()); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); String userpass = username + ":" + password; String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); String res = IOUtils.toString(connection.getInputStream()); Map<String, Object> responseMap = Helper.deserialize(res, Map.class); String code = (String) responseMap.get("code"); uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback"); uriBuilder.queryParam("jobId", Integer.parseInt(jobId)); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("multiple", false); String uri = uriBuilder.build(true).toUriString() + "&code=" + code; mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); // For Button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("multiple", true); System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); uriBuilder = UriComponentsBuilder.fromUriString("https://www.globus.org/service/graph/goauth/authorize"); uriBuilder.queryParam("response_type", "code"); uriBuilder.queryParam("client_id", username); url = new URL(uriBuilder.build(true).toUriString()); connection = (HttpsURLConnection) url.openConnection(); userpass = username + ":" + password; basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes())); connection.setRequestProperty("Authorization", basicAuth); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); res = IOUtils.toString(connection.getInputStream()); responseMap = Helper.deserialize(res, Map.class); code = (String) responseMap.get("code"); // For button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/loginCallback"); uriBuilder.queryParam("jobId", Integer.parseInt(jobId)); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("multiple", true); uri = uriBuilder.build(true).toUriString() + "&code=" + code; mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); // Getting accessToken only from one button String accessToken = ""; String[] urlParts = redirectedUrl.split("&"); for (String urlPart : urlParts) { if (urlPart.contains("accessToken")) { String[] accessTokenPair = urlPart.split("="); accessToken = accessTokenPair[1]; break; } } //Button 1 uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile1"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); //Button 2 uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam(URLEncoder.encode("file[0]", "UTF-8"), FILE_TO_UPLOAD_1); uriBuilder.queryParam(URLEncoder.encode("file[1]", "UTF-8"), FILE_TO_UPLOAD_2); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile2"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/remote_endpoint/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); //For getting Storage Files (an abstract button called browsefile3) uriBuilder = UriComponentsBuilder.fromUriString("/globus/browseFile"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile3"); uriBuilder.queryParam("multiple", true); uriBuilder.queryParam("storageFile", "StorageFile:1");// This file has to be present in the storage file record and in memory System.out.println(uriBuilder.build(true).toUriString()); mockHttpServletRequestBuilder = get(uriBuilder.build(true).toUriString()).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); redirectedUrl = resultActions.andReturn().getResponse().getContentAsString(); System.out.println("Redirected to: " + redirectedUrl); //FileSelect uriBuilder = UriComponentsBuilder.fromUriString("/globus/fileSelectCallback"); uriBuilder.queryParam("fileId", 1); uriBuilder.queryParam(URLEncoder.encode("folder[0]", "UTF-8"), "remote_endpoint/"); uriBuilder.queryParam("jobId", jobId); uriBuilder.queryParam("alias", templateId + ".browsefile3"); uriBuilder.queryParam("accessToken", accessToken);//URLEncoder.encode(accessToken,"UTF-8") uriBuilder.queryParam("path", URLEncoder.encode("/~/", "UTF-8")); uri = uriBuilder.build(true).toUriString(); uri = URLDecoder.decode(uri, "UTF-8"); uri = uri + "&endpoint=" + URLEncoder.encode(endpoint, "UTF-8"); mockHttpServletRequestBuilder = get(uri).session(httpSession); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); String multipartBoundary = "------WebKitFormBoundary3xeGH8uP6GWtBfd1"; MultiPartFileContentBuilder multiPartFileContentBuilder = new MultiPartFileContentBuilder( multipartBoundary); multiPartFileContentBuilder.addField("autoGenerated", "true"); multiPartFileContentBuilder.addField("jobId", jobId); multiPartFileContentBuilder.addField("taskId", taskId); multiPartFileContentBuilder.addField("jsonToServer", "{}"); multiPartFileContentBuilder.addField("isIframe", "true"); multiPartFileContentBuilder.addField("experimentId", ""); multiPartFileContentBuilder.addField("projectId", ""); multiPartFileContentBuilder .addField(templateId + ".name({%22_template_version:%22" + templateVersion + "%22})", ""); multiPartFileContentBuilder .addField(templateId + ".browsefile1({%22_template_version:%22" + templateVersion + "%22})", ""); multiPartFileContentBuilder .addField(templateId + ".browsefile2({%22_template_version:%22" + templateVersion + "%22})", ""); String taskContent = multiPartFileContentBuilder.build(); // /rest/objectus post call mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/rest/objectus/") .param("jobId", jobId).param("taskId", taskId).param(templateId + ".name", "") .param(templateId + ".browsefile1", "").param(templateId + ".browsefile2", "") .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession); mockHttpServletRequestBuilder.content(taskContent); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().isOk()); multipartBoundary = "------WebKitFormBoundarybiQtLhfKnPwaMgsR"; multiPartFileContentBuilder = new MultiPartFileContentBuilder(multipartBoundary); multiPartFileContentBuilder.addField("jobId", jobId); multiPartFileContentBuilder.addField("taskId", taskId); multiPartFileContentBuilder.addField("jsonToServer", "{}"); taskContent = multiPartFileContentBuilder.build(); // /jobs/task post call mockHttpServletRequestBuilder = (MockMultipartHttpServletRequestBuilder) fileUpload("/jobs/task") .param("jobId", jobId).param("taskId", taskId).param("ignoreFormData", "true") .param("jsonToServer", "{}").accept(MediaType.ALL).session(httpSession); mockHttpServletRequestBuilder.content(taskContent); resultActions = mockMvc.perform(mockHttpServletRequestBuilder); resultActions.andExpect(status().is3xxRedirection()); redirectedUrl = resultActions.andReturn().getResponse().getRedirectedUrl(); System.out.println("Redirected to: " + redirectedUrl); deleteDatasetEntries(templateId); }
From source file:ch.silviowangler.dox.web.ImportControllerTest.java
@Test public void importDocumentValidationException() throws DocumentClassNotFoundException, DocumentDuplicationException, ValidationException { when(request.getParameterNames()).thenReturn(Lists.asList("a", new String[] { "b", "c" }).iterator()); when(request.getParameter("a")).thenReturn("A"); when(request.getParameter("b")).thenReturn("B"); when(request.getParameter("c")).thenReturn("C"); when(documentService.importDocument(any(PhysicalDocument.class))).thenThrow(new ValidationException("bla")); ResponseEntity responseEntity = controller.importDocument( new MockMultipartFile("test.pdf", "this is just a test".getBytes()), request, "Client"); assertThat(responseEntity.getStatusCode(), is(CONFLICT)); verify(documentService).importDocument(any(PhysicalDocument.class)); }
From source file:business.UploadTests.java
@Test(groups = "upload", dependsOnMethods = "createRequest") public void uploadFileNoMimetype() throws IOException { UserAuthenticationToken requester = getRequester(); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(requester); RequestRepresentation representation = requestController.getRequestById(requester, processInstanceId); log.info("Status: " + representation.getStatus()); int attachmentCount = representation.getAttachments().size(); ClassLoader classLoader = getClass().getClassLoader(); URL resource = classLoader.getResource("test/Utrecht_Oude_Gracht_Hamburgerbrug_(LOC).jpg"); InputStream input = resource.openStream(); MultipartFile file = new MockMultipartFile(resource.getFile(), input); //MultipartFile file = new MockMultipartFile(resource.getFile(), resource.getFile().toString(), "undefined", input); Integer flowTotalChunks = 1;/* w ww . ja v a 2s . com*/ Integer flowChunkNumber = 1; String flowIdentifier = "flow"; representation = requestController.uploadRequestAttachment(requester, processInstanceId, resource.getFile(), flowTotalChunks, flowChunkNumber, flowIdentifier, file); assertEquals(attachmentCount + 1, representation.getAttachments().size()); printFiles(representation.getAttachments()); SecurityContextHolder.clearContext(); }
From source file:com.carlos.projects.billing.ExcelToMySQLImporterTest.java
@Test public void shouldNotImportComponentsWithTheSameCodeTwice() throws Exception { //given//w w w .j a v a2 s . c om ExcelToMySQLImporter importer = new ExcelToMySQLImporter(familyDAO, componentDAO); MultipartFile file = new MockMultipartFile("dataWithDuplicatedComponentCodes.xlsx", getClass().getResourceAsStream("/dataWithDuplicatedComponentCodes.xlsx")); Family family1 = createFamily("36", "CONTADORES"); Component component = createComponent("KITAZUL162212", "KIT AZUL BATERIA 16-2-21/2 BAHISA", 33.0, 0.0, 383.2065, family1); Family family2 = createFamily("33", "ACCES. FONTANERIA"); family2.setComponents(new HashSet<Component>()); when(componentDAO.getById((Class<Component>) anyObject(), anyString())).thenReturn(null, component); //when Long importedComponents = importer.importData(file); //then assertThat("The number of components imported is not 1", importedComponents, is(1L)); InOrder inOrder = inOrder(familyDAO, componentDAO); inOrder.verify(familyDAO).getById(Family.class, family1.getCode()); inOrder.verify(componentDAO).getById(Component.class, component.getCode()); inOrder.verify(familyDAO).save(family1); inOrder.verify(familyDAO).getById(Family.class, family2.getCode()); inOrder.verify(componentDAO).getById(Component.class, component.getCode()); inOrder.verify(familyDAO).save(family2); verifyNoMoreInteractions(familyDAO, componentDAO); }
From source file:com.trenako.web.controllers.admin.AdminOptionsControllerTests.java
OptionForm postedForm() { OptionForm form = new OptionForm(); form.setOption(new Option("name", "dcc-interface", null)); form.setFile(new MockMultipartFile("file.png", "content".getBytes())); return form;/*from w w w. ja v a 2s .c o m*/ }
From source file:com.carlos.projects.billing.ExcelToMySQLImporterTest.java
@Test public void shouldNotImportFamiliesWithTheSameCodeTwice() throws Exception { //given//from ww w .ja v a 2 s .co m ExcelToMySQLImporter importer = new ExcelToMySQLImporter(familyDAO, componentDAO); MultipartFile file = new MockMultipartFile("dataWithDuplicatedFamilyCodes.xlsx", getClass().getResourceAsStream("/dataWithDuplicatedFamilyCodes.xlsx")); Family family = createFamily("36", "CONTADORES"); Component component1 = createComponent("KITAZUL162212", "KIT AZUL BATERIA 16-2-21/2 BAHISA", 33.0, 0.0, 383.2065, family); Component component2 = createComponent("000636", "LATIGUILLO FLEX.RIVER MH 2 300", 40.0, 0.0, 38.274, family); when(familyDAO.getById(Family.class, family.getCode())).thenReturn(null, family); //when Long importedComponents = importer.importData(file); //then assertThat("The number of components imported is not 2", importedComponents, is(2L)); InOrder inOrder = inOrder(familyDAO, componentDAO); inOrder.verify(familyDAO).getById(Family.class, family.getCode()); inOrder.verify(componentDAO).getById(Component.class, component1.getCode()); inOrder.verify(familyDAO).save(family); inOrder.verify(familyDAO).getById(Family.class, family.getCode()); inOrder.verify(componentDAO).getById(Component.class, component2.getCode()); inOrder.verify(componentDAO).save(component2); verifyNoMoreInteractions(familyDAO, componentDAO); }