Java Code Examples for org.springframework.mock.web.server.MockServerWebExchange#from()

The following examples show how to use org.springframework.mock.web.server.MockServerWebExchange#from() . 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: CachingHttpHeadersFilterTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void cacheHeadersNotSetWhenPathDoesntMatch() {
    WebFilterChain filterChain = (filterExchange) -> {
        try {
            HttpHeaders headers = filterExchange.getResponse().getHeaders();
            assertThat(headers.getPragma()).isNull();
            assertThat(headers.getCacheControl()).isNull();;
            assertThat(headers.getExpires()).isEqualTo(-1);
        } catch (AssertionError ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    };
    MockServerWebExchange exchange = MockServerWebExchange.from(
        MockServerHttpRequest.get("/foo/foo")
    );
    this.filter.filter(exchange, filterChain).block();
}
 
Example 2
Source File: ApiVersionWebFilterTest.java    From spring-cloud-open-service-broker with Apache License 2.0 6 votes vote down vote up
private void setUpVersionResponse(String version) {
	MockServerHttpRequest request;
	if (version == null) {
		request = MockServerHttpRequest
				.get(V2_API_PATH_PATTERN)
				.build();
	}
	else {
		request = MockServerHttpRequest
				.get(V2_API_PATH_PATTERN)
				.header("header", version)
				.build();
	}
	this.exchange = MockServerWebExchange.from(request);
	MockitoAnnotations.initMocks(this);
	exchange.getResponse().setStatusCode(HttpStatus.OK);
	given(chain.filter(exchange))
			.willReturn(Mono.empty());
}
 
Example 3
Source File: RequestHeaderToRequestUriGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void filterChangeRequestUri() {
	RequestHeaderToRequestUriGatewayFilterFactory factory = new RequestHeaderToRequestUriGatewayFilterFactory();
	GatewayFilter filter = factory.apply(c -> c.setName("X-CF-Forwarded-Url"));
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.header("X-CF-Forwarded-Url", "https://example.com").build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR,
			URI.create("http://localhost"));
	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);
	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());
	filter.filter(exchange, filterChain);
	ServerWebExchange webExchange = captor.getValue();
	URI uri = (URI) webExchange.getAttributes().get(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).isNotNull();
	assertThat(uri.toString()).isEqualTo("https://example.com");
}
 
Example 4
Source File: RemoveRequestParameterGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void removeRequestParameterFilterShouldOnlyRemoveSpecifiedParam() {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.queryParam("foo", "bar").queryParam("abc", "xyz").build();
	exchange = MockServerWebExchange.from(request);
	NameConfig config = new NameConfig();
	config.setName("foo");
	GatewayFilter filter = new RemoveRequestParameterGatewayFilterFactory()
			.apply(config);

	filter.filter(exchange, filterChain);

	ServerHttpRequest actualRequest = captor.getValue().getRequest();
	assertThat(actualRequest.getQueryParams()).doesNotContainKey("foo");
	assertThat(actualRequest.getQueryParams()).containsEntry("abc",
			singletonList("xyz"));
}
 
Example 5
Source File: PrefixPathGatewayFilterFactoryTest.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private void testPrefixPathFilter(String prefix, String path, String expectedPath) {
	GatewayFilter filter = new PrefixPathGatewayFilterFactory()
			.apply(c -> c.setPrefix(prefix));
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost" + path).build();

	ServerWebExchange exchange = MockServerWebExchange.from(request);

	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);

	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());

	filter.filter(exchange, filterChain);

	ServerWebExchange webExchange = captor.getValue();

	assertThat(webExchange.getRequest().getURI()).hasPath(expectedPath);
	LinkedHashSet<URI> uris = webExchange
			.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
	assertThat(uris).contains(request.getURI());
}
 
Example 6
Source File: CookieCsrfFilterTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void cookieNotSetIfTokenInRequest() {
    WebFilterChain filterChain = (filterExchange) -> {
        try {
            assertThat(filterExchange.getResponse().getCookies().getFirst(CSRF_COOKIE_NAME)).isNull();
        } catch (AssertionError ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    };
    MockServerWebExchange exchange = MockServerWebExchange.from(
        MockServerHttpRequest
            .post(TEST_URL)
            .cookie(new HttpCookie(CSRF_COOKIE_NAME, "csrf_token"))
    );
    exchange.getAttributes().put(CsrfToken.class.getName(), Mono.just(new DefaultCsrfToken(CSRF_COOKIE_NAME, "_csrf", "some token")));
    this.filter.filter(exchange, filterChain).block();
}
 
Example 7
Source File: GatewayHttpTagsProviderTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void statusNotChanged() {
	ServerWebExchange exchange = MockServerWebExchange
			.from(MockServerHttpRequest.get(ROUTE_URI).build());

	Tags tags = tagsProvider.apply(exchange);
	assertThat(tags).isEqualTo(Tags.of("outcome", "CUSTOM", "status", "CUSTOM",
			"httpStatusCode", "NA", "httpMethod", "GET"));
}
 
Example 8
Source File: StripPrefixGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private void testStripPrefixFilter(String actualPath, String expectedPath,
		int parts) {
	GatewayFilter filter = new StripPrefixGatewayFilterFactory()
			.apply(c -> c.setParts(parts));

	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost" + actualPath).build();

	ServerWebExchange exchange = MockServerWebExchange.from(request);

	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);

	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());

	filter.filter(exchange, filterChain);

	ServerWebExchange webExchange = captor.getValue();

	assertThat(webExchange.getRequest().getURI()).hasPath(expectedPath);

	URI requestUrl = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(requestUrl).hasScheme("http").hasHost("localhost").hasNoPort()
			.hasPath(expectedPath);
	LinkedHashSet<URI> uris = webExchange
			.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
	assertThat(uris).contains(request.getURI());
}
 
Example 9
Source File: RequestIdentityWebFilterTest.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
@Test
void requestIdentityHeader() {
	MockServerHttpRequest request = MockServerHttpRequest
			.get(V2_API_PATH_PATTERN)
			.header(ServiceBrokerRequest.REQUEST_IDENTITY_HEADER, "request-id")
			.build();
	this.exchange = MockServerWebExchange.from(request);
	MockitoAnnotations.initMocks(this);
	given(chain.filter(exchange)).willReturn(Mono.empty());
	RequestIdentityWebFilter webFilter = new RequestIdentityWebFilter();
	webFilter.filter(exchange, chain).block();
	assertThat(exchange.getResponse().getHeaders().getFirst(ServiceBrokerRequest.REQUEST_IDENTITY_HEADER))
			.isEqualTo("request-id");
}
 
Example 10
Source File: SecureHeadersGatewayFilterFactoryUnitTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.build();
	exchange = MockServerWebExchange.from(request);
	filterChain = mock(GatewayFilterChain.class);
	captor = ArgumentCaptor.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());

}
 
Example 11
Source File: RewritePathGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private ServerWebExchange testRewriteFilter(String regex, String replacement,
		String actualPath, String expectedPath) {
	GatewayFilter filter = new RewritePathGatewayFilterFactory()
			.apply(c -> c.setRegexp(regex).setReplacement(replacement));

	URI url = UriComponentsBuilder.fromUriString("http://localhost" + actualPath)
			.build(true).toUri();
	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	ServerWebExchange exchange = MockServerWebExchange.from(request);

	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);

	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());

	filter.filter(exchange, filterChain);

	ServerWebExchange webExchange = captor.getValue();

	assertThat(webExchange.getRequest().getURI()).hasPath(expectedPath);

	URI requestUrl = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(requestUrl).hasScheme("http").hasHost("localhost").hasNoPort()
			.hasPath(expectedPath);
	LinkedHashSet<URI> uris = webExchange
			.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
	assertThat(uris).contains(request.getURI());

	return webExchange;
}
 
Example 12
Source File: TokenRelayGatewayFilterFactoryTests.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
	repository = mock(ServerOAuth2AuthorizedClientRepository.class);
	request = MockServerHttpRequest.get("/hello").build();
	mockExchange = MockServerWebExchange.from(request);
	filterChain = mock(GatewayFilterChain.class);
	when(filterChain.filter(any(ServerWebExchange.class))).thenReturn(Mono.empty());
	filter = new TokenRelayGatewayFilterFactory(repository).apply();
}
 
Example 13
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void routedPathInRequestPathButNotPrefix() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("https://originalhost:8080/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();
	filter.setPrefixAppend(true);
	filter.setPrefixEnabled(true);
	filter.setForEnabled(false);
	filter.setHostEnabled(false);
	filter.setPortEnabled(false);
	filter.setProtoEnabled(false);

	ServerWebExchange exchange = MockServerWebExchange.from(request);
	LinkedHashSet<URI> originalUris = new LinkedHashSet<>();
	originalUris.add(UriComponentsBuilder
			.fromUriString("https://originalhost:8080/one/two/three").build()
			.toUri());
	exchange.getAttributes().put(GATEWAY_ORIGINAL_REQUEST_URL_ATTR, originalUris);
	URI requestUri = UriComponentsBuilder
			.fromUriString("https://routedservice:8090/two").build().toUri();
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUri);

	HttpHeaders headers = filter.filter(request.getHeaders(), exchange);

	assertThat(headers).isEmpty();
}
 
Example 14
Source File: GatewayRouteTagsProviderTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void routeTags() {
	ServerWebExchange exchange = MockServerWebExchange
			.from(MockServerHttpRequest.get(ROUTE_URI).build());
	exchange.getAttributes().put(GATEWAY_ROUTE_ATTR, ROUTE);

	Tags tags = tagsProvider.apply(exchange);
	assertThat(tags).isEqualTo(DEFAULT_TAGS);
}
 
Example 15
Source File: SpringAdviceTraitTest.java    From problem-spring-web with MIT License 5 votes vote down vote up
@Test
void buildsOnThrowable() {
    final HttpStatusAdapter adapter = new HttpStatusAdapter(RESET_CONTENT);

    final MockServerWebExchange request = MockServerWebExchange.from(MockServerHttpRequest.get("/"));

    final ResponseEntity<Problem> result = unit.create(RESET_CONTENT,
            new IllegalStateException("Message"), request).block();

    assertThat(result, hasFeature("Status", ResponseEntity::getStatusCode, is(RESET_CONTENT)));
    assertThat(result.getHeaders(), hasFeature("Content-Type", HttpHeaders::getContentType, is(PROBLEM)));
    assertThat(result.getBody(), compose(hasFeature("Status", Problem::getStatus, is(adapter)))
            .and(hasFeature("Detail", Problem::getDetail, is("Message"))));
}
 
Example 16
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void prefixToInfer() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("https://originalhost:8080/prefix/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();
	filter.setPrefixAppend(true);
	filter.setPrefixEnabled(true);

	ServerWebExchange exchange = MockServerWebExchange.from(request);
	LinkedHashSet<URI> originalUris = new LinkedHashSet<>();
	originalUris.add(UriComponentsBuilder
			.fromUriString("https://originalhost:8080/prefix/get/").build().toUri()); // trailing
																						// slash
	exchange.getAttributes().put(GATEWAY_ORIGINAL_REQUEST_URL_ATTR, originalUris);
	URI requestUri = UriComponentsBuilder
			.fromUriString("https://routedservice:8090/get").build().toUri();
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUri);

	HttpHeaders headers = filter.filter(request.getHeaders(), exchange);

	assertThat(headers).containsKeys(X_FORWARDED_PREFIX_HEADER);

	assertThat(headers.getFirst(X_FORWARDED_PREFIX_HEADER)).isEqualTo("/prefix");
}
 
Example 17
Source File: CloudFoundryRouteServiceRoutePredicateFactoryTest.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void itReturnsFalseWithAHeadersMissing() {
	MockServerHttpRequest request = MockServerHttpRequest.get("someurl")
			.header(CloudFoundryRouteServiceRoutePredicateFactory.X_CF_FORWARDED_URL,
					"url")
			.header(CloudFoundryRouteServiceRoutePredicateFactory.X_CF_PROXY_METADATA,
					"metadata")
			.build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);

	assertThat(predicate.test(exchange)).isFalse();
}
 
Example 18
Source File: ReactiveLoadBalancerClientFilterTests.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() {
	properties = new LoadBalancerProperties();
	exchange = MockServerWebExchange
			.from(MockServerHttpRequest.get("/mypath").build());
}
 
Example 19
Source File: XForwardedRemoteAddressResolverTest.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
private ServerWebExchange buildExchange(
		MockServerHttpRequest.BaseBuilder requestBuilder) {
	return MockServerWebExchange.from(requestBuilder.build());
}
 
Example 20
Source File: BetweenRoutePredicateFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
static ServerWebExchange getExchange() {
	MockServerHttpRequest request = MockServerHttpRequest.get("https://example.com")
			.build();
	return MockServerWebExchange.from(request);
}