List of usage examples for org.springframework.mock.web MockHttpServletResponse getContentAsString
public String getContentAsString() throws UnsupportedEncodingException
From source file:org.jasig.cas.support.oauth.web.OAuth20WrapperControllerTests.java
@Test public void verifyNoGrantTypeForTokenCtrls() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", CONTEXT + OAuthConstants.TOKEN_URL); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus()); assertEquals("application/json", mockResponse.getContentType()); final ObjectMapper mapper = new ObjectMapper(); final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST + "\",\"error_description\":\"" + new InvalidParameterException(OAuthConstants.GRANT_TYPE).getMessage() + "\"}"; final JsonNode expectedObj = mapper.readTree(expected); final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString()); assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText()); assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText()); }
From source file:com.thoughtworks.go.server.controller.GoConfigAdministrationControllerIntegrationTest.java
@Test public void shouldGetTemplateAsPartialXmlOnlyIfUserHasAdminRights() throws Exception { //get the pipeline XML configHelper.addPipeline("pipeline", "dev", "linux", "windows"); configHelper.addTemplate("new-template", "dev"); controller.getPipelineAsXmlPartial(0, TemplatesConfig.PIPELINE_TEMPLATES_FAKE_GROUP_NAME, null, response); String xml = response.getContentAsString(); assertThat(xml, containsString("new-template")); //save the pipeline XML MockHttpServletResponse postResponse = new MockHttpServletResponse(); String modifiedXml = xml.replace("new-template", "new-name-for-template"); controller.postPipelineAsXmlPartial(0, TemplatesConfig.PIPELINE_TEMPLATES_FAKE_GROUP_NAME, modifiedXml, goConfigFileDao.md5OfConfigFile(), postResponse); //get the pipeline XML again MockHttpServletResponse getResponse = new MockHttpServletResponse(); controller.getPipelineAsXmlPartial(0, TemplatesConfig.PIPELINE_TEMPLATES_FAKE_GROUP_NAME, null, getResponse);// ww w .java 2 s. c om assertThat(getResponse.getContentAsString(), containsString("new-name-for-template")); assertThat(getResponse.getContentAsString(), is(modifiedXml)); setCurrentUser("user"); MockHttpServletResponse nonAdminResponse = new MockHttpServletResponse(); controller.getPipelineAsXmlPartial(0, TemplatesConfig.PIPELINE_TEMPLATES_FAKE_GROUP_NAME, null, nonAdminResponse); assertThat(nonAdminResponse.getStatus(), is(SC_UNAUTHORIZED)); assertThat(nonAdminResponse.getContentAsString(), is("User 'user' does not have permission to administer pipeline templates")); }
From source file:com.tasktop.c2c.server.common.service.tests.ajp.AjpProtocolTest.java
private void assertResponseIsExpected(Payload expectedPayload, MockHttpServletResponse response) throws UnsupportedEncodingException { Assert.assertEquals(expectedPayload.responseCode, response.getStatus()); for (Entry<String, String> header : expectedPayload.getResponseHeaders().entrySet()) { Assert.assertEquals(header.getValue(), response.getHeader(header.getKey())); }/* ww w. ja v a 2 s. com*/ if (expectedPayload.binaryContent != null) { Assert.assertArrayEquals(expectedPayload.binaryContent, response.getContentAsByteArray()); } else if (expectedPayload.characterContent != null) { Assert.assertEquals(expectedPayload.characterContent, response.getContentAsString()); } }
From source file:org.auraframework.integration.test.http.resource.BootstrapTest.java
@SuppressWarnings("unchecked") @Test//from w w w . ja v a 2 s . com public void testWriteSetsOkResponseWithErrorPayloadWhenTokenValidationFails() throws Exception { // Arrange if (contextService.isEstablished()) { contextService.endContext(); } DefDescriptor<ApplicationDef> appDesc = addSourceAutoCleanup(ApplicationDef.class, "<aura:application></aura:application>"); AuraContext context = contextService.startContext(AuraContext.Mode.PROD, AuraContext.Format.MANIFEST, AuraContext.Authentication.AUTHENTICATED, appDesc); HttpServletRequest request = mock(HttpServletRequest.class); MockHttpServletResponse response = new MockHttpServletResponse(); ConfigAdapter configAdapter = mock(ConfigAdapter.class); Bootstrap bootstrap = getBootstrap(); bootstrap.setConfigAdapter(configAdapter); // Force token validation to fail when(configAdapter.validateBootstrap(anyString())).thenReturn(false); // Act bootstrap.write(request, response, context); // Assert // JWT token failure returns 2xx response code with error payload so browser executes it assertEquals(HttpStatus.SC_OK, response.getStatus()); /* * Expected appBootstrap object * window.Aura.appBootstrap = { * "error":{ * "message":"Invalid jwt parameter" * } * }; */ String content = response.getContentAsString(); Pattern pattern = Pattern.compile("appBootstrap = (\\{.*\\});", Pattern.DOTALL); Matcher matcher = pattern.matcher(content); assertTrue("Failed to find appBootstrap in response: " + content, matcher.find()); Map<String, Object> appBootstrap = (Map<String, Object>) new JsonReader().read(matcher.group(1)); Map<String, Object> error = (Map<String, Object>) appBootstrap.get("error"); String actualMessage = error.get("message").toString(); // refer to the message in Bootstrap.write() String expectedMessage = "Invalid jwt parameter"; assertThat("Failed to find expected message: " + content, actualMessage, containsString(expectedMessage)); }
From source file:org.springframework.data.rest.webmvc.jpa.JpaWebTests.java
/** * @see DATAREST-95//www. j av a 2 s .co m */ @Test public void createThenPatch() throws Exception { Link peopleLink = client.discoverUnique("people"); MockHttpServletResponse bilbo = postAndGet(peopleLink, "{ \"firstName\" : \"Bilbo\", \"lastName\" : \"Baggins\" }", MediaType.APPLICATION_JSON); Link bilboLink = client.assertHasLinkWithRel("self", bilbo); assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.firstName"), is("Bilbo")); assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.lastName"), is("Baggins")); MockHttpServletResponse frodo = patchAndGet(bilboLink, "{ \"firstName\" : \"Frodo\" }", MediaType.APPLICATION_JSON); assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName"), is("Frodo")); assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName"), is("Baggins")); frodo = patchAndGet(bilboLink, "{ \"firstName\" : null }", MediaType.APPLICATION_JSON); assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName"), is(nullValue())); assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.lastName"), is("Baggins")); }
From source file:org.springframework.data.rest.webmvc.jpa.JpaWebTests.java
/** * @see DATAREST-238// www . ja v a 2s .com */ @Test public void putShouldWorkDespiteExistingLinks() throws Exception { Link peopleLink = client.discoverUnique("people"); Person frodo = new Person("Frodo", "Baggins"); String frodoString = mapper.writeValueAsString(frodo); MockHttpServletResponse createdPerson = postAndGet(peopleLink, frodoString, MediaType.APPLICATION_JSON); Link frodoLink = client.assertHasLinkWithRel("self", createdPerson); assertJsonPathEquals("$.firstName", "Frodo", createdPerson); String bilboWithFrodosLinks = createdPerson.getContentAsString().replace("Frodo", "Bilbo"); MockHttpServletResponse overwrittenResponse = putAndGet(frodoLink, bilboWithFrodosLinks, MediaType.APPLICATION_JSON); client.assertHasLinkWithRel("self", overwrittenResponse); assertJsonPathEquals("$.firstName", "Bilbo", overwrittenResponse); }
From source file:org.springframework.data.rest.webmvc.jpa.JpaWebTests.java
/** * @see DATAREST-150/* ww w. ja v a2 s . c o m*/ */ @Test public void createThenPut() throws Exception { Link peopleLink = client.discoverUnique("people"); MockHttpServletResponse bilbo = postAndGet(peopleLink, // "{ \"firstName\" : \"Bilbo\", \"lastName\" : \"Baggins\" }", // MediaType.APPLICATION_JSON); Link bilboLink = client.assertHasLinkWithRel("self", bilbo); assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.firstName"), equalTo("Bilbo")); assertThat((String) JsonPath.read(bilbo.getContentAsString(), "$.lastName"), equalTo("Baggins")); MockHttpServletResponse frodo = putAndGet(bilboLink, // "{ \"firstName\" : \"Frodo\" }", // MediaType.APPLICATION_JSON); assertThat((String) JsonPath.read(frodo.getContentAsString(), "$.firstName"), equalTo("Frodo")); assertNull(JsonPath.read(frodo.getContentAsString(), "$.lastName")); }
From source file:org.jasig.cas.support.oauth.web.OAuth20RevokeTokenControllerTests.java
@Test public void verifyNoToken() throws Exception { final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class); when(centralOAuthService.getToken(null)).thenThrow(new InvalidTokenException("error")); final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", CONTEXT + OAuthConstants.REVOKE_URL); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.setCentralOAuthService(centralOAuthService); oauth20WrapperController.afterPropertiesSet(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertNull(modelAndView);/* www . j a v a2 s . com*/ assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus()); assertEquals(CONTENT_TYPE, mockResponse.getContentType()); final ObjectMapper mapper = new ObjectMapper(); final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST + "\",\"error_description\":\"Invalid Token\"}"; final JsonNode expectedObj = mapper.readTree(expected); final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString()); assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText()); assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText()); }
From source file:org.jasig.cas.support.oauth.web.OAuth20WrapperControllerTests.java
@Test public void verifyInvalidGrantTypeForTokenCtrls() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", CONTEXT + OAuthConstants.TOKEN_URL); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); mockRequest.setParameter(OAuthConstants.GRANT_TYPE, "banana"); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(HttpStatus.SC_BAD_REQUEST, mockResponse.getStatus()); assertEquals("application/json", mockResponse.getContentType()); final ObjectMapper mapper = new ObjectMapper(); final String expected = "{\"error\":\"" + OAuthConstants.INVALID_REQUEST + "\",\"error_description\":\"" + new InvalidParameterException(OAuthConstants.GRANT_TYPE).getMessage() + "\"}"; final JsonNode expectedObj = mapper.readTree(expected); final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString()); assertEquals(expectedObj.get("error").asText(), receivedObj.get("error").asText()); assertEquals(expectedObj.get("error_description").asText(), receivedObj.get("error_description").asText()); }
From source file:alfio.controller.ReservationFlowIntegrationTest.java
private void checkCSV(String eventName, String ticketIdentifier, String fullName) throws IOException { //FIXME get all fields :D and put it in the request... Principal principal = Mockito.mock(Principal.class); Mockito.when(principal.getName()).thenReturn(user); MockHttpServletResponse response = new MockHttpServletResponse(); List<SerializablePair<String, String>> fields = eventApiController.getAllFields(eventName); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("fields", fields.stream().map(SerializablePair::getKey).toArray(String[]::new)); eventApiController.downloadAllTicketsCSV(eventName, request, response, principal); CSVReader csvReader = new CSVReader(new StringReader(response.getContentAsString())); List<String[]> csv = csvReader.readAll(); assertEquals(2, csv.size());//w ww . ja v a 2 s . co m assertEquals(ticketIdentifier, csv.get(1)[0]); assertEquals("default", csv.get(1)[2]); assertEquals("ACQUIRED", csv.get(1)[4]); assertEquals(fullName, csv.get(1)[10]); }