Java Examples for org.springframework.mock.web.MockMultipartFile

The following java examples will help you to understand the usage of org.springframework.mock.web.MockMultipartFile. These source code samples are taken from different open source projects.

Example 1
Project: Katari-master  File: EmptyAwareMultipartFileEditorTest.java View source code
public final void testSetValue_notNull() {
    EmptyAwareMultipartFileEditor editor = new EmptyAwareMultipartFileEditor();
    byte[] data = (new String("data")).getBytes();
    MultipartFile multipart;
    multipart = new MockMultipartFile("test", "test", "text/html", data);
    editor.setValue(multipart);
    assertEquals(data, editor.getValue());
}
Example 2
Project: opentides3-master  File: ImageValidatorTest.java View source code
@Test
public void testValidateInvalidFile() {
    MockMultipartFile file = new MockMultipartFile("image1", "image1", "application/doc", "image".getBytes());
    AjaxUpload obj = new AjaxUpload();
    obj.setAttachment(file);
    BindException errors = new BindException(obj, "ajaxUpload");
    imageValidator.validate(obj, errors);
    assertTrue(errors.hasErrors());
    ObjectError error = errors.getFieldError("attachment");
    assertNotNull(error);
}
Example 3
Project: spring-rest-client-master  File: UploadApiTest.java View source code
@Test
public void testTwo2() throws IOException {
    MockMultipartFile file1 = new MockMultipartFile("myimage1.image", "/originial/name1", null, "Hello test one1111".getBytes("UTF-8"));
    MockMultipartFile file2 = new MockMultipartFile("myimage2.image", "/originial/name2", null, "Hello test one22222".getBytes("UTF-8"));
    uploadApi.images2("bingoohuang.txt", Lists.<MultipartFile>newArrayList(file1, file2));
}
Example 4
Project: OpenConext-teams-master  File: InvitationFormValidatorTest.java View source code
@Test
public void testValidateForCSVInput() throws Exception {
    InvitationForm form = new InvitationForm();
    String mails = "test@example.com,test@example.net,john.doe@example.org";
    MultipartFile mockFile = new MockMultipartFile("mockFile", "test.csv", "text/csv", mails.getBytes("utf-8"));
    form.setCsvFile(mockFile);
    Errors errors = new BeanPropertyBindingResult(form, "invitationForm");
    validator.validate(form, errors);
    assertEquals(0, errors.getErrorCount());
}
Example 5
Project: spring-restdocs-master  File: MockMvcRequestConverterTests.java View source code
@Test
public void mockMultipartFileUpload() throws Exception {
    OperationRequest request = createOperationRequest(MockMvcRequestBuilders.fileUpload("/foo").file(new MockMultipartFile("file", new byte[] { 1, 2, 3, 4 })));
    assertThat(request.getUri(), is(URI.create("http://localhost/foo")));
    assertThat(request.getMethod(), is(HttpMethod.POST));
    assertThat(request.getParts().size(), is(1));
    OperationRequestPart part = request.getParts().iterator().next();
    assertThat(part.getName(), is(equalTo("file")));
    assertThat(part.getSubmittedFileName(), is(nullValue()));
    assertThat(part.getHeaders().size(), is(1));
    assertThat(part.getHeaders().getContentLength(), is(4L));
    assertThat(part.getContent(), is(equalTo(new byte[] { 1, 2, 3, 4 })));
}
Example 6
Project: ABRAID-MP-master  File: CovariatesControllerValidatorTest.java View source code
@Test
public void validateCovariateUploadRejectsEmptyFile() throws Exception {
    // Arrange
    CovariatesControllerValidator target = new CovariatesControllerValidator(mock(CovariateService.class), mock(DiseaseService.class));
    MockMultipartFile emptyFile = new MockMultipartFile(" ", new byte[0]);
    // Act
    Collection<String> result = target.validateCovariateUpload("name", "qualifier", null, "subdir", emptyFile, "path");
    // Assert
    assertThat(result).contains("File missing.");
}
Example 7
Project: aranea-master  File: UploadControllerTest.java View source code
@Before
public void setUp() throws Exception {
    mockMultipartFile = new MockMultipartFile("File", "file2.jpg", "img", new byte[] { 1, 2, 3, 4, 5, 66, 7, 7, 8, 9, 77, 8, 9, 0 });
    controller = new ImageUploadController();
    String property = System.getProperty("java.io.tmpdir");
    File tmp = new File(property);
    controller.setTmpFolder(tmp);
    workFolder = new File(tmp, controller.getClass().getSimpleName());
    MockitoAnnotations.initMocks(this);
}
Example 8
Project: openmrs-module-webservices.rest-master  File: ObsController1_9Test.java View source code
@Test
public void shouldUploadFileAndFetchComplexObs() throws Exception {
    ConceptComplex conceptComplex = newConceptComplex();
    InputStream in = getClass().getClassLoader().getResourceAsStream("customTestDataset.xml");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copy(in, out);
    String json = "{\"concept\":\"" + conceptComplex.getUuid() + "\", \"person\":\"5946f880-b197-400b-9caa-a3c661d23041\"," + "\"obsDatetime\":\"2015-09-07T00:00:00.000+0530\"}";
    MockMultipartHttpServletRequest request = newUploadRequest(getURI());
    request.addFile(new MockMultipartFile("file", "customTestDataset.xml", null, out.toByteArray()));
    request.addParameter("json", json);
    SimpleObject response = deserialize(handle(request));
    MockHttpServletResponse rawResponse = handle(newGetRequest(getURI() + "/" + response.get("uuid") + "/value"));
    assertThat(out.toByteArray(), is(equalTo(rawResponse.getContentAsByteArray())));
}
Example 9
Project: spring-batch-admin-master  File: FileControllerTests.java View source code
@Test
public void testUpload() throws Exception {
    MockMultipartFile file = new MockMultipartFile("foo", "foo.properties", "text/plain", "bar".getBytes());
    ExtendedModelMap model = new ExtendedModelMap();
    Date date = new Date();
    controller.upload("spam", file, model, 0, 20, date, new BindException(date, "date"));
    String uploaded = (String) model.get("uploaded");
    // System.err.println(uploaded);
    assertTrue("Wrong filename: " + uploaded, uploaded.matches("spam.foo.*\\.properties$"));
}
Example 10
Project: spring-framework-2.5.x-master  File: MockMultipartHttpServletRequestTests.java View source code
public void testMockMultipartHttpServletRequestWithByteArray() throws IOException {
    MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
    assertFalse(request.getFileNames().hasNext());
    assertNull(request.getFile("file1"));
    assertNull(request.getFile("file2"));
    assertTrue(request.getFileMap().isEmpty());
    request.addFile(new MockMultipartFile("file1", "myContent1".getBytes()));
    request.addFile(new MockMultipartFile("file2", "myOrigFilename", "text/plain", "myContent2".getBytes()));
    doTestMultipartHttpServletRequest(request);
}
Example 11
Project: strongbox-master  File: ArtifactOperationsValidatorTest.java View source code
@Before
public void setUp() throws Exception {
    File baseDir = new File(REPOSITORY_BASEDIR + "/" + REPOSITORY_ID);
    if (!baseDir.exists()) {
        //noinspection ResultOfMethodCallIgnored
        baseDir.mkdirs();
    }
    is = new RandomInputStream(20480000);
    multipartFile = new MockMultipartFile("artifact", "strongbox-validate-8.1.jar", "application/octet-stream", is);
}
Example 12
Project: weplantaforest-master  File: ProjectControllerTest.java View source code
@Test
public void testAddProjectImage() throws Exception {
    User manager = _dbInjecter.injectUser("manager");
    _dbInjecter.injectProject("project 1", manager, "desc", true, 1.0f, 1.0f);
    String userToken = _tokenAuthenticationService.getTokenFromUser(_userRepository.findOne(1L));
    assertThat(_projectImageRepository.findProjectImagesToProjectByProjectId(1L).size()).isEqualTo(0);
    ProjectImageRequest projectImageRequest = new ProjectImageRequest(null, "title", "<mlpr>GERMAN<equ>Beschreibung<sep>ENGLISH<equ>description<sep>ITALIAN<equ>Oak tree<sep>", 1L);
    String projectImageRequestAsJson = TestUtil.getJsonStringFromObject(projectImageRequest);
    mockMvc.perform(MockMvcRequestBuilders.post(Uris.PROJECT_IMAGE_CREATE_EDIT).header("X-AUTH-TOKEN", userToken).contentType(TestUtil.APPLICATION_JSON_UTF8).content(projectImageRequestAsJson)).andExpect(status().isOk());
    assertThat(_projectImageRepository.findProjectImagesToProjectByProjectId(1L).size()).isEqualTo(1);
    FileInputStream fileInputStream = new FileInputStream("src/test/resources/images/" + "test.jpg");
    MockMultipartFile image = new MockMultipartFile("file", fileInputStream);
    MediaType mediaType = new MediaType("multipart", "form-data");
    mockMvc.perform(MockMvcRequestBuilders.fileUpload(Uris.PROJECT_IMAGE_UPLOAD).file(image).header("X-AUTH-TOKEN", userToken).contentType(mediaType).param("imageId", "1")).andExpect(status().isOk());
    assertThat(_projectImageRepository.findProjectImagesToProjectByProjectId(1L).size()).isEqualTo(1);
    TestUtil.deleteFilesInDirectory(new File(FileSystemInjector.getImageFolderForProjects()));
}
Example 13
Project: elmis-master  File: UploadControllerTest.java View source code
@Test
public void shouldThrowErrorIfFileIsEmpty() throws Exception {
    byte[] content = new byte[0];
    MockMultipartFile multiPartMock = new MockMultipartFile("csvFile", "mock.csv", null, content);
    OpenLmisMessage message = new OpenLmisMessage(UploadController.FILE_IS_EMPTY);
    when(messageService.message(message)).thenReturn("File is empty");
    ResponseEntity<OpenLmisResponse> uploadResponse = controller.upload(multiPartMock, "product", request);
    assertThat(uploadResponse.getBody().getErrorMsg(), is("File is empty"));
}
Example 14
Project: gocd-master  File: ArtifactsControllerIntegrationTest.java View source code
@Test
public void shouldSaveChecksumFileInTheCruiseOutputFolder() throws Exception {
    File fooFile = createFile(artifactsRoot, "/tmp/foobar.html");
    FileUtils.writeStringToFile(fooFile, "FooBarBaz...");
    File checksumFile = createFile(artifactsRoot, "/tmp/foobar.html.checksum");
    FileUtils.writeStringToFile(checksumFile, "baz/foobar.html:FooMD5\n");
    MockMultipartFile artifactMultipart = new MockMultipartFile("file", new FileInputStream(fooFile));
    MockMultipartFile checksumMultipart = new MockMultipartFile("file_checksum", new FileInputStream(checksumFile));
    request.addHeader("Confirm", "true");
    StubMultipartHttpServletRequest multipartRequest = new StubMultipartHttpServletRequest(request, artifactMultipart, checksumMultipart);
    postFileWithChecksum("baz/foobar.html", multipartRequest);
    assertThat(file(artifactsRoot, "baz/foobar.html"), exists());
    File uploadedChecksumFile = file(artifactsRoot, "cruise-output/md5.checksum");
    assertThat(uploadedChecksumFile, exists());
    assertThat(FileUtils.readLines(uploadedChecksumFile).get(0).toString(), is("baz/foobar.html:FooMD5"));
}
Example 15
Project: jcommune-master  File: ImageServiceTest.java View source code
@DataProvider
public Object[][] invalidFormatValues() {
    return new Object[][] { { new MockMultipartFile("test_image", "test_image", "image/bmp", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "image/tiff", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "text/plain", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "audio/mpeg", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "audio/x-wav", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "text/plain", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "text/html", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "video/mpeg", new byte[10]) } };
}
Example 16
Project: jTalk-master  File: ImageServiceTest.java View source code
@DataProvider
public Object[][] invalidFormatValues() {
    return new Object[][] { { new MockMultipartFile("test_image", "test_image", "image/bmp", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "image/tiff", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "text/plain", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "audio/mpeg", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "audio/x-wav", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "text/plain", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "text/html", new byte[10]) }, { new MockMultipartFile("test_image", "test_image", "video/mpeg", new byte[10]) } };
}
Example 17
Project: spring-framework-master  File: MultipartControllerTests.java View source code
@Test
public void multipartRequest() throws Exception {
    byte[] fileContent = "bar".getBytes(StandardCharsets.UTF_8);
    MockMultipartFile filePart = new MockMultipartFile("file", "orig", null, fileContent);
    byte[] json = "{\"name\":\"yeeeah\"}".getBytes(StandardCharsets.UTF_8);
    MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", json);
    standaloneSetup(new MultipartController()).build().perform(multipart("/test-multipartfile").file(filePart).file(jsonPart)).andExpect(status().isFound()).andExpect(model().attribute("fileContent", fileContent)).andExpect(model().attribute("jsonContent", Collections.singletonMap("name", "yeeeah")));
}
Example 18
Project: CBIRestAPI-master  File: ImageResourceTest.java View source code
@Test
public void testAddImage() throws Exception {
    // Validate the database is empty (only default storage)
    assertThat(retrievalServer.getSize()).isEqualTo(NUMBER_OF_PICTURES_AT_BEGINNING);
    String storage = DEFAULT_STORAGE;
    Long id = 5l;
    File file = new File(IMAGE_PATHS[(int) (id - 1)]);
    MockMultipartFile firstFile = new MockMultipartFile("file", file.getName(), "image/png", Files.readAllBytes(Paths.get(IMAGE_PATHS[(int) (id - 1)])));
    MockMultipartFile file1 = new MockMultipartFile(file.getName(), Files.readAllBytes(Paths.get(IMAGE_PATHS[(int) (id - 1)])));
    MvcResult result = restStorageMockMvc.perform(fileUpload("/api/images").file(firstFile).param("id", id + "").param("storage", storage).param("keys", "date;test").param("values", "2015;test").param("async", "false")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(id + "")).andExpect(jsonPath("$.test").value("test")).andReturn();
    assertThat(retrievalServer.getStorage(storage).getProperties(id)).isNotNull();
    assertThat(retrievalServer.getStorage(storage).getProperties(id)).containsEntry("id", id + "");
}
Example 19
Project: ngrinder-master  File: FileEntryControllerTest.java View source code
@SuppressWarnings("unchecked")
@Test
public void testUploadFiles() {
    ModelMap model = new ModelMap();
    String path = "test-upload-path";
    scriptController.addFolder(getTestUser(), "", path, model);
    String upFileName = "Uploaded";
    MultipartFile upFile = new MockMultipartFile("Uploaded.py", "Uploaded.py", null, "#test content...".getBytes());
    path = path + "/" + upFileName;
    scriptController.upload(getTestUser(), path, "Uploaded file desc.", upFile, model);
    model.clear();
    scriptController.search(getTestUser(), "Uploaded", model);
    Collection<FileEntry> searchResult = (Collection<FileEntry>) model.get("files");
    assertThat(searchResult.size(), is(1));
}
Example 20
Project: site-master  File: AssetApiControllerTest.java View source code
@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);
}
Example 21
Project: tasq-master  File: ImportExportControllerTest.java View source code
@Test
public void importTasksTest() {
    URL fileURL = getClass().getResource("sampleImport.xls");
    Project project = TestUtils.createProject();
    when(projSrvMock.findByProjectId(PROJECT_ID)).thenReturn(project);
    try {
        mockMultipartFile = new MockMultipartFile("content", fileURL.getFile(), "text/plain", getClass().getResourceAsStream("sampleImport.xls"));
        importExportCtrl.importTasks(mockMultipartFile, PROJECT_ID, modelMock);
        verify(taskSrvMock, times(2)).save(any(Task.class));
        verify(taskSrvMock, times(3)).createSubTask(any(Project.class), any(Task.class), any(Task.class));
    } catch (IOException e) {
        fail(e.getMessage());
    }
}
Example 22
Project: geowebcache-master  File: OperationsRestTest.java View source code
@Test
public void testMultipleFilesUploadReplace() throws Exception {
    // creates some database files for the tests
    Tuple<File, Tuple<String, String>> testFiles = createTestFiles();
    File rootDirectory = testFiles.first;
    try (FileInputStream fileA = new FileInputStream(new File(rootDirectory, testFiles.second.first));
        FileInputStream fileB = new FileInputStream(new File(rootDirectory, testFiles.second.second))) {
        // perform the rest request
        MockMultipartFile fileUploadA = new MockMultipartFile("file", fileA);
        MockMultipartFile fileUploadB = new MockMultipartFile("file", fileB);
        MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        // first request
        mockMvc.perform(MockMvcRequestBuilders.fileUpload("/sqlite/replace").file(fileUploadA).param("layer", "europe").param("destination", testFiles.second.first)).andExpect(status().is(200));
        // second request
        mockMvc.perform(MockMvcRequestBuilders.fileUpload("/sqlite/replace").file(fileUploadB).param("layer", "europe").param("destination", testFiles.second.second)).andExpect(status().is(200));
        // check that files were replaced
        checkThatStoreContainsReplacedTiles(testFiles.second.first, testFiles.second.second);
    }
}
Example 23
Project: liferay-portal-master  File: PortletContainerTestUtil.java View source code
public static LiferayServletRequest getMultipartRequest(String fileNameParameter, byte[] bytes) {
    MockMultipartHttpServletRequest mockMultipartHttpServletRequest = new MockMultipartHttpServletRequest();
    mockMultipartHttpServletRequest.addFile(new MockMultipartFile(fileNameParameter, bytes));
    mockMultipartHttpServletRequest.setContent(bytes);
    mockMultipartHttpServletRequest.setContentType("multipart/form-data;boundary=" + System.currentTimeMillis());
    mockMultipartHttpServletRequest.setCharacterEncoding("UTF-8");
    MockHttpSession mockHttpSession = new MockHttpSession();
    mockHttpSession.setAttribute(ProgressTracker.PERCENT, new Object());
    mockMultipartHttpServletRequest.setSession(mockHttpSession);
    return new LiferayServletRequest(mockMultipartHttpServletRequest);
}
Example 24
Project: Consent2Share-master  File: ClinicalDocumentControllerTest.java View source code
@Test
public void testSecureClinicalDocumentsUploadWhenAllChecksSucced() throws Exception {
    MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());
    doReturn(true).when(xmlValidator).validate(any(InputStream.class));
    doReturn("true").when(sut).scanMultipartFile(file);
    doReturn(false).when(clinicalDocumentService).isDocumentOversized(file);
    doReturn(true).when(clinicalDocumentService).isDocumentExtensionPermitted(file);
    doReturn(true).when(recaptchaUtil).checkAnswer(anyString(), anyString(), anyString());
    mockMvc.perform(fileUpload("/patients/clinicaldocuments.html").file(file).param("name", "mocked_name").param("description", "mocked_description").param("documentType", "mocked_type").param("recaptcha_challenge_field", "recaptcha_challenge_field").param("recaptcha_response_field", "recaptcha_response_field")).andExpect(view().name("redirect:/patients/clinicaldocuments.html"));
}
Example 25
Project: bonita-ui-designer-master  File: WidgetResourceTest.java View source code
@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());
    Widget widget = aWidget().id("my-widget").custom().build();
    Asset expectedAsset = anAsset().withId("assetId").active().withName("myfile.js").withOrder(2).withType(AssetType.JAVASCRIPT).build();
    when(widgetRepository.get("my-widget")).thenReturn(widget);
    when(widgetAssetService.upload(file, widget, "js")).thenReturn(expectedAsset);
    mockMvc.perform(fileUpload("/rest/widgets/my-widget/assets/js").file(file)).andExpect(status().isCreated()).andExpect(jsonPath("$.id").value("assetId")).andExpect(jsonPath("$.name").value("myfile.js")).andExpect(jsonPath("$.type").value("js")).andExpect(jsonPath("$.order").value(2));
    verify(widgetAssetService).upload(file, widget, "js");
}
Example 26
Project: orchidae-master  File: _PictureController.java View source code
@Test
public void pictureUploadCheck() throws Exception {
    // check that there's no picture yet
    getLatest(10).andExpect(content().string("[]"));
    // upload one picture
    UploadResponse response = factory.readEntity(UploadResponse.class, createPicture("test", "jpg").andReturn().getResponse().getContentAsString());
    assertEquals(1, response.getIds().size());
    assertTrue(FileUtil.validateId(response.getIds().get(0)));
    // make sure the picture is there
    getLatest(10).andExpect(jsonPath("$[0].title", is("test"))).andExpect(jsonPath("$[0].originalName", is("test.jpg"))).andExpect(jsonPath("$[0].order", is(1)));
    userUtil._clear();
    // Upload another picture
    response = factory.readEntity(UploadResponse.class, createPicture("b", "png").andReturn().getResponse().getContentAsString());
    assertEquals(1, response.getIds().size());
    assertTrue(FileUtil.validateId(response.getIds().get(0)));
    // verify we have two pictures now
    getLatest(10).andExpect(jsonPath("$[1].title", is("test"))).andExpect(jsonPath("$[1].originalName", is("test.jpg"))).andExpect(jsonPath("$[1].order", is(1))).andExpect(jsonPath("$[0].title", is("b"))).andExpect(jsonPath("$[0].originalName", is("b.png"))).andExpect(jsonPath("$[0].order", is(2)));
    // check that if some IOException happens we get it returned appropriate
    MockMultipartFile file = new MockMultipartFile("b", "b.png", "image/png", "nonsensecontent".getBytes());
    mvc.perform(fileUpload("/picture").file(file).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(containsString("b.png")));
}
Example 27
Project: crowdsource-master  File: ProjectControllerTest.java View source code
@Test
public void addProjectAttachment_shouldDelegateToProjectService() throws Exception {
    final String email = "some@mail.com";
    final UserEntity user = userEntity(email, Roles.ROLE_USER, Roles.ROLE_ADMIN);
    final Attachment expectedAttachment = anExpectedAttachment(aPersistedProjectEntity());
    MockMultipartFile content = mockedMultipart("somecontent", "test_filename", "text/plain");
    MediaType mediaType = mediaType();
    when(projectService.addProjectAttachment(eq("some_id"), eq(Attachment.asCreationCommand("test_filename", "text/plain", content.getInputStream())), eq(user))).thenReturn(expectedAttachment);
    MvcResult mvcRes = mockMvc.perform(fileUpload("/projects/{projectId}/attachments", "some_id").file(content).principal(authentication(user)).contentType(mediaType)).andExpect(status().isOk()).andReturn();
    Attachment res = mapper.readValue(mvcRes.getResponse().getContentAsString(), Attachment.class);
    assertAttachmentsEqual(expectedAttachment, res);
}
Example 28
Project: rest-assured-master  File: MockMvcRequestSenderImpl.java View source code
private MockMvcResponse sendRequest(HttpMethod method, String path, Object[] pathParams) {
    notNull(path, "Path");
    if (requestBody != null && !multiParts.isEmpty()) {
        throw new IllegalStateException("You cannot specify a request body and a multi-part body in the same request. Perhaps you want to change the body to a multi part?");
    }
    String baseUri;
    if (isNotBlank(basePath)) {
        baseUri = mergeAndRemoveDoubleSlash(basePath, path);
    } else {
        baseUri = path;
    }
    final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri);
    if (!queryParams.isEmpty()) {
        new ParamApplier(queryParams) {

            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                uriComponentsBuilder.queryParam(paramName, paramValues);
            }
        }.applyParams();
    }
    String uri = uriComponentsBuilder.build().toUriString();
    final MockHttpServletRequestBuilder request;
    if (multiParts.isEmpty()) {
        request = MockMvcRequestBuilders.request(method, uri, pathParams);
    } else if (method != POST) {
        throw new IllegalArgumentException("Currently multi-part file data uploading only works for " + POST);
    } else {
        request = MockMvcRequestBuilders.fileUpload(uri, pathParams);
    }
    String requestContentType = findContentType();
    if (!params.isEmpty()) {
        new ParamApplier(params) {

            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.param(paramName, paramValues);
            }
        }.applyParams();
        if (StringUtils.isBlank(requestContentType) && method == POST && !isInMultiPartMode(request)) {
            setContentTypeToApplicationFormUrlEncoded(request);
        }
    }
    if (!formParams.isEmpty()) {
        if (method == GET) {
            throw new IllegalArgumentException("Cannot use form parameters in a GET request");
        }
        new ParamApplier(formParams) {

            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.param(paramName, paramValues);
            }
        }.applyParams();
        boolean isInMultiPartMode = isInMultiPartMode(request);
        if (StringUtils.isBlank(requestContentType) && !isInMultiPartMode) {
            setContentTypeToApplicationFormUrlEncoded(request);
        }
    }
    if (!attributes.isEmpty()) {
        new ParamApplier(attributes) {

            @Override
            protected void applyParam(String paramName, String[] paramValues) {
                request.requestAttr(paramName, paramValues[0]);
            }
        }.applyParams();
    }
    if (RestDocsClassPathChecker.isSpringRestDocsInClasspath() && config.getMockMvcConfig().shouldAutomaticallyApplySpringRestDocsMockMvcSupport()) {
        request.requestAttr(ATTRIBUTE_NAME_URL_TEMPLATE, PathSupport.getPath(uri));
    }
    if (StringUtils.isNotBlank(requestContentType)) {
        request.contentType(MediaType.parseMediaType(requestContentType));
    }
    if (headers.exist()) {
        for (Header header : headers) {
            request.header(header.getName(), header.getValue());
        }
    }
    if (cookies.exist()) {
        for (Cookie cookie : cookies) {
            javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());
            if (cookie.hasComment()) {
                servletCookie.setComment(cookie.getComment());
            }
            if (cookie.hasDomain()) {
                servletCookie.setDomain(cookie.getDomain());
            }
            if (cookie.hasMaxAge()) {
                servletCookie.setMaxAge(cookie.getMaxAge());
            }
            if (cookie.hasPath()) {
                servletCookie.setPath(cookie.getPath());
            }
            if (cookie.hasVersion()) {
                servletCookie.setVersion(cookie.getVersion());
            }
            servletCookie.setSecure(cookie.isSecured());
            request.cookie(servletCookie);
        }
    }
    if (!sessionAttributes.isEmpty()) {
        request.sessionAttrs(sessionAttributes);
    }
    if (!multiParts.isEmpty()) {
        MockMultipartHttpServletRequestBuilder multiPartRequest = (MockMultipartHttpServletRequestBuilder) request;
        for (MockMvcMultiPart multiPart : multiParts) {
            MockMultipartFile multipartFile;
            String fileName = multiPart.getFileName();
            String controlName = multiPart.getControlName();
            String mimeType = multiPart.getMimeType();
            if (multiPart.isByteArray()) {
                multipartFile = new MockMultipartFile(controlName, fileName, mimeType, (byte[]) multiPart.getContent());
            } else if (multiPart.isFile() || multiPart.isInputStream()) {
                InputStream inputStream;
                if (multiPart.isFile()) {
                    try {
                        inputStream = new FileInputStream((File) multiPart.getContent());
                    } catch (FileNotFoundException e) {
                        return SafeExceptionRethrower.safeRethrow(e);
                    }
                } else {
                    inputStream = (InputStream) multiPart.getContent();
                }
                try {
                    multipartFile = new MockMultipartFile(controlName, fileName, mimeType, inputStream);
                } catch (IOException e) {
                    return SafeExceptionRethrower.safeRethrow(e);
                }
            } else {
                // String
                multipartFile = new MockMultipartFile(controlName, fileName, mimeType, ((String) multiPart.getContent()).getBytes());
            }
            multiPartRequest.file(multipartFile);
        }
    }
    if (requestBody != null) {
        if (requestBody instanceof byte[]) {
            request.content((byte[]) requestBody);
        } else if (requestBody instanceof File) {
            byte[] bytes = toByteArray((File) requestBody);
            request.content(bytes);
        } else {
            request.content(requestBody.toString());
        }
    }
    logRequestIfApplicable(method, baseUri, path, pathParams);
    return performRequest(request);
}
Example 29
Project: spring-webflow-master  File: MvcViewTests.java View source code
public void testResumeEventModelBinding() throws Exception {
    MockRequestContext context = new MockRequestContext();
    context.putRequestParameter("_eventId", "submit");
    context.putRequestParameter("stringProperty", "foo");
    context.putRequestParameter("integerProperty", "5");
    context.putRequestParameter("dateProperty", "2007-01-01");
    context.putRequestParameter("beanProperty.name", "foo");
    context.putRequestParameter("multipartFile", new MockMultipartFile("foo", new byte[0]));
    context.putRequestParameter("stringArrayProperty", new String[] { "foo", "bar", "baz" });
    context.putRequestParameter("integerArrayProperty", new String[] { "1", "2", "3" });
    context.putRequestParameter("primitiveArrayProperty", new String[] { "1", "2", "3" });
    context.putRequestParameter("listProperty", new String[] { "1", "2", "3" });
    BindBean bindBean = new BindBean();
    StaticExpression modelObject = new StaticExpression(bindBean);
    modelObject.setExpressionString("bindBean");
    context.getCurrentState().getAttributes().put("model", modelObject);
    context.getFlowScope().put("bindBean", bindBean);
    context.getMockExternalContext().setNativeContext(new MockServletContext());
    context.getMockExternalContext().setNativeRequest(new MockHttpServletRequest());
    context.getMockExternalContext().setNativeResponse(new MockHttpServletResponse());
    context.getMockFlowExecutionContext().setKey(new MockFlowExecutionKey("c1v1"));
    org.springframework.web.servlet.View mvcView = new MockView();
    AbstractMvcView view = new MockMvcView(mvcView, context);
    view.setExpressionParser(createExpressionParser());
    view.processUserEvent();
    assertTrue(view.hasFlowEvent());
    assertFalse(context.getFlashScope().contains(ViewActionStateHolder.KEY));
    assertEquals("submit", view.getFlowEvent().getId());
    assertEquals("foo", bindBean.getStringProperty());
    assertEquals(new Integer(5), bindBean.getIntegerProperty());
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(Calendar.YEAR, 2007);
    assertEquals(cal.getTime(), bindBean.getDateProperty());
    assertEquals("foo", bindBean.getBeanProperty().getName());
    assertEquals("foo", bindBean.getMultipartFile().getName());
    assertEquals(3, bindBean.getStringArrayProperty().length);
    assertEquals("foo", bindBean.getStringArrayProperty()[0]);
    assertEquals("bar", bindBean.getStringArrayProperty()[1]);
    assertEquals("baz", bindBean.getStringArrayProperty()[2]);
    assertEquals(3, bindBean.getIntegerArrayProperty().length);
    assertEquals(new Integer(1), bindBean.getIntegerArrayProperty()[0]);
    assertEquals(new Integer(2), bindBean.getIntegerArrayProperty()[1]);
    assertEquals(new Integer(3), bindBean.getIntegerArrayProperty()[2]);
    assertEquals(3, bindBean.getPrimitiveArrayProperty().length);
    assertEquals(1, bindBean.getPrimitiveArrayProperty()[0]);
    assertEquals(2, bindBean.getPrimitiveArrayProperty()[1]);
    assertEquals(3, bindBean.getPrimitiveArrayProperty()[2]);
    assertEquals(3, bindBean.getListProperty().size());
    assertEquals("1", bindBean.getListProperty().get(0));
    assertEquals("2", bindBean.getListProperty().get(1));
    assertEquals("3", bindBean.getListProperty().get(2));
    assertFalse(bindBean.validationMethodInvoked);
}
Example 30
Project: genie-master  File: JobRestControllerIntegrationTests.java View source code
private String submitJob(final int documentationId, final JobRequest jobRequest, final List<MockMultipartFile> attachments) throws Exception {
    final MvcResult result;
    if (attachments != null) {
        final RestDocumentationResultHandler createResultHandler = MockMvcRestDocumentation.document("{class-name}/" + documentationId + "/submitJobWithAttachments/", Preprocessors.preprocessRequest(Preprocessors.prettyPrint()), Preprocessors.preprocessResponse(Preprocessors.prettyPrint()), HeaderDocumentation.requestHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE).description(MediaType.MULTIPART_FORM_DATA_VALUE)), // Request headers
        RequestDocumentation.requestParts(RequestDocumentation.partWithName("request").description("The job request JSON. Content type must be application/json for part"), RequestDocumentation.partWithName("attachment").description("An attachment file. There can be multiple. Type should be octet-stream")), // Response Headers
        Snippets.LOCATION_HEADER);
        final MockMultipartFile json = new MockMultipartFile("request", "", MediaType.APPLICATION_JSON_VALUE, this.objectMapper.writeValueAsBytes(jobRequest));
        final MockMultipartHttpServletRequestBuilder builder = RestDocumentationRequestBuilders.fileUpload(JOBS_API).file(json);
        for (final MockMultipartFile attachment : attachments) {
            builder.file(attachment);
        }
        builder.contentType(MediaType.MULTIPART_FORM_DATA);
        result = this.mvc.perform(builder).andExpect(MockMvcResultMatchers.status().isAccepted()).andExpect(MockMvcResultMatchers.header().string(HttpHeaders.LOCATION, Matchers.notNullValue())).andDo(createResultHandler).andReturn();
    } else {
        // Use regular POST
        final RestDocumentationResultHandler createResultHandler = MockMvcRestDocumentation.document("{class-name}/" + documentationId + "/submitJobWithoutAttachments/", Preprocessors.preprocessRequest(Preprocessors.prettyPrint()), Preprocessors.preprocessResponse(Preprocessors.prettyPrint()), // Request headers
        Snippets.CONTENT_TYPE_HEADER, // Request Fields
        Snippets.getJobRequestRequestPayload(), // Response Headers
        Snippets.LOCATION_HEADER);
        result = this.mvc.perform(MockMvcRequestBuilders.post(JOBS_API).contentType(MediaType.APPLICATION_JSON).content(this.objectMapper.writeValueAsBytes(jobRequest))).andExpect(MockMvcResultMatchers.status().isAccepted()).andExpect(MockMvcResultMatchers.header().string(HttpHeaders.LOCATION, Matchers.notNullValue())).andDo(createResultHandler).andReturn();
    }
    return this.getIdFromLocation(result.getResponse().getHeader(HttpHeaders.LOCATION));
}
Example 31
Project: spring-mvc-showcase-master  File: FileUploadControllerTests.java View source code
@Test
public void readString() throws Exception {
    MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());
    webAppContextSetup(this.wac).build().perform(fileUpload("/fileupload").file(file)).andExpect(model().attribute("message", "File 'orig' uploaded successfully"));
}
Example 32
Project: spring-test-mvc-master  File: MultipartMockHttpServletRequestBuilder.java View source code
/**
     * Create a new MockMultipartFile with the given content.
     *
     * @param name    the name of the file
     * @param content the content of the file
     */
public MultipartMockHttpServletRequestBuilder file(String name, byte[] content) {
    files.add(new MockMultipartFile(name, content));
    return this;
}
Example 33
Project: cloudify-master  File: UploadRepoTest.java View source code
public static MultipartFile createNewMultiFile(final File file) throws IOException {
    byte[] content = FileUtils.readFileToByteArray(file);
    final MockMultipartFile mockMultipartFile = new MockMultipartFile(CloudifyConstants.UPLOAD_FILE_PARAM_NAME, file.getName(), "text/plain", content);
    return mockMultipartFile;
}
Example 34
Project: cross-preferences-master  File: PrefsControllerTest.java View source code
@Test
public void shouldUploadXmlFile() throws Exception {
    final MockMultipartFile file = new MockMultipartFile("file", "prefs.xml", APPLICATION_XML_VALUE, getSystemResourceAsStream("sys.xml"));
    mvc.perform(fileUpload("/").file(file)).andExpect(status().is(303)).andExpect(header().string("Location", "/"));
}
Example 35
Project: odroid-master  File: ApplicationControllerTest.java View source code
private MultipartFile mockMapPriceFile(String name, byte[] content) {
    return new MockMultipartFile(name, content);
}
Example 36
Project: radiology-master  File: RadiologyDashboardReportTemplatesTabControllerTest.java View source code
@Before
public void setUp() throws IOException {
    inputStream = IOUtils.toInputStream(MOCK_TEMPLATE_CONTENT);
    multipartFile = new MockMultipartFile("mrrtReportTemplate", "mrrtReportTemplate.html", "html", inputStream);
    request = new MockHttpServletRequest();
}