Search in sources :

Example 1 with MockMultipartHttpServletRequestBuilder

use of org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder in project rest-assured by rest-assured.

the class MockMvcRequestSenderImpl method sendRequest.

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);
}
Also used : MockMultipartFile(org.springframework.mock.web.MockMultipartFile) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) MockMultipartHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) io.restassured.http(io.restassured.http) MockMultipartFile(org.springframework.mock.web.MockMultipartFile)

Example 2 with MockMultipartHttpServletRequestBuilder

use of org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder in project spring-security by spring-projects.

the class RequestCacheConfigurerTests method postWhenRequestIsMultipartThenPostAuthenticationRedirectsToRoot.

// SEC-7060
@Test
public void postWhenRequestIsMultipartThenPostAuthenticationRedirectsToRoot() throws Exception {
    this.spring.register(RequestCacheDefaultsConfig.class, DefaultSecurityConfig.class).autowire();
    MockMultipartFile aFile = new MockMultipartFile("aFile", "A_FILE".getBytes());
    MockMultipartHttpServletRequestBuilder request = multipart("/upload").file(aFile);
    // @formatter:off
    MockHttpSession session = (MockHttpSession) this.mvc.perform(request).andReturn().getRequest().getSession();
    // @formatter:on
    this.mvc.perform(formLogin(session)).andExpect(redirectedUrl("/"));
}
Also used : MockMultipartFile(org.springframework.mock.web.MockMultipartFile) MockMultipartHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder) MockHttpSession(org.springframework.mock.web.MockHttpSession) Test(org.junit.jupiter.api.Test)

Example 3 with MockMultipartHttpServletRequestBuilder

use of org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder in project spring-framework by spring-projects.

the class MockMvcHttpConnector method initRequestBuilder.

private MockHttpServletRequestBuilder initRequestBuilder(HttpMethod httpMethod, URI uri, MockClientHttpRequest httpRequest, @Nullable byte[] bytes) {
    String contentType = httpRequest.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
    if (!StringUtils.startsWithIgnoreCase(contentType, "multipart/")) {
        MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.request(httpMethod, uri);
        if (!ObjectUtils.isEmpty(bytes)) {
            requestBuilder.content(bytes);
        }
        return requestBuilder;
    }
    // Parse the multipart request in order to adapt to Servlet Part's
    MockMultipartHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.multipart(uri);
    Assert.notNull(bytes, "No multipart content");
    ReactiveHttpInputMessage inputMessage = MockServerHttpRequest.post(uri.toString()).headers(httpRequest.getHeaders()).body(Mono.just(DefaultDataBufferFactory.sharedInstance.wrap(bytes)));
    MULTIPART_READER.read(ResolvableType.forClass(Part.class), inputMessage, Collections.emptyMap()).flatMap(part -> DataBufferUtils.join(part.content()).doOnNext(buffer -> {
        byte[] partBytes = new byte[buffer.readableByteCount()];
        buffer.read(partBytes);
        DataBufferUtils.release(buffer);
        // Adapt to jakarta.servlet.http.Part...
        MockPart mockPart = (part instanceof FilePart ? new MockPart(part.name(), ((FilePart) part).filename(), partBytes) : new MockPart(part.name(), partBytes));
        mockPart.getHeaders().putAll(part.headers());
        requestBuilder.part(mockPart);
    })).blockLast(TIMEOUT);
    return requestBuilder;
}
Also used : MockMvcRequestBuilders.asyncDispatch(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch) FilePart(org.springframework.http.codec.multipart.FilePart) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ClientHttpResponse(org.springframework.http.client.reactive.ClientHttpResponse) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) MockMvc(org.springframework.test.web.servlet.MockMvc) HttpCookie(org.springframework.http.HttpCookie) MockPart(org.springframework.mock.web.MockPart) RequestBuilder(org.springframework.test.web.servlet.RequestBuilder) Part(org.springframework.http.codec.multipart.Part) MockMvcResultHandlers(org.springframework.test.web.servlet.result.MockMvcResultHandlers) Duration(java.time.Duration) MvcResult(org.springframework.test.web.servlet.MvcResult) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) ClientHttpRequest(org.springframework.http.client.reactive.ClientHttpRequest) Nullable(org.springframework.lang.Nullable) FlashMap(org.springframework.web.servlet.FlashMap) URI(java.net.URI) ResolvableType(org.springframework.core.ResolvableType) ResponseCookie(org.springframework.http.ResponseCookie) MockClientHttpResponse(org.springframework.mock.http.client.reactive.MockClientHttpResponse) DefaultPartHttpMessageReader(org.springframework.http.codec.multipart.DefaultPartHttpMessageReader) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) HttpHeaders(org.springframework.http.HttpHeaders) StringWriter(java.io.StringWriter) ObjectUtils(org.springframework.util.ObjectUtils) HttpMethod(org.springframework.http.HttpMethod) Mono(reactor.core.publisher.Mono) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockMvcRequestBuilders(org.springframework.test.web.servlet.request.MockMvcRequestBuilders) ModelAndView(org.springframework.web.servlet.ModelAndView) List(java.util.List) Cookie(jakarta.servlet.http.Cookie) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) MockServerClientHttpResponse(org.springframework.test.web.reactive.server.MockServerClientHttpResponse) MockMultipartHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder) Collections(java.util.Collections) ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) MockClientHttpRequest(org.springframework.mock.http.client.reactive.MockClientHttpRequest) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) MockMultipartHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder) FilePart(org.springframework.http.codec.multipart.FilePart) MockPart(org.springframework.mock.web.MockPart) Part(org.springframework.http.codec.multipart.Part) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) MockPart(org.springframework.mock.web.MockPart) ReactiveHttpInputMessage(org.springframework.http.ReactiveHttpInputMessage) FilePart(org.springframework.http.codec.multipart.FilePart)

Example 4 with MockMultipartHttpServletRequestBuilder

use of org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder in project TOSCAna by StuPro-TOSCAna.

the class CsarControllerTest method uploadTest.

@Test
public void uploadTest() throws Exception {
    byte[] data = generateRandomByteArray(rnd, 10 * 1024);
    byte[] hash = getSHA256Hash(data);
    String path = CSAR_BASE_URL + "rnd";
    MockMultipartHttpServletRequestBuilder builder = buildMockedMultipartUploadRequest(data, path);
    ResultActions resultActions = mvc.perform(builder).andDo(print()).andExpect(status().is2xxSuccessful());
    resultActions.andReturn();
    assertNotNull(dataRead);
    assertEquals(data.length, dataRead.length);
    byte[] hashUpload = getSHA256Hash(this.dataRead);
    assertHashesEqual(hash, hashUpload);
}
Also used : MockMultipartHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder) Mockito.anyString(org.mockito.Mockito.anyString) ResultActions(org.springframework.test.web.servlet.ResultActions) Test(org.junit.Test) BaseSpringTest(org.opentosca.toscana.core.BaseSpringTest)

Example 5 with MockMultipartHttpServletRequestBuilder

use of org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder in project ArachneCentralAPI by OHDSI.

the class AnalysisControllerTests method testUpdateCodeFile.

@Test
@WithUserDetails(value = ADMIN_EMAIL)
@DatabaseSetups({ @DatabaseSetup("/data/study-with-contributor.xml"), @DatabaseSetup("/data/analysis/analysis-list.xml"), @DatabaseSetup("/data/analysis/code-file-before-deleting.xml") })
@ExpectedDatabases({ @ExpectedDatabase(value = "/data/study-with-contributor.xml", assertionMode = NON_STRICT), @ExpectedDatabase(value = "/data/analysis/code-file-after-updating.xml", assertionMode = NON_STRICT) })
public void testUpdateCodeFile() throws Exception {
    String uuid = "68b75ac9-ab29-49a6-8edb-95142456f5fc";
    String path = this.getClass().getResource("/test.jpg").getPath();
    FileInputStream fileInputStream = new FileInputStream(path);
    MockMultipartFile multipartFile = new MockMultipartFile("file", "test_updated.jpg", "image/jpeg", fileInputStream);
    MockMultipartHttpServletRequestBuilder builder = fileUpload("/api/v1/analysis-management/analyses/{analysisId}/files/{fileUuid}", ANALYSIS_ID, uuid);
    builder.with(request -> {
        request.setMethod("PUT");
        return request;
    });
    mvc.perform(builder.file(multipartFile).param("label", "labelUploadedFile").param("file", path).contentType(MULTIPART_FORM_DATA)).andExpect(NO_ERROR_CODE).andExpect(TRUE_RESULT);
}
Also used : MockMultipartFile(org.springframework.mock.web.MockMultipartFile) MockMultipartHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder) FileInputStream(java.io.FileInputStream) DatabaseSetups(com.github.springtestdbunit.annotation.DatabaseSetups) Test(org.junit.Test) WithUserDetails(org.springframework.security.test.context.support.WithUserDetails) ExpectedDatabases(com.github.springtestdbunit.annotation.ExpectedDatabases)

Aggregations

MockMultipartHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder)7 MockMultipartFile (org.springframework.mock.web.MockMultipartFile)4 Test (org.junit.Test)3 Mockito.anyString (org.mockito.Mockito.anyString)2 BaseSpringTest (org.opentosca.toscana.core.BaseSpringTest)2 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)2 DatabaseSetups (com.github.springtestdbunit.annotation.DatabaseSetups)1 ExpectedDatabases (com.github.springtestdbunit.annotation.ExpectedDatabases)1 io.restassured.http (io.restassured.http)1 Cookie (jakarta.servlet.http.Cookie)1 FileInputStream (java.io.FileInputStream)1 StringWriter (java.io.StringWriter)1 URI (java.net.URI)1 Duration (java.time.Duration)1 Collections (java.util.Collections)1 List (java.util.List)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 Function (java.util.function.Function)1 Test (org.junit.jupiter.api.Test)1 ResolvableType (org.springframework.core.ResolvableType)1