Example usage for org.springframework.mock.web MockMultipartFile MockMultipartFile

List of usage examples for org.springframework.mock.web MockMultipartFile MockMultipartFile

Introduction

In this page you can find the example usage for org.springframework.mock.web MockMultipartFile MockMultipartFile.

Prototype

public MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType,
        InputStream contentStream) throws IOException 

Source Link

Document

Create a new MockMultipartFile with the given content.

Usage

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java

@Test
@Description("Verifies that artifacts which exceed the configured maximum size cannot be uploaded.")
public void uploadArtifactFailsIfTooLarge() throws Exception {
    final SoftwareModule sm = testdataFactory.createSoftwareModule("quota", "quota");
    final long maxSize = quotaManagement.getMaxArtifactSize();

    // create a file which exceeds the configured maximum size
    final byte[] randomBytes = randomBytes(Math.toIntExact(maxSize) + 1024);

    final MockMultipartFile file = new MockMultipartFile("file", "origFilename", null, randomBytes);

    // try to upload
    mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
            .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
            .andExpect(status().isForbidden());
}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java

@Test
@Description("Verifies that artifact with invalid filename cannot be uploaded to prevent cross site scripting.")
public void uploadArtifactFailsIfFilenameInvalide() throws Exception {
    final SoftwareModule sm = testdataFactory.createSoftwareModule("quota", "quota");
    final String illegalFilename = "<img src=ernw onerror=alert(1)>.xml";

    final byte[] randomBytes = randomBytes(5 * 1024);
    final MockMultipartFile file = new MockMultipartFile("file", illegalFilename, null, randomBytes);

    mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
            .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.message", containsString("Invalid characters in string")));
}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java

@Test
@Description("Verfies that the system does not accept empty artifact uploads. Expected response: BAD REQUEST")
public void emptyUploadArtifact() throws Exception {
    assertThat(softwareModuleManagement.findAll(PAGE)).hasSize(0);
    assertThat(artifactManagement.count()).isEqualTo(0);

    final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();

    final MockMultipartFile file = new MockMultipartFile("file", "orig", null, new byte[0]);

    mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
            .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
            .andExpect(status().isBadRequest());
}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java

@Test
@Description("Verfies that the system does not accept identical artifacts uploads for the same software module. Expected response: CONFLICT")
public void duplicateUploadArtifact() throws Exception {
    final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();

    final byte random[] = randomBytes(5 * 1024);
    final String md5sum = HashGeneratorUtils.generateMD5(random);
    final String sha1sum = HashGeneratorUtils.generateSHA1(random);
    final MockMultipartFile file = new MockMultipartFile("file", "orig", null, random);

    mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
            .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
            .andExpect(status().isCreated())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.hashes.md5", equalTo(md5sum)))
            .andExpect(jsonPath("$.hashes.sha1", equalTo(sha1sum)))
            .andExpect(jsonPath("$.providedFilename", equalTo("orig"))).andExpect(status().isCreated());

    mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isConflict());
}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java

@Test
@Description("verfies that option to upload artifacts with a custom defined by metadata, i.e. not the file name of the binary itself.")
public void uploadArtifactWithCustomName() throws Exception {
    final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
    assertThat(artifactManagement.count()).isEqualTo(0);

    // create test file
    final byte random[] = randomBytes(5 * 1024);
    final MockMultipartFile file = new MockMultipartFile("file", "origFilename", null, random);

    // upload/* ww w  .  j a  v a  2  s .  co  m*/
    mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file).param("filename",
            "customFilename")).andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
            .andExpect(content().contentType(MediaTypes.HAL_JSON_UTF8))
            .andExpect(jsonPath("$.providedFilename", equalTo("customFilename")))
            .andExpect(status().isCreated());

    // check result in db...
    // repo
    assertThat(artifactManagement.count()).isEqualTo(1);

    // hashes
    assertThat(artifactManagement.getByFilename("customFilename")).as("Local artifact is wrong").isPresent();
}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java

@Test
@Description("Verfies that the system refuses upload of an artifact where the provided hash sums do not match. Expected result: BAD REQUEST")
public void uploadArtifactWithHashCheck() throws Exception {
    final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
    assertThat(artifactManagement.count()).isEqualTo(0);

    // create test file
    final byte random[] = randomBytes(5 * 1024);
    final String md5sum = HashGeneratorUtils.generateMD5(random);
    final String sha1sum = HashGeneratorUtils.generateSHA1(random);
    final MockMultipartFile file = new MockMultipartFile("file", "origFilename", null, random);

    // upload/*from w w  w .j  a va2  s .co  m*/
    // wrong sha1
    MvcResult mvcResult = mvc
            .perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
                    .param("md5sum", md5sum).param("sha1sum", "afsdff"))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn();

    // check error result
    ExceptionInfo exceptionInfo = ResourceUtility
            .convertException(mvcResult.getResponse().getContentAsString());
    assertThat(exceptionInfo.getErrorCode()).as("Exception contains wrong error code")
            .isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED_SHA1_MATCH.getKey());

    // wrong md5
    mvcResult = mvc
            .perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
                    .param("md5sum", "sdfsdfs").param("sha1sum", sha1sum))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn();

    // check error result
    exceptionInfo = ResourceUtility.convertException(mvcResult.getResponse().getContentAsString());
    assertThat(exceptionInfo.getErrorCode()).as("Exception contains wrong error code")
            .isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED_MD5_MATCH.getKey());

    mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
            .param("md5sum", md5sum).param("sha1sum", sha1sum)).andDo(MockMvcResultPrinter.print())
            .andExpect(status().isCreated());

    assertArtifact(sm, random);

}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java

@Test
@Description("Verifies that only a limited number of artifacts can be uploaded for one software module.")
public void uploadArtifactsUntilQuotaExceeded() throws Exception {
    final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
    final long maxArtifacts = quotaManagement.getMaxArtifactsPerSoftwareModule();

    for (int i = 0; i < maxArtifacts; ++i) {
        // create test file
        final byte random[] = randomBytes(5 * 1024);
        final String md5sum = HashGeneratorUtils.generateMD5(random);
        final String sha1sum = HashGeneratorUtils.generateSHA1(random);
        final MockMultipartFile file = new MockMultipartFile("file", "origFilename" + i, null, random);

        // upload
        mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
                .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
                .andExpect(status().isCreated())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(jsonPath("$.hashes.md5", equalTo(md5sum)))
                .andExpect(jsonPath("$.hashes.sha1", equalTo(sha1sum)))
                .andExpect(jsonPath("$.size", equalTo(random.length)))
                .andExpect(jsonPath("$.providedFilename", equalTo("origFilename" + i))).andReturn();
    }/*from  w w w  .ja  va 2s . c o m*/

    // upload one more file to cause the quota to be exceeded
    final byte random[] = randomBytes(5 * 1024);
    HashGeneratorUtils.generateMD5(random);
    HashGeneratorUtils.generateSHA1(random);
    final MockMultipartFile file = new MockMultipartFile("file", "origFilename_final", null, random);

    // upload
    mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
            .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
            .andExpect(status().isForbidden())
            .andExpect(jsonPath("$.exceptionClass", equalTo(QuotaExceededException.class.getName())))
            .andExpect(jsonPath("$.errorCode", equalTo(SpServerError.SP_QUOTA_EXCEEDED.getKey())));

}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java

@Test
@Description("Verifies that artifacts can only be added as long as the artifact storage quota is not exceeded.")
public void uploadArtifactsUntilStorageQuotaExceeded() throws Exception {

    final long storageLimit = quotaManagement.getMaxArtifactStorage();

    // choose an artifact size which does not violate the max file size
    final int artifactSize = Math.toIntExact(quotaManagement.getMaxArtifactSize() / 10);
    final int numArtifacts = Math.toIntExact(storageLimit / artifactSize);

    for (int i = 0; i < numArtifacts; ++i) {
        // create test file
        final byte random[] = randomBytes(artifactSize);
        final String md5sum = HashGeneratorUtils.generateMD5(random);
        final String sha1sum = HashGeneratorUtils.generateSHA1(random);
        final MockMultipartFile file = new MockMultipartFile("file", "origFilename" + i, null, random);

        // upload
        final SoftwareModule sm = testdataFactory.createSoftwareModuleOs("sm" + i);
        mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
                .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
                .andExpect(status().isCreated())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(jsonPath("$.hashes.md5", equalTo(md5sum)))
                .andExpect(jsonPath("$.hashes.sha1", equalTo(sha1sum)))
                .andExpect(jsonPath("$.size", equalTo(random.length)))
                .andExpect(jsonPath("$.providedFilename", equalTo("origFilename" + i))).andReturn();
    }/*from   www  .java2s  .  c  o  m*/

    // upload one more file to cause the quota to be exceeded
    final byte random[] = randomBytes(artifactSize);
    HashGeneratorUtils.generateMD5(random);
    HashGeneratorUtils.generateSHA1(random);
    final MockMultipartFile file = new MockMultipartFile("file", "origFilename_final", null, random);

    // upload
    final SoftwareModule sm = testdataFactory.createSoftwareModuleOs("sm" + numArtifacts);
    mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
            .accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
            .andExpect(status().isForbidden())
            .andExpect(jsonPath("$.exceptionClass", equalTo(QuotaExceededException.class.getName())))
            .andExpect(jsonPath("$.errorCode", equalTo(SpServerError.SP_QUOTA_EXCEEDED.getKey())));

}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.MgmtSoftwareModuleResourceTest.java

@Test
@Description("Verfies that the system refuses unsupported request types and answers as defined to them, e.g. NOT FOUND on a non existing resource. Or a HTTP POST for updating a resource results in METHOD NOT ALLOWED etc.")
public void invalidRequestsOnArtifactResource() throws Exception {

    final int artifactSize = 5 * 1024;
    final byte random[] = randomBytes(artifactSize);
    final MockMultipartFile file = new MockMultipartFile("file", "orig", null, random);

    final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();

    // no artifact available
    mvc.perform(get("/rest/v1/softwaremodules/{smId}/artifacts/1234567/download", sm.getId()))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());

    mvc.perform(delete("/rest/v1/softwaremodules/{smId}/artifacts/1234567", sm.getId()))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());

    // SM does not exist
    artifactManagement.create(/*from  www.  j a  v a  2 s .  com*/
            new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize));
    mvc.perform(get("/rest/v1/softwaremodules/1234567890/artifacts")).andDo(MockMvcResultPrinter.print())
            .andExpect(status().isNotFound());

    mvc.perform(fileUpload("/rest/v1/softwaremodules/1234567890/artifacts").file(file))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());

    // bad request - no content
    mvc.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());

    // not allowed methods
    mvc.perform(put("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());

    mvc.perform(delete("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
}

From source file:org.eclipse.hawkbit.mgmt.rest.resource.SMRessourceMisingMongoDbConnectionTest.java

@Test
@Description("Ensures that the correct error code is returned in case MongoDB unavailable.")
public void missingMongoDbConnectionResultsInErrorAtUpload() throws Exception {
    mongodExecutable.stop();/*from   w w  w. jav  a2  s  . c  o m*/

    assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
    assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(0);
    SoftwareModule sm = entityFactory.generateSoftwareModule(
            softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", "version 1", null, null);
    sm = softwareManagement.createSoftwareModule(sm);
    assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(0);

    // create test file
    final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
    final MockMultipartFile file = new MockMultipartFile("file", "origFilename", null, random);

    // upload
    final MvcResult mvcResult = mvc
            .perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file))
            .andDo(MockMvcResultPrinter.print()).andExpect(status().isInternalServerError()).andReturn();

    // check error result
    final ExceptionInfo exceptionInfo = ResourceUtility
            .convertException(mvcResult.getResponse().getContentAsString());
    assertThat(exceptionInfo.getErrorCode()).isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED.getKey());
    assertThat(exceptionInfo.getMessage()).isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED.getMessage());

    // ensure that the JPA transaction was rolled back
    assertThat(artifactManagement.countLocalArtifactsAll()).isEqualTo(0);

}