org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder Java Examples
The following examples show how to use
org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AddPermissionsV2EndToEndTest.java From credhub with Apache License 2.0 | 7 votes |
@Test public void POST_whenUserTriesToGrantPermissionsToSelf_theyCannotAddAPermission() throws Exception { final String credentialName = "/test"; PermissionsV2EndToEndTestHelper.setPermissions(mockMvc, credentialName, PermissionOperation.WRITE); final MockHttpServletRequestBuilder addPermissionRequestWithRead = post("/api/v2/permissions") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) .content("{" + " \"actor\": \"" + ALL_PERMISSIONS_ACTOR_ID + "\",\n" + " \"path\": \"" + credentialName + "\",\n" + " \"operations\": [\"write\", \"read\"]\n" + "}"); mockMvc.perform(addPermissionRequestWithRead).andExpect(status().isBadRequest()); }
Example #2
Source File: AddPermissionsV2EndToEndTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void POST_whenUserTriesToAddAnAdditionalOperationToAPermissionThatAlreadyExists_theyReceiveAConflict() throws Exception { final String credentialName = "/test"; PermissionsV2EndToEndTestHelper.setPermissions(mockMvc, credentialName, PermissionOperation.WRITE); final MockHttpServletRequestBuilder addPermissionRequestWithRead = post("/api/v2/permissions") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) .content("{" + " \"actor\": \"" + USER_A_ACTOR_ID + "\",\n" + " \"path\": \"" + credentialName + "\",\n" + " \"operations\": [\"write\", \"read\"]\n" + "}"); mockMvc.perform(addPermissionRequestWithRead).andExpect(status().isConflict()); }
Example #3
Source File: CertificateSetAndRegenerateTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void certificateSetRequest_whenProvidedANonCertificateValue_returnsAValidationError() throws Exception { final String setJson = JSONObject.toJSONString( ImmutableMap.<String, String>builder() .put("ca_name", "") .put("certificate", "This is definitely not a certificate. Or is it?") .put("private_key", TEST_PRIVATE_KEY) .build()); final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) //language=JSON .content("{\n" + " \"name\" : \"/crusher\",\n" + " \"type\" : \"certificate\",\n" + " \"value\" : " + setJson + "}"); this.mockMvc.perform(certificateSetRequest) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error", equalTo("The provided certificate value is not a valid X509 certificate."))); }
Example #4
Source File: MockMvcCreateTaskTests.java From spring4-sandbox with Apache License 2.0 | 6 votes |
@Test public void createTaskFormSubmit() throws Exception { String nameParamName = "name"; String descriptionParamName = "description"; mockMvc.perform(get("/tasks/new")) .andExpect(xpath("//input[@name='" + nameParamName + "']").exists()) .andExpect(xpath("//textarea[@name='" + descriptionParamName + "']").exists()); MockHttpServletRequestBuilder createTask = post("/tasks") .param(nameParamName, "First task") .param(descriptionParamName, "Description of my first task"); mockMvc.perform(createTask) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/tasks")); mockMvc.perform(get("/tasks")) .andExpect(xpath("//ul[@id='todotasks']//li[@class='list-group-item']").exists()); mockMvc.perform(get("/tasks")) .andExpect(xpath("//ul[@id='doingtasks']//li[@class='list-group-item']").exists()); mockMvc.perform(get("/tasks")) .andExpect(xpath("//ul[@id='donetasks']//li[@class='list-group-item']").exists()); }
Example #5
Source File: UpdatePermissionsV2EndToEndTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void PUT_whenUUIDIsInvalid_ReturnStatusNotFound() throws Exception { final String credUUID = "not-a-uuid"; final MockHttpServletRequestBuilder putPermissionRequest = put("/api/v2/permissions/" + credUUID) .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) .content("{" + " \"actor\": \"" + USER_A_ACTOR_ID + "\",\n" + " \"path\": \"" + "badCredentialName" + "\",\n" + " \"operations\": [\"" + "write" + "\"]\n" + "}"); final String responseJson = mockMvc.perform(putPermissionRequest).andExpect(status().isNotFound()).andReturn().getResponse().getContentAsString(); final String errorMessage = new JSONObject(responseJson).getString("error"); assertThat(errorMessage, is(IsEqual.equalTo("The request includes a permission that does not exist."))); }
Example #6
Source File: CredentialAclEnforcementTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void POST_whenTheUserHasPermissionToWrite_succeeds() throws Exception { final MockHttpServletRequestBuilder edit = post("/api/v1/data") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON_UTF8) // language=JSON .content("{\n" + " \"name\" : \"" + CREDENTIAL_NAME + "\",\n" + " \"type\" : \"password\"\n" + "}") .accept(APPLICATION_JSON); this.mockMvc.perform(edit) .andDo(print()) .andExpect(status().is2xxSuccessful()); }
Example #7
Source File: GetPermissionsV2EndToEndTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void GET_whenUserGivesAPermissionGuid_theyReceiveThePermissions() throws Exception { final String credentialName = "/test"; final UUID credentialUuid = PermissionsV2EndToEndTestHelper.setPermissions(mockMvc, credentialName, PermissionOperation.WRITE); final MockHttpServletRequestBuilder getUuidRequest = get("/api/v2/permissions/" + credentialUuid) .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON); final String content = mockMvc.perform(getUuidRequest).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); final PermissionsV2View returnValue = JsonTestHelper.deserialize(content, PermissionsV2View.class); assertThat(returnValue.getActor(), equalTo(USER_A_ACTOR_ID)); assertThat(returnValue.getPath(), equalTo(credentialName)); assertThat(returnValue.getOperations(), contains(PermissionOperation.WRITE)); assertThat(returnValue.getUuid(), equalTo(credentialUuid)); }
Example #8
Source File: RegenerationEndpointTest.java From credhub with Apache License 2.0 | 6 votes |
@Before public void beforeEach() throws Exception { mockMvc = MockMvcBuilders .webAppContextSetup(webApplicationContext) .apply(springSecurity()) .build(); final MockHttpServletRequestBuilder generatePasswordRequest = post(API_V1_DATA_ENDPOINT) .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) //language=JSON .content("{\n" + " \"name\" : \"" + CREDENTIAL_NAME + "\",\n" + " \"type\" : \"password\"\n" + "}"); final String generatePasswordResult = this.mockMvc.perform(generatePasswordRequest) .andDo(print()) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); originalPassword = (new JSONObject(generatePasswordResult)).getString("value"); assertThat(originalPassword, notNullValue()); }
Example #9
Source File: BulkRegenerateTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void regeneratingCertificatesSignedByCA_shouldRegenerateCertificates() throws Exception { final MockHttpServletRequestBuilder regenerateCertificatesRequest = post(API_V1_BULK_REGENERATE_ENDPOINT) .header("Authorization", "Bearer " + USER_A_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON_UTF8) //language=JSON .content("{\"signed_by\" : \"" + caName + "\"}"); final String regenerateCertificatesResult = this.mockMvc.perform(regenerateCertificatesRequest) .andDo(print()) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); final JSONArray regeneratedCredentials = (new JSONObject(regenerateCertificatesResult)).getJSONArray("regenerated_credentials"); final List<String> result = Arrays.asList(regeneratedCredentials.getString(0), regeneratedCredentials.getString(1)); assertThat(regeneratedCredentials.length(), equalTo(2)); assertThat(result, containsInAnyOrder(cert1Name, cert2Name)); }
Example #10
Source File: CredentialSetErrorHandlingTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void givenACertificateRequest_whenAnInvalidCaNameIsProvided_returns404() throws Exception { final String setJson = JSONObject.toJSONString( ImmutableMap.<String, String>builder() .put("ca_name", "does not exist") .put("certificate", TestConstants.TEST_CERTIFICATE) .put("private_key", TestConstants.TEST_PRIVATE_KEY) .build()); final MockHttpServletRequestBuilder request = put("/api/v1/data") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) .content("{" + " \"name\":\"some-name\"," + " \"type\":\"certificate\"," + " \"value\": " + setJson + "}"); mockMvc.perform(request) .andExpect(status().isNotFound()) .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON)) .andExpect(jsonPath("$.error").value(ErrorMessages.Credential.CERTIFICATE_ACCESS)); }
Example #11
Source File: CredentialsTypeSpecificGenerateIntegrationTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void shouldAcceptAnyCasingForType() throws Exception { final MockHttpServletRequestBuilder request = post("/api/v1/data") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) .content("{" + "\"name\":\"" + CREDENTIAL_NAME + "\"," + "\"type\":\"" + parametizer.credentialType.toUpperCase() + "\"," + "\"parameters\":" + parametizer.generationParameters + "," + "\"overwrite\":" + false + "}"); mockMvc.perform(request) .andExpect(status().isOk()) .andExpect(parametizer.jsonAssertions()) .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON)) .andExpect(MultiJsonPathMatcher.multiJsonPath( "$.type", parametizer.credentialType, "$.version_created_at", FROZEN_TIME.toString()) ); }
Example #12
Source File: UserControllerIntTest.java From spring-boot-completablefuture with MIT License | 6 votes |
@Test public void testGetUsersPage1Size1() throws Exception { final MockHttpServletRequestBuilder getRequest = get("/api/users") .param("page", "1") .param("size", "1") .accept(MediaType.APPLICATION_JSON); final MvcResult mvcResult = mockMvc .perform(getRequest) .andExpect(MockMvcResultMatchers.request().asyncStarted()) .andReturn(); mockMvc .perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.content", Matchers.hasSize(1))) .andExpect(jsonPath("$.content[0].email").value("[email protected]")) .andExpect(jsonPath("$.totalElements").value(2)) .andExpect(jsonPath("$.totalPages").value(2)) .andExpect(jsonPath("$.size").value(1)) .andExpect(jsonPath("$.number").value(1)) .andExpect(jsonPath("$.first").value("false")) .andExpect(jsonPath("$.last").value("true")); }
Example #13
Source File: CredentialGetTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void getCertificateCredentials_whenCurrentFalseReturnsAllCertificateCredentials() throws Exception { final String credentialName = "/first-certificate"; generateCertificateCredential(mockMvc, credentialName, true, "test", null, ALL_PERMISSIONS_TOKEN); String response = getCertificateCredentialsByName(mockMvc, ALL_PERMISSIONS_TOKEN, credentialName); final String uuid = JsonPath.parse(response) .read("$.certificates[0].id"); RequestHelper.regenerateCertificate(mockMvc, uuid, true, ALL_PERMISSIONS_TOKEN); RequestHelper.regenerateCertificate(mockMvc, uuid, false, ALL_PERMISSIONS_TOKEN); final MockHttpServletRequestBuilder request = get("/api/v1/data?name=" + credentialName + "¤t=false") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON); response = mockMvc.perform(request) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); final JSONObject responseObject = new JSONObject(response); assertThat(responseObject.getJSONArray("data").length(), equalTo(3)); }
Example #14
Source File: JobConfigControllerTestIT.java From blackduck-alert with Apache License 2.0 | 6 votes |
@Test @WithMockUser(roles = AlertIntegrationTest.ROLE_ALERT_ADMIN) public void testSaveConfig() throws Exception { addGlobalConfiguration(blackDuckProviderKey, Map.of( BlackDuckDescriptor.KEY_BLACKDUCK_URL, List.of("BLACKDUCK_URL"), BlackDuckDescriptor.KEY_BLACKDUCK_API_KEY, List.of("BLACKDUCK_API"))); MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post(url) .with(SecurityMockMvcRequestPostProcessors.user("admin").roles(AlertIntegrationTest.ROLE_ALERT_ADMIN)) .with(SecurityMockMvcRequestPostProcessors.csrf()); JobFieldModel fieldModel = createTestJobFieldModel(null, null); request.content(gson.toJson(fieldModel)); request.contentType(contentType); MvcResult mvcResult = mockMvc.perform(request).andExpect(MockMvcResultMatchers.status().isCreated()).andReturn(); String response = mvcResult.getResponse().getContentAsString(); checkResponse(response); }
Example #15
Source File: AuthConfigurationTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void dataEndpoint_withMutualTLS_deniesClientCertsWithOrgUnitNotPrefixedAccurately() throws Exception { setupDataEndpointMocks(); final CertificateReader certificateReader = new CertificateReader(CertificateStringConstants.TEST_CERT_WITH_INVALID_ORGANIZATION_UNIT_PREFIX); final MockHttpServletRequestBuilder post = post(dataApiPath) .with(SecurityMockMvcRequestPostProcessors.x509( certificateReader.getCertificate())) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .content("{\"type\":\"password\",\"name\":\"" + credentialName + "\"}"); final String expectedError = "The provided authentication mechanism does not provide a " + "valid identity. Please contact your system administrator."; mockMvc.perform(post) .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$.error").value(expectedError)); }
Example #16
Source File: PermissionsEndpointTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void POST_whenMalformedJsonIsSent_returnsBadRequest() throws Exception { final String malformedJson = "{" + " \"credential_name\": \"foo\"," + " \"permissions\": [" + " {" + " \"actor\": \"dan\"," + " \"operations\":" + " }]" + "}"; final MockHttpServletRequestBuilder post = post("/api/v1/permissions") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) .content(malformedJson); this.mockMvc.perform(post).andExpect(status().isBadRequest()) .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON)) .andExpect(jsonPath("$.error", equalTo( "The request could not be fulfilled because the request path or body did" + " not meet expectation. Please check the documentation for required " + "formatting and retry your request."))); }
Example #17
Source File: ContentModelControllerUnitTest.java From entando-components with GNU Lesser General Public License v3.0 | 6 votes |
private ResultActions performRequest(MockHttpServletRequestBuilder requestBuilder, String payload) throws Exception { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build(); String accessToken = mockOAuthInterceptor(user); requestBuilder = requestBuilder .contentType(MediaType.APPLICATION_JSON_VALUE) .header("Authorization", "Bearer " + accessToken); if (payload != null) { requestBuilder = requestBuilder.content(payload); } ResultActions result = mockMvc.perform(requestBuilder); return result; }
Example #18
Source File: CertificateSetAndRegenerateTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void certificateSetRequest_whenProvidedAMalformedCertificate_returnsAValidationError() throws Exception { final String setJson = JSONObject.toJSONString( ImmutableMap.<String, String>builder() .put("certificate", "-----BEGIN CERTIFICATE-----") // missing END CERTIFICATE tag .build()); final MockHttpServletRequestBuilder certificateSetRequest = put("/api/v1/data") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) .content("{\n" + " \"name\" : \"/crusher\",\n" + " \"type\" : \"certificate\",\n" + " \"value\" : " + setJson + "}"); this.mockMvc.perform(certificateSetRequest) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.error", equalTo("The provided certificate value is not a valid X509 certificate."))); }
Example #19
Source File: CertificateGetTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void getCertificateCredentialsByName_doesNotReturnOtherCredentialTypes() throws Exception { generatePassword(mockMvc, "my-credential", true, 10, ALL_PERMISSIONS_TOKEN); final MockHttpServletRequestBuilder get = get("/api/v1/certificates?name=" + "my-credential") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON); final String response = mockMvc.perform(get) .andDo(print()) .andExpect(status().isNotFound()) .andReturn().getResponse().getContentAsString(); assertThat(response, containsString( "The request could not be completed because the credential does not exist or you do not have sufficient authorization.")); }
Example #20
Source File: CredentialsTypeSpecificGenerateIntegrationTest.java From credhub with Apache License 2.0 | 5 votes |
@Test public void generatingANewCredentialVersion_withOverwriteFalse_returnsThePreviousVersion_whenParametersAreTheSame() throws Exception { beforeEachExistingCredential(); final MockHttpServletRequestBuilder request = beforeEachOverwriteSetToFalse(); mockMvc.perform(request) .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(parametizer.jsonAssertions()) .andExpect(MultiJsonPathMatcher.multiJsonPath( "$.id", credentialUuid.toString(), "$.version_created_at", FROZEN_TIME.minusSeconds(1).toString())); }
Example #21
Source File: AbstractParametricValuesServiceIT.java From find with MIT License | 5 votes |
@Test public void getDependentParametricValues() throws Exception { final MvcResult mvcResult = mockMvc.perform(parametricValuesRequest()).andReturn(); final byte[] contentBytes = mvcResult.getResponse().getContentAsByteArray(); final JsonNode contentTree = new ObjectMapper().readTree(contentBytes); final List<String> fields = new LinkedList<>(); // Only ask for dependent parametric values in fields which have values for (final JsonNode fieldNode : contentTree) { if (fieldNode.get("totalValues").asInt() > 0) { fields.add(fieldNode.get("id").asText()); } } if (fields.isEmpty()) { throw new IllegalStateException("No parametric fields have values"); } final MockHttpServletRequestBuilder requestBuilder = get(ParametricValuesController.PARAMETRIC_PATH + ParametricValuesController.DEPENDENT_VALUES_PATH) .param(ParametricValuesController.FIELD_NAMES_PARAM, fields.toArray(new String[]{})) .param(ParametricValuesController.DATABASES_PARAM, mvcIntegrationTestUtils.getDatabases()) .param(ParametricValuesController.QUERY_TEXT_PARAM, "*") .param(ParametricValuesController.FIELD_TEXT_PARAM, "") .with(authentication(userAuth())); mockMvc.perform(requestBuilder) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$", not(empty()))); }
Example #22
Source File: CredentialDeleteTest.java From credhub with Apache License 2.0 | 5 votes |
@Test public void delete_whenNoCredentialExistsWithTheName_returnsAnError() throws Exception { final MockHttpServletRequestBuilder delete = delete("/api/v1/data?name=invalid_name") .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN) .accept(APPLICATION_JSON); final String expectedError = "The request could not be completed because the credential does not exist or you do not have sufficient authorization."; mockMvc.perform(delete) .andExpect(status().isNotFound()) .andExpect(content().contentTypeCompatibleWith(APPLICATION_JSON)) .andExpect(jsonPath("$.error").value(expectedError)); }
Example #23
Source File: ContentVersioningControllerIntegrationTest.java From entando-components with GNU Lesser General Public License v3.0 | 5 votes |
private ResultActions listLatestVersions(UserDetails user, Map<String,String> params) throws Exception { String accessToken = mockOAuthInterceptor(user); final MockHttpServletRequestBuilder requestBuilder = get("/plugins/versioning/contents/") .sessionAttr("user", user) .header("Authorization", "Bearer " + accessToken); for (String key : Optional.ofNullable(params).orElse(new HashMap<>()).keySet()) { requestBuilder.param(key, params.get(key)); } return mockMvc.perform(requestBuilder) .andDo(print()); }
Example #24
Source File: AbstractMvcTest.java From kafka-webview with MIT License | 5 votes |
/** * Utility method to test URLs are/are not accessible w/o the admin role. * @param url Url to hit * @param isPost If its a POST true, false if GET * @throws Exception on error. */ protected void testUrlWithOutAdminRole(final String url, final boolean isPost) throws Exception { final MockHttpServletRequestBuilder action; if (isPost) { action = post(url) .with(csrf()); } else { action = get(url); } mockMvc .perform(action.with(user(nonAdminUserDetails))) //.andDo(print()) .andExpect(status().isForbidden()); }
Example #25
Source File: GeneralOperatingControllTest.java From rebuild with GNU General Public License v3.0 | 5 votes |
@Test public void test5UnshareBatch() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders .post("/app/entity/record-unshare-batch?id=" + lastSaveId + "&to=" + UserService.SYSTEM_USER); MvcResponse resp = perform(builder, UserService.ADMIN_USER); System.out.println(resp); Assert.assertTrue(resp.isSuccess()); }
Example #26
Source File: ExportControllerIT.java From find with MIT License | 5 votes |
@Test public void exportSunburstToPptx() throws Exception { final MockHttpServletRequestBuilder requestBuilder = post(ExportController.EXPORT_PATH + ExportController.PPTX_PATH + ExportController.SUNBURST_PATH).with(authentication(biAuth())); requestBuilder.param(ExportController.DATA_PARAM, getData(SUNBURST_DATA)); mockMvc.perform(requestBuilder) .andExpect(status().isOk()) .andExpect(content().contentType(ExportFormat.PPTX.getMimeType())) .andExpect(content().string(notNullValue())); }
Example #27
Source File: ReviewControllerTests.java From mirrorgate with Apache License 2.0 | 5 votes |
@Test public void createFeedbackReviewRedirectTest() throws Exception { final Review review = createFeedbackReview(); when(reviewService.saveApplicationReview(eq(review.getAppname()), any())).thenReturn(map(review)); final MockHttpServletRequestBuilder mockHSRB = post("/reviews/" + review.getAppname()); this.mockMvc.perform(mockHSRB .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("rate", String.valueOf(review.getStarrating())) .param("comment", review.getComment()) .param("url", "foobar")) .andExpect(status().is(HttpStatus.FOUND.value())); }
Example #28
Source File: ResourceVersioningControllerIntegrationTest.java From entando-components with GNU Lesser General Public License v3.0 | 5 votes |
private ResultActions performDownloadResource(UserDetails user, String resourceId, Integer size) throws Exception { final MockHttpServletRequestBuilder requestBuilder = get( "/plugins/versioning/resources/{resourceId}/{size}", resourceId, size) .sessionAttr("user", user) .header("Authorization", "Bearer " + mockOAuthInterceptor(user)); return mockMvc.perform(requestBuilder) .andDo(print()); }
Example #29
Source File: ApplicationControllerTest.java From steady with Apache License 2.0 | 5 votes |
/** * Repo-save and rest-clean (fails due to read-only space) * @param obj * @return */ @Test @Transactional public void testCleanAppReadOnlySpace() throws Exception { final Library lib = this.createExampleLibrary(); this.libRepository.customSave(lib); Application app = this.createExampleApplication(); app = this.appRepository.customSave(app); // Repo must contain 1 assertEquals(1, this.appRepository.count()); // Make the space read-only try{ final Space default_space = SpaceRepository.FILTER.findOne(spaceRepository.findBySecondaryKey(TEST_DEFAULT_SPACE)); default_space.setReadOnly(true); } catch(EntityNotFoundException e) { e.printStackTrace(); assertTrue(false); } // Rest-post final MockHttpServletRequestBuilder post_builder = post(getAppUri(app)) .param("clean", "true") .accept(MediaType.APPLICATION_JSON); mockMvc.perform(post_builder) .andExpect(status().isBadRequest()); // Repo must still contain 1 assertEquals(1, this.appRepository.count()); }
Example #30
Source File: BugControllerTest.java From steady with Apache License 2.0 | 5 votes |
/** * Duplicate rest-post. * @throws Exception */ @Test public void testDuplicatePost() throws Exception { final Bug bug = this.createExampleBug(BUG_ID, BUG_DESCR); // Rest-post final MockHttpServletRequestBuilder post_builder = post("/bugs/") .content(JacksonUtil.asJsonString(bug).getBytes()) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON); mockMvc.perform(post_builder) .andExpect(status().isCreated()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.bugId", is(BUG_ID))) .andExpect(jsonPath("$.reference[0]", is(BUG_URL1))) .andExpect(jsonPath("$.reference[1]", is(BUG_URL2))) .andExpect(jsonPath("$.description", is(BUG_DESCR))); // Repo must contain 1 assertEquals(1, this.bugRepository.count()); // Rest-post mockMvc.perform(post_builder) .andExpect(status().isConflict()); // Repo must contain 1 assertEquals(1, this.bugRepository.count()); }