Java Code Examples for org.springframework.mock.web.MockHttpServletRequest#setRequestURI()

The following examples show how to use org.springframework.mock.web.MockHttpServletRequest#setRequestURI() . 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: RestControllerTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testFeaturePaging() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setRequestURI("/rest/beans");
	request.setMethod("GET");
	MockHttpServletResponse response = new MockHttpServletResponse();
	// check all
	ModelAndView mav = adapter.handle(request, response, restController);
	Assert.assertEquals(Arrays.asList("1", "2", "3"), getIdsFromModel(mav.getModel()));
	// check first 1
	request.setParameter("maxFeatures", "1");
	mav = adapter.handle(request, response, restController);
	Assert.assertEquals(Arrays.asList("1"), getIdsFromModel(mav.getModel()));
	// check first 2
	request.setParameter("maxFeatures", "2");
	mav = adapter.handle(request, response, restController);
	Assert.assertEquals(Arrays.asList("1", "2"), getIdsFromModel(mav.getModel()));
	// check 1 -3
	request.setParameter("maxFeatures", "2");
	request.setParameter("offset", "1");
	mav = adapter.handle(request, response, restController);
	Assert.assertEquals(Arrays.asList("2", "3"), getIdsFromModel(mav.getModel()));
}
 
Example 2
Source File: SampleKatharsisServletTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testKatharsisIncludeWithNullIterableRelationshipCall() throws Exception {
	Node root = new Node(1L, null, null);
	// by making the setting children null and requesting them in the include statement should cause a serialization error
	Node child1 = new Node(2L, root, null);
	Node child2 = new Node(3L, root, null);
	root.setChildren(new LinkedHashSet<>(Arrays.asList(child1, child2)));
	nodeRepository.save(root);
	nodeRepository.save(child1);
	nodeRepository.save(child2);
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setServletPath("/api");
	request.setPathInfo("/nodes");
	request.setRequestURI("/api/nodes");
	request.setQueryString("include[nodes]=children");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	Map<String, String> params = new HashMap<>();
	params.put("include[nodes]", "children");
	request.setParameters(params);
	request.addHeader("Accept", "*/*");
	MockHttpServletResponse response = new MockHttpServletResponse();
	katharsisServlet.service(request, response);
	assertEquals(500, response.getStatus());
}
 
Example 3
Source File: UnauthorizedHandlerTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCommence() throws IOException, ServletException {
    UnauthorizedHandler unauthorizedHandler = new UnauthorizedHandler(new AuthExceptionHandler(messageService, objectMapper));

    MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setRequestURI("URI");

    MockHttpServletResponse httpServletResponse = new MockHttpServletResponse();

    unauthorizedHandler.commence(httpServletRequest, httpServletResponse, new TokenExpireException("ERROR"));

    assertEquals(HttpStatus.UNAUTHORIZED.value(), httpServletResponse.getStatus());

    Message message = messageService.createMessage(
        ErrorType.TOKEN_EXPIRED.getErrorMessageKey(),
        httpServletRequest.getRequestURI());
    verify(objectMapper).writeValue(httpServletResponse.getWriter(), message.mapToView());
}
 
Example 4
Source File: JWTFilterTest.java    From e-commerce-microservice with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 5
Source File: RestControllerTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testBboxFilter() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setRequestURI("/rest/beans");
	request.addParameter("bbox", "4,6,0,3");
	request.setMethod("GET");

	MockHttpServletResponse response = new MockHttpServletResponse();
	ModelAndView mav = adapter.handle(request, response, restController);
	Object o = mav.getModel().get(RestController.FEATURE_COLLECTION);
	Assert.assertTrue(o instanceof List<?>);
	for (Object f : (List<?>) o) {
		Assert.assertTrue(f instanceof InternalFeature);
		Assert.assertTrue(new Envelope(4, 6, 0, 3).intersects(((InternalFeature) f).getGeometry()
				.getEnvelopeInternal()));
	}

}
 
Example 6
Source File: ServletRequestContextTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testBaseUrlForInvalidServletPath() {
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("/api/tasks/"); // invalid => Spring Boot setup as it seems
	request.setPathInfo(null);
	request.setRequestURI("/api/tasks/");
	request.setContentType(HttpHeaders.JSONAPI_CONTENT_TYPE);
	request.setServerName("test");
	request.setServerPort(1234);

	ServletRequestContext context = new ServletRequestContext(servletContext, request, servletResponse, "/api");

	Assert.assertEquals("http://test:1234/api", context.getBaseUrl());
	Assert.assertEquals("/tasks/", context.getPath());
}
 
Example 7
Source File: BaseControllerTest.java    From Kylin with Apache License 2.0 6 votes vote down vote up
@Test
public void testBasics() throws IOException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("http://localhost");

    NotFoundException notFoundException = new NotFoundException("not found");
    ErrorResponse errorResponse = basicController.handleBadRequest(request, notFoundException);
    Assert.assertNotNull(errorResponse);

    ForbiddenException forbiddenException = new ForbiddenException("forbidden");
    errorResponse = basicController.handleForbidden(request, forbiddenException);
    Assert.assertNotNull(errorResponse);

    InternalErrorException internalErrorException = new InternalErrorException("error");
    errorResponse = basicController.handleError(request, internalErrorException);
    Assert.assertNotNull(errorResponse);

    BadRequestException badRequestException = new BadRequestException("error");
    errorResponse = basicController.handleBadRequest(request, badRequestException);
    Assert.assertNotNull(errorResponse);
}
 
Example 8
Source File: CrnkFilterTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void onNonRepositoryRequestShouldPassTrough() throws Exception {
    MockFilterChain filterChain = new MockFilterChain();

    MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    request.setMethod("GET");
    request.setContextPath("");
    request.setServletPath("/api");
    request.setPathInfo(null);
    request.setRequestURI("/api/somethingDifferent/");
    request.addHeader("Accept", "*/*");

    MockHttpServletResponse response = new MockHttpServletResponse();

    filter.doFilter(request, response, filterChain);

    // no content set yet
    Assert.assertEquals(0, response.getContentLength());
}
 
Example 9
Source File: SampleKatharsisServletTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnacceptableRequestContentType() throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath("/api");
	request.setPathInfo("/tasks");
	request.setRequestURI("/api/tasks");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	request.addHeader("Accept", "application/xml");
	request.addParameter("filter[Task][name]", "John");
	request.setQueryString(URLEncoder.encode("filter[Task][name]", StandardCharsets.UTF_8.name()) + "=John");

	MockHttpServletResponse response = new MockHttpServletResponse();

	katharsisServlet.service(request, response);

	assertEquals(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, response.getStatus());
	String responseContent = response.getContentAsString();
	assertTrue(responseContent == null || "".equals(responseContent.trim()));
}
 
Example 10
Source File: HttpMockServiceImpl.java    From AnyMock with Apache License 2.0 6 votes vote down vote up
private MockHttpServletRequest buildMockRequest(HttpServletRequest request) {
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setParameters(request.getParameterMap());

    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String)headerNames.nextElement();
        mockRequest.addHeader(key, request.getHeader(key));
    }

    mockRequest.setMethod(request.getMethod());
    mockRequest.setRequestURI(request.getRequestURI());
    mockRequest.setRemoteAddr(request.getRemoteAddr());
    mockRequest.setRemoteHost(request.getRemoteHost());
    mockRequest.setRemotePort(request.getRemotePort());
    mockRequest.setRemoteUser(request.getRemoteUser());
    mockRequest.setAttribute(BODY, request.getAttribute(BODY));
    return mockRequest;
}
 
Example 11
Source File: OptionsEndpointFilterTest.java    From webauthn4j-spring-security with Apache License 2.0 6 votes vote down vote up
@Test
public void doFilter_test() throws IOException, ServletException {
    OptionsProvider optionsProvider = mock(OptionsProvider.class);
    AttestationOptions attestationOptions = new AttestationOptions(null, null, null, null, null, Collections.emptyList(), null);
    when(optionsProvider.getAttestationOptions(any(), any(), any())).thenReturn(attestationOptions);
    AssertionOptions assertionOptions = new AssertionOptions(null, null, null, null, null, null);
    when(optionsProvider.getAssertionOptions(any(), any(), any())).thenReturn(assertionOptions);
    OptionsEndpointFilter optionsEndpointFilter = new OptionsEndpointFilter(optionsProvider, objectConverter);
    AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
    optionsEndpointFilter.setTrustResolver(trustResolver);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI(OptionsEndpointFilter.FILTER_URL);
    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain filterChain = new MockFilterChain();

    optionsEndpointFilter.doFilter(request, response, filterChain);
    assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
}
 
Example 12
Source File: SlashFilterTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldNotFilterAPI() throws Exception {
    final RequestContext ctx = RequestContext.getCurrentContext();
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setRequestURI("/api/v1/service");
    ctx.set(PROXY_KEY, "api/v1/service");
    ctx.setRequest(mockRequest);
    assertEquals(false, this.filter.shouldFilter());
}
 
Example 13
Source File: FlowExecutionExceptionResolverTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void verifyNoSuchFlowExecutionExeptionWithQueryString() {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("test");
    request.setQueryString("test=test");
    ModelAndView model = this.resolver.resolveException(request,
            new MockHttpServletResponse(), null,
            new NoSuchFlowExecutionException(new FlowExecutionKey(){

                private static final long serialVersionUID = -4750073902540974152L;

                @Override
                public String toString() {
                    return "test";
                }

                @Override
                public boolean equals(final Object o) {
                    return true;
                }

                @Override
                public int hashCode() {
                    return 0;
                }
            }, new RuntimeException()));

    assertEquals(request.getRequestURI() + "?" + request.getQueryString(), ((RedirectView) model.getView())
            .getUrl());
}
 
Example 14
Source File: ResponseLinksMapperTest.java    From moserp with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(){
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setRequestURI("/api/products");
    servletRequest.setServerPort(8080);
    RequestContextHolder.setRequestAttributes(new ServletWebRequest(servletRequest));
}
 
Example 15
Source File: KatharsisFilterTest.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void onSimpleCollectionGetShouldReturnCollectionOfResources() throws Exception {
	MockFilterChain filterChain = new MockFilterChain();

	MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
	request.setMethod("GET");
	request.setContextPath("");
	request.setServletPath(null);
	request.setPathInfo(null);
	request.setRequestURI("/api/tasks/");
	request.setContentType(JsonApiMediaType.APPLICATION_JSON_API);
	request.addHeader("Accept", "*/*");

	MockHttpServletResponse response = new MockHttpServletResponse();

	katharsisFilter.doFilter(request, response, filterChain);

	String responseContent = response.getContentAsString();

	log.debug("responseContent: {}", responseContent);
	assertNotNull(responseContent);

	assertJsonPartEquals("tasks", responseContent, "data[0].type");
	assertJsonPartEquals("\"1\"", responseContent, "data[0].id");
	assertJsonPartEquals(FIRST_TASK_ATTRIBUTES, responseContent, "data[0].attributes");
	assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data[0].links");
	assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data[0].relationships.project.links");
}
 
Example 16
Source File: JWTFilterTest.java    From ehcache3-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void testJWTFilterMissingAuthorization() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    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();
}
 
Example 17
Source File: JWTFilterTest.java    From alchemy with Apache License 2.0 5 votes vote down vote up
@Test
public void testJWTFilterMissingToken() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer ");
    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();
}
 
Example 18
Source File: DomainValidateFilterTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
public void testShutDownValidationProcess() throws Exception {
    MockHttpServletRequest request = getMockedRequest("error.domain");

    MockHttpServletResponse response = execute(request);
    Assert.assertEquals(BAD_REQUEST_CODE, response.getStatus());

    request = getMockedRequest("127.0.0.1:8080");
    request.setRequestURI(STOP_CHECK_URI);
    execute(request);

    request = getMockedRequest("error.domain");
    response = execute(request);
    Assert.assertEquals(200, response.getStatus());
}
 
Example 19
Source File: JWTFilterTest.java    From flair-engine with Apache License 2.0 5 votes vote down vote up
@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(JWTConfigurer.AUTHORIZATION_HEADER, "Basic " + jwt);
    request.setRequestURI("/api/test");
}
 
Example 20
Source File: RestControllerTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testWrongFeatureId() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setRequestURI("/rest/beans/200.json");
	request.setMethod("GET");
	MockHttpServletResponse response = new MockHttpServletResponse();
	try {
		adapter.handle(request, response, restController);
		Assert.fail("feature 200 should not exist");
	} catch (Exception e) {
		Assert.assertTrue(e instanceof RestException);
		Assert.assertEquals(RestException.FEATURE_NOT_FOUND, ((RestException) e).getExceptionCode());
	}
}