下面列出了org.mockito.verification.VerificationMode#org.springframework.mock.web.MockHttpServletResponse 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void test_contentType() throws Exception {
EasyMock.expect(mockService.testMethod("Whir?inaki")).andReturn("For?est");
EasyMock.replay(mockService);
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test-post");
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContentType("application/json");
request.setContent("{\"jsonrpc\":\"2.0\",\"id\":123,\"method\":\"testMethod\",\"params\":[\"Whir?inaki\"]}".getBytes(StandardCharsets.UTF_8));
jsonRpcServer.setContentType("flip/flop");
jsonRpcServer.handle(request, response);
assertTrue("flip/flop".equals(response.getContentType()));
checkSuccessfulResponse(response);
}
public static MockHttpServletResponse sendPut(MockMvc mockMvc,String uriWithParam,String requestJson){
MockHttpServletResponse mockResponse = null;
try {
mockResponse = mockMvc
.perform(
put(uriWithParam, ConstantsForTest.JSON)
.characterEncoding(ConstantsForTest.UTF8)
.contentType(MediaType.APPLICATION_JSON)
.content(requestJson)
)
.andReturn()
.getResponse();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mockResponse;
}
@Test
public void testHttpHeaderAuthenticationFilterMultipleRoles() throws Exception
{
modifyPropertySourceInEnvironment(getDefaultSecurityEnvironmentVariables());
try
{
MockHttpServletRequest request =
getRequestWithHeaders(USER_ID, "testFirstName", "testLastName", "testEmail", "testRole1,testRole2", "Wed, 11 Mar 2015 10:24:09");
// Invalidate user session if exists.
invalidateApplicationUser(request);
httpHeaderAuthenticationFilter.init(new MockFilterConfig());
httpHeaderAuthenticationFilter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
Set<String> expectedRoles = new HashSet<>();
expectedRoles.add("testRole1");
expectedRoles.add("testRole2");
validateHttpHeaderApplicationUser(USER_ID, "testFirstName", "testLastName", "testEmail", expectedRoles, "Wed, 11 Mar 2015 10:24:09", null, null);
}
finally
{
restorePropertySourceInEnvironment();
}
}
@Test
public final void testProcessCancel() {
try {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
DefaultCommand comm = new DefaultCommand();
comm.setMode(DefaultCommand.MODE_EDIT);
Tab currTab = testInstance.getTabConfig().getTabs().get(0);
assertTrue(currTab != null);
BindException aError = new BindException(new DefaultSiteCommand(),
null);
ModelAndView mav = testInstance.processCancel(currTab, request,
response, comm, aError);
assertTrue(mav != null);
assertTrue(mav.getViewName().equals(
"redirect:/curator/groups/search.html"));
} catch (Exception e) {
String message = e.getClass().toString() + " - " + e.getMessage();
log.debug(message);
fail(message);
}
}
/**
* The PageList is displayed when the webResource is a Site instance.
* When the request has no TgolKeyStore.STATUS_KEY parameter set,
* the page that lists the number of page by Http Status Code has to be
* returned
*
* @throws Exception
*/
public void testDisplayPageList() throws Exception {
System.out.println("testDisplayPageList");
setUpMockAuditDataService(SITE_AUDIT_GENERAL_PAGE_LIST_ID);
setUpMockUserDataService();
setUpActDataService(true);
setUpMockAuthenticationContext();
setUpAuditStatisticsFactory();
List<String> authorizedScopeForPageList = new ArrayList();
authorizedScopeForPageList.add("DOMAIN");
instance.setAuthorizedScopeForPageList(authorizedScopeForPageList);
HttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();
String expResult = TgolKeyStore.PAGE_LIST_VIEW_NAME;
request.addParameter(TgolKeyStore.AUDIT_ID_KEY, String.valueOf(SITE_AUDIT_GENERAL_PAGE_LIST_ID));
String result = instance.displayPageList(request, response, new ExtendedModelMap());
assertEquals(expResult, result);
}
@Test
public void createJsonFileFromSwaggerEndpoint() throws Exception {
String outputDir = Optional.ofNullable(System.getProperty("io.springfox.staticdocs.outputDir"))
.orElse("build/swagger");
System.err.println(outputDir);
MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String swaggerJson = response.getContentAsString();
Files.createDirectories(Paths.get(outputDir));
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"),
StandardCharsets.UTF_8)) {
writer.write(swaggerJson);
}
}
@Test
public void createSpringfoxSwaggerJson() throws Exception{
String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String swaggerJson = response.getContentAsString();
Files.createDirectories(Paths.get(outputDir));
try(BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
writer.write(swaggerJson);
}
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withGeneratedExamples()
.withInterDocumentCrossReferences()
.build();
Swagger2MarkupConverter.from(Paths.get(outputDir,"swagger.json"))
.withConfig(config)
.build()
.toFile(Paths.get(outputDir, "swagger"));
}
@Test
public void testHttpHeaderAuthenticationFilterNoRoles() throws Exception
{
modifyPropertySourceInEnvironment(getDefaultSecurityEnvironmentVariables());
try
{
MockHttpServletRequest request = getRequestWithHeaders(USER_ID, "testFirstName", "testLastName", "testEmail", null, "Wed, 11 Mar 2015 10:24:09");
// Invalidate user session if exists.
invalidateApplicationUser(request);
httpHeaderAuthenticationFilter.init(new MockFilterConfig());
httpHeaderAuthenticationFilter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain());
validateHttpHeaderApplicationUser(USER_ID, "testFirstName", "testLastName", "testEmail", (String) null, "Wed, 11 Mar 2015 10:24:09", null, null);
}
finally
{
restorePropertySourceInEnvironment();
}
}
@Test
public void testJWTFilterWrongScheme() throws Exception {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
"test-user",
"test-password",
Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
);
String jwt = tokenProvider.createToken(authentication, false);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt);
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void testFailedAuthenticationWithNoService() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockRequestContext context = new MockRequestContext();
request.addParameter("username", "test");
request.addParameter("password", "test2");
context.setExternalContext(new ServletExternalContext(
new MockServletContext(), request, new MockHttpServletResponse()));
context.getRequestScope().put("credentials",
TestUtils.getCredentialsWithDifferentUsernameAndPassword());
context.getRequestScope().put(
"org.springframework.validation.BindException.credentials",
new BindException(TestUtils
.getCredentialsWithDifferentUsernameAndPassword(),
"credentials"));
// this.action.bind(context);
// assertEquals("error", this.action.submit(context).getId());
}
@Test
public void testShowForm() {
//boolean result;
try {
assertTrue(tc!=null);
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
req.addParameter("_tab_edit", "_tab_edit");
req.addParameter("_tab_current_page","1");
TabbedModelAndView tmav = (TabbedModelAndView)tc.processFormSubmission(req, res, null, null);
assertTrue(methodsCalled.get(0) == "TabbedController.switchToEditMode");
assertTrue(methodsCalled.get(1) == "TabHandler.preProcessNextTab");
assertTrue(tmav.getTabStatus().getCurrentTab().getPageId() == "1");
}
catch (Exception e)
{
String message = e.getClass().toString() + " - " + e.getMessage();
log.debug(message);
fail(message);
}
}
@Test
public void testRequestNewVersionsOfArtifact()
throws Exception
{
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI( "/feeds/org/apache/archiva/artifact-two" );
request.addHeader( "User-Agent", "Apache Archiva unit test" );
request.setMethod( "GET" );
//WebRequest request = new GetMethodWebRequest( "http://localhost/feeds/org/apache/archiva/artifact-two" );
Base64 encoder = new Base64( 0, new byte[0] );
String userPass = "user1:password1";
String encodedUserPass = encoder.encodeToString( userPass.getBytes() );
request.addHeader( "Authorization", "BASIC " + encodedUserPass );
MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
rssFeedServlet.doGet( request, mockHttpServletResponse );
assertEquals( RssFeedServlet.MIME_TYPE, mockHttpServletResponse.getHeader( "CONTENT-TYPE" ) );
assertNotNull( "Should have recieved a response", mockHttpServletResponse.getContentAsString() );
assertEquals( "Should have been an OK response code.", HttpServletResponse.SC_OK,
mockHttpServletResponse.getStatus() );
}
@Test
public void verifyDeleteService() throws Exception {
final RegisteredServiceImpl r = new RegisteredServiceImpl();
r.setId(1200);
r.setName("name");
r.setServiceId("serviceId");
r.setEvaluationOrder(1);
this.servicesManager.save(r);
final MockHttpServletResponse response = new MockHttpServletResponse();
this.controller.manage(response);
this.controller.deleteRegisteredService(1200, response);
assertNull(this.servicesManager.findServiceBy(1200));
assertTrue(response.getContentAsString().contains("serviceName"));
}
@Test
public void shouldInitializeFlashIfNotPresent() throws IOException, ServletException {
MockHttpServletRequest req = new MockHttpServletRequest();
MockHttpServletResponse res = new MockHttpServletResponse();
FilterChain filterChain = new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response) {
messageKey = service.add(new FlashMessageModel("my message", "error"));
flash = service.get(messageKey);
}
};
assertThat(messageKey, is(nullValue()));
filter.doFilter(req, res, filterChain);
assertThat(messageKey, not(nullValue()));
assertThat(flash.toString(), is("my message"));
assertThat(flash.getFlashClass(), is("error"));
}
@Test
public void testTrustedUserFilterNoSpel() throws Exception
{
// Override configuration.
Map<String, Object> overrideMap = new HashMap<>();
overrideMap.put(ConfigurationValue.SECURITY_ENABLED_SPEL_EXPRESSION.getKey(), "");
modifyPropertySourceInEnvironment(overrideMap);
try
{
// Invalidate user session if exists.
invalidateApplicationUser(null);
trustedUserAuthenticationFilter.init(new MockFilterConfig());
trustedUserAuthenticationFilter.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse(), new MockFilterChain());
assertNoUserInContext();
}
finally
{
// Restore the property sources so we don't affect other tests.
restorePropertySourceInEnvironment();
}
}
@Test
public void testValidServiceTicketWithInsecurePgtUrl() throws Exception {
this.serviceValidateController.setProxyHandler(new Cas10ProxyHandler());
final String tId = getCentralAuthenticationService()
.createTicketGrantingTicket(TestUtils.getCredentialsWithSameUsernameAndPassword());
final String sId = getCentralAuthenticationService().grantServiceTicket(tId, TestUtils.getService());
final MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("service", TestUtils.getService().getId());
request.addParameter("ticket", sId);
request.addParameter("pgtUrl", "http://www.github.com");
final ModelAndView modelAndView = this.serviceValidateController
.handleRequestInternal(request, new MockHttpServletResponse());
assertEquals(ServiceValidateController.DEFAULT_SERVICE_FAILURE_VIEW_NAME, modelAndView.getViewName());
}
@Test
public void testGetMethod_unencodedParams() throws Exception {
EasyMock.expect(mockService.testMethod("Whir?inaki")).andReturn("For?est");
EasyMock.replay(mockService);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test-get");
MockHttpServletResponse response = new MockHttpServletResponse();
request.addParameter("id", Integer.toString(123));
request.addParameter("method", "testMethod");
request.addParameter("params", "[\"Whir?inaki\"]");
jsonRpcServer.handle(request, response);
assertTrue("application/json-rpc".equals(response.getContentType()));
checkSuccessfulResponse(response);
}
@Test
public final void testShowForm() {
try
{
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
DefaultSiteCommand comm = new DefaultSiteCommand();
comm.setEditMode(true);
comm.setSiteOid(null);
BindException aError = new BindException(new DefaultSiteCommand(), null);
ModelAndView mav = testInstance.showForm(request, response, comm, aError);
assertTrue(mav != null);
assertTrue(mav.getViewName().equals("site"));
SiteEditorContext context = testInstance.getEditorContext(request);
assertSame(context.getSite().getOwningAgency(), AuthUtil.getRemoteUserObject().getAgency());
}
catch (Exception e)
{
String message = e.getClass().toString() + " - " + e.getMessage();
log.debug(message);
fail(message);
}
}
@Test
public void testPrettyPrint() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
ServletResponseResultWriter writer = new ServletResponseResultWriter(response, null,
true /* prettyPrint */, true /* addContentLength */);
writer.write(ImmutableMap.of("one", "two", "three", "four"));
// If the response is pretty printed, there should be at least two newlines.
String body = response.getContentAsString();
int index = body.indexOf('\n');
assertThat(index).isAtLeast(0);
index = body.indexOf('\n', index + 1);
assertThat(index).isAtLeast(0);
// Unlike the Jackson pretty printer, which will either put no space around a colon or a space
// on both sides, we want to ensure that a space comes after a colon, but not before.
assertThat(body).contains("\": ");
assertThat(body).doesNotContain("\" :");
}
@Test
public void createSpringfoxSwaggerJson() throws Exception{
String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String swaggerJson = response.getContentAsString();
Files.createDirectories(Paths.get(outputDir));
try(BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)){
writer.write(swaggerJson);
}
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withGeneratedExamples()
.withInterDocumentCrossReferences()
.build();
Swagger2MarkupConverter.from(Paths.get(outputDir,"swagger.json"))
.withConfig(config)
.build()
.toFile(Paths.get(outputDir, "swagger"));
}
protected String service(HttpServletRequest request) throws ServletException, IOException {
try {
MockHttpServletResponse response = new MockHttpServletResponse();
ApiListenerServlet servlet = servlets.get();
assertNotNull("Servlet cannot be found!??", servlet);
servlet.service(request, response);
return response.getContentAsString();
} catch (Throwable t) {
//Silly hack to try and make the error visible in Travis.
assertTrue(ExceptionUtils.getStackTrace(t), false);
}
//This should never happen because of the assertTrue(false) statement in the catch cause.
return null;
}
@Test
public void verifyRenewWithServiceAndBadCredentials() throws Exception {
final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword();
final TicketGrantingTicket ticketGrantingTicket = getCentralAuthenticationService().createTicketGrantingTicket(c);
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockRequestContext context = new MockRequestContext();
WebUtils.putTicketGrantingTicketInScopes(context, ticketGrantingTicket);
request.addParameter("renew", "true");
request.addParameter("service", "test");
final Credential c2 = TestUtils.getCredentialsWithDifferentUsernameAndPassword();
context.setExternalContext(new ServletExternalContext(
new MockServletContext(), request, new MockHttpServletResponse()));
putCredentialInRequestScope(context, c2);
context.getRequestScope().put(
"org.springframework.validation.BindException.credentials",
new BindException(c2, "credentials"));
final MessageContext messageContext = mock(MessageContext.class);
assertEquals("error", this.action.submit(context, c2, messageContext).getId());
}
@Test
public void run_on_valid_response() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
RequestContext context = RequestContext.getCurrentContext();
context.setRequest(request);
MockHttpServletResponse response = new MockHttpServletResponse();
context.setResponseGZipped(false);
context.setResponse(response);
InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}", StandardCharsets.UTF_8);
context.setResponseDataStream(in);
filter.run();
assertEquals("UTF-8", response.getCharacterEncoding());
assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
@Test
public void run_on_valid_response() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service1" + DEFAULT_URL);
RequestContext context = RequestContext.getCurrentContext();
context.setRequest(request);
MockHttpServletResponse response = new MockHttpServletResponse();
context.setResponseGZipped(false);
context.setResponse(response);
InputStream in = IOUtils.toInputStream("{\"basePath\":\"/\"}", StandardCharsets.UTF_8);
context.setResponseDataStream(in);
filter.run();
assertEquals("UTF-8", response.getCharacterEncoding());
assertEquals("{\"basePath\":\"/service1\"}", context.getResponseBody());
}
@Test
public void testSuccessfulAuthenticationWithServiceAndWarn()
throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest();
final MockHttpServletResponse response = new MockHttpServletResponse();
final MockRequestContext context = new MockRequestContext();
request.addParameter("username", "test");
request.addParameter("password", "test");
request.addParameter("warn", "true");
request.addParameter("service", "test");
context.setExternalContext(new ServletExternalContext(
new MockServletContext(), request, response));
context.getRequestScope().put("credentials",
TestUtils.getCredentialsWithSameUsernameAndPassword());
// this.action.bind(context);
// assertEquals("success", this.action.submit(context).getId());
// assertNotNull(response.getCookie(this.warnCookieGenerator
// .getCookieName()));
}
@Test
public void testJWTFilterInvalidToken() throws Exception {
String jwt = "wrong_jwt";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
void exceptionCapturingShouldNotContainUserInformationRecordedOnTheTransactionAfterTheErrorWasCaptured() throws IOException, ServletException {
filterChain = new MockFilterChain(new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
tracer.getActive().captureException(new RuntimeException("Test exception capturing"));
tracer.currentTransaction().setUser("id", "email", "username");
}
});
filterChain.doFilter(new MockHttpServletRequest("GET", "/foo"), new MockHttpServletResponse());
assertThat(reporter.getTransactions()).hasSize(1);
assertThat(reporter.getErrors()).hasSize(1);
assertThat(reporter.getFirstError().getContext().getUser().hasContent()).isFalse();
}
public static MockRequestContext getContext(
final MockHttpServletRequest request,
final MockHttpServletResponse response) {
final MockRequestContext context = new MockRequestContext();
context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));
return context;
}
@Test
public void fetchAllInvestors() throws Exception{
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/investors").accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
System.out.println("here "+response);
}
@Test
public void testRasterizeFromCache() throws Exception {
InternalTile tile;
// create metadata
GetVectorTileRequest metadata = new GetVectorTileRequest();
metadata.setCode(new TileCode(4, 8, 8));
metadata.setCrs("EPSG:4326");
metadata.setLayerId(layerBeans.getId());
metadata.setPanOrigin(new Coordinate(0, 0));
metadata.setScale(16);
metadata.setRenderer(TileMetadata.PARAM_SVG_RENDERER);
metadata.setStyleInfo(layerBeansStyleInfo);
metadata.setPaintLabels(false);
metadata.setPaintGeometries(true);
// get tile
recorder.clear();
tile = vectorLayerService.getTile(metadata);
Assert.assertEquals("", recorder.matches(CacheCategory.RASTER));
// find the key
String url = tile.getFeatureContent();
Assert.assertTrue(url.startsWith("http://test/rasterizing/layer/beans/"));
Assert.assertTrue(url.contains("?"));
String key = url.substring("http://test/rasterizing/layer/beans/".length(), url.indexOf(".png"));
Object o = cacheManager.get(layerBeans, CacheCategory.REBUILD, key);
Assert.assertNotNull("Missing rebuild data in cache", o);
MockHttpServletResponse response = new MockHttpServletResponse();
recorder.clear();
controller.getImage(layerBeans.getId(), key, response);
Assert.assertEquals("", recorder.matches(CacheCategory.RASTER, "Rasterization success", "Put item in cache"));
new ServletResponseAssert(response).assertEqualImage("beans-4-8-8.png", writeImages, DELTA);
cacheManager.drop(layerBeans);
}