org.springframework.mock.http.server.reactive.MockServerHttpRequest Java Examples

The following examples show how to use org.springframework.mock.http.server.reactive.MockServerHttpRequest. 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: RequestHeaderToRequestUriGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 7 votes vote down vote up
@Test
public void filterDoesNotChangeRequestUriIfHeaderIsInvalid() throws Exception {
	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", "example").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.toURL().toString()).isEqualTo("http://localhost");
}
 
Example #2
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 #3
Source File: ReactiveLoadBalancerClientFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void encodedParameters() {
	URI url = UriComponentsBuilder.fromUriString("http://localhost/get?a=b&c=d[]")
			.buildAndExpand().encode().toUri();

	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	URI lbUrl = UriComponentsBuilder.fromUriString("lb://service1?a=b&c=d[]")
			.buildAndExpand().encode().toUri();

	// prove that it is encoded
	assertThat(lbUrl.getRawQuery()).isEqualTo("a=b&c=d%5B%5D");

	assertThat(lbUrl).hasParameter("c", "d[]");

	ServerWebExchange webExchange = testFilter(request, lbUrl);
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("service1-host1").hasParameter("a", "b")
			.hasParameter("c", "d[]");

	// prove that it is not double encoded
	assertThat(uri.getRawQuery()).isEqualTo("a=b&c=d%5B%5D");
}
 
Example #4
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void defaultPort() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.header(HttpHeaders.HOST, "myhost").build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers).containsKeys(X_FORWARDED_FOR_HEADER, X_FORWARDED_HOST_HEADER,
			X_FORWARDED_PORT_HEADER, X_FORWARDED_PROTO_HEADER);

	assertThat(headers.getFirst(X_FORWARDED_FOR_HEADER)).isEqualTo("10.0.0.1");
	assertThat(headers.getFirst(X_FORWARDED_HOST_HEADER)).isEqualTo("localhost");
	assertThat(headers.getFirst(X_FORWARDED_PORT_HEADER)).isEqualTo("80");
	assertThat(headers.getFirst(X_FORWARDED_PROTO_HEADER)).isEqualTo("http");
}
 
Example #5
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void appendsValues() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost:8080/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.header(X_FORWARDED_FOR_HEADER, "192.168.0.2")
			.header(X_FORWARDED_HOST_HEADER, "example.com")
			.header(X_FORWARDED_PORT_HEADER, "443")
			.header(X_FORWARDED_PROTO_HEADER, "https").build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers).containsKeys(X_FORWARDED_FOR_HEADER, X_FORWARDED_HOST_HEADER,
			X_FORWARDED_PORT_HEADER, X_FORWARDED_PROTO_HEADER);

	assertThat(headers.getFirst(X_FORWARDED_FOR_HEADER))
			.isEqualTo("192.168.0.2,10.0.0.1");
	assertThat(headers.getFirst(X_FORWARDED_HOST_HEADER))
			.isEqualTo("example.com,localhost:8080");
	assertThat(headers.getFirst(X_FORWARDED_PORT_HEADER)).isEqualTo("443,8080");
	assertThat(headers.getFirst(X_FORWARDED_PROTO_HEADER)).isEqualTo("https,http");
}
 
Example #6
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void prefixAddedWithoutTrailingSlash() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("https://originalhost:8080/foo/bar")
			.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/foo/bar").build().toUri());
	exchange.getAttributes().put(GATEWAY_ORIGINAL_REQUEST_URL_ATTR, originalUris);
	URI requestUri = UriComponentsBuilder.fromUriString("https://routedservice:8090/")
			.build().toUri();
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUri);

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

	assertThat(headers.getFirst(X_FORWARDED_PREFIX_HEADER)).isEqualTo("/foo/bar");
}
 
Example #7
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 #8
Source File: ForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void unresolvedRemoteAddressFallsBackToHostName() throws UnknownHostException {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost/get")
			.remoteAddress(
					InetSocketAddress.createUnresolved("unresolvable-hostname", 80))
			.build();

	ForwardedHeadersFilter filter = new ForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers.get(FORWARDED_HEADER)).hasSize(1);

	List<Forwarded> forwardeds = ForwardedHeadersFilter
			.parse(headers.get(FORWARDED_HEADER));

	assertThat(forwardeds).hasSize(1);
	Forwarded forwarded = forwardeds.get(0);

	assertThat(forwarded.getValues()).containsEntry("proto", "http")
			.containsEntry("for", "\"unresolvable-hostname:80\"");
}
 
Example #9
Source File: XForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void xForwardedHeadersDoNotExist() throws Exception {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost:8080/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.header(HttpHeaders.HOST, "myhost").build();

	XForwardedHeadersFilter filter = new XForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers).containsKeys(X_FORWARDED_FOR_HEADER, X_FORWARDED_HOST_HEADER,
			X_FORWARDED_PORT_HEADER, X_FORWARDED_PROTO_HEADER);

	assertThat(headers.getFirst(X_FORWARDED_FOR_HEADER)).isEqualTo("10.0.0.1");
	assertThat(headers.getFirst(X_FORWARDED_HOST_HEADER)).isEqualTo("localhost:8080");
	assertThat(headers.getFirst(X_FORWARDED_PORT_HEADER)).isEqualTo("8080");
	assertThat(headers.getFirst(X_FORWARDED_PROTO_HEADER)).isEqualTo("http");
}
 
Example #10
Source File: RouteToRequestUrlFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void unencodedParameters() {
	URI url = URI.create("http://localhost/get?a=b&c=d[]");

	// prove that it is unencoded
	assertThat(url.getRawQuery()).isEqualTo("a=b&c=d[]");

	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	ServerWebExchange webExchange = testFilter(request, "http://myhost");

	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("myhost").hasParameter("a", "b")
			.hasParameter("c", "d[]");

	// prove that it is NOT encoded
	assertThat(uri.getRawQuery()).isEqualTo("a=b&c=d[]");
}
 
Example #11
Source File: RouteToRequestUrlFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void encodedUrl() {
	URI url = UriComponentsBuilder.fromUriString("http://localhost/abc def/get")
			.buildAndExpand().encode().toUri();

	// prove that it is encoded
	assertThat(url.getRawPath()).isEqualTo("/abc%20def/get");

	assertThat(url).hasPath("/abc def/get");

	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	ServerWebExchange webExchange = testFilter(request,
			"http://myhost/abc%20def/get");
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("myhost").hasPath("/abc def/get");

	// prove that it is not double encoded
	assertThat(uri.getRawPath()).isEqualTo("/abc%20def/get");
}
 
Example #12
Source File: RouteToRequestUrlFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void encodedParameters() {
	URI url = UriComponentsBuilder.fromUriString("http://localhost/get?a=b&c=d[]")
			.buildAndExpand().encode().toUri();

	// prove that it is encoded
	assertThat(url.getRawQuery()).isEqualTo("a=b&c=d%5B%5D");

	assertThat(url).hasParameter("c", "d[]");

	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	ServerWebExchange webExchange = testFilter(request, "http://myhost");
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("myhost").hasParameter("a", "b")
			.hasParameter("c", "d[]");

	// prove that it is not double encoded
	assertThat(uri.getRawQuery()).isEqualTo("a=b&c=d%5B%5D");
}
 
Example #13
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 #14
Source File: CookieCsrfFilterTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void cookieSetInResponse() {
    final String token = "test_token";
    WebFilterChain filterChain = (filterExchange) -> {
        try {
            ResponseCookie cookie = filterExchange.getResponse().getCookies().getFirst(CSRF_COOKIE_NAME);
            assertThat(cookie).isNotNull();
            assertThat(cookie.getName()).isEqualTo(CSRF_COOKIE_NAME);
            assertThat(cookie.getValue()).isEqualTo(token);
            assertThat(cookie.getPath()).isEqualTo("/");
            assertThat(cookie.getMaxAge()).isEqualTo(Duration.ofSeconds(-1));
            assertThat(cookie.isHttpOnly()).isFalse();
            assertThat(cookie.isSecure()).isFalse();
        } catch (AssertionError ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    };
    MockServerWebExchange exchange = MockServerWebExchange.from(
        MockServerHttpRequest.post(TEST_URL)
    );
    exchange.getAttributes().put(CsrfToken.class.getName(), Mono.just(new DefaultCsrfToken(CSRF_COOKIE_NAME, "_csrf", token)));
    this.filter.filter(exchange, filterChain).block();
}
 
Example #15
Source File: TraceRequestHttpHeadersFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_reuse_headers_only_from_input_since_exchange_may_contain_already_ignored_headers() {
	HttpHeadersFilter filter = TraceRequestHttpHeadersFilter.create(this.httpTracing);
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.set("X-Hello", "World");
	MockServerHttpRequest request = MockServerHttpRequest.post("foo/bar")
			.headers(httpHeaders).build();
	MockServerWebExchange exchange = MockServerWebExchange.builder(request).build();

	HttpHeaders filteredHeaders = filter.filter(requestHeaders(), exchange);

	BDDAssertions.then(filteredHeaders.get("X-B3-TraceId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-B3-SpanId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-Hello")).isNullOrEmpty();
	BDDAssertions
			.then((Object) exchange
					.getAttribute(TraceRequestHttpHeadersFilter.SPAN_ATTRIBUTE))
			.isNotNull();
}
 
Example #16
Source File: RequestHeaderToRequestUriGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void filterDoesNotChangeRequestUriIfHeaderIsAbsent() {
	RequestHeaderToRequestUriGatewayFilterFactory factory = new RequestHeaderToRequestUriGatewayFilterFactory();
	GatewayFilter filter = factory.apply(c -> c.setName("X-CF-Forwarded-Url"));
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.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("http://localhost");
}
 
Example #17
Source File: SetPathGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private void testFilter(String template, String expectedPath,
		HashMap<String, String> variables) {
	GatewayFilter filter = new SetPathGatewayFilterFactory()
			.apply(c -> c.setTemplate(template));

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

	ServerWebExchange exchange = MockServerWebExchange.from(request);
	ServerWebExchangeUtils.putUriTemplateVariables(exchange, variables);

	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 #18
Source File: TraceRequestHttpHeadersFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_set_tracing_headers() {
	HttpHeadersFilter filter = TraceRequestHttpHeadersFilter.create(this.httpTracing);
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.set("X-Hello", "World");
	MockServerHttpRequest request = MockServerHttpRequest.post("foo/bar")
			.headers(httpHeaders).build();
	MockServerWebExchange exchange = MockServerWebExchange.builder(request).build();

	HttpHeaders filteredHeaders = filter.filter(requestHeaders(httpHeaders),
			exchange);

	BDDAssertions.then(filteredHeaders.get("X-B3-TraceId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-B3-SpanId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-Hello"))
			.isEqualTo(Collections.singletonList("World"));
	BDDAssertions.then(filteredHeaders.get("X-Hello-Request"))
			.isEqualTo(Collections.singletonList("Request World"));
	BDDAssertions
			.then((Object) exchange
					.getAttribute(TraceRequestHttpHeadersFilter.SPAN_ATTRIBUTE))
			.isNotNull();
}
 
Example #19
Source File: TraceRequestHttpHeadersFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_set_tracing_headers_with_multiple_values() {
	HttpHeadersFilter filter = TraceRequestHttpHeadersFilter.create(this.httpTracing);
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.add("X-Hello-Request", "Request World");
	httpHeaders.addAll("X-Hello", Arrays.asList("World1", "World2"));
	MockServerHttpRequest request = MockServerHttpRequest.post("foo/bar")
			.headers(httpHeaders).build();
	MockServerWebExchange exchange = MockServerWebExchange.builder(request).build();

	HttpHeaders filteredHeaders = filter.filter(httpHeaders, exchange);

	BDDAssertions.then(filteredHeaders.get("X-B3-TraceId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-B3-SpanId")).isNotEmpty();
	BDDAssertions.then(filteredHeaders.get("X-Hello"))
			.isEqualTo(Arrays.asList("World1", "World2"));
	BDDAssertions.then(filteredHeaders.get("X-Hello-Request"))
			.isEqualTo(Collections.singletonList("Request World"));
	BDDAssertions
			.then((Object) exchange
					.getAttribute(TraceRequestHttpHeadersFilter.SPAN_ATTRIBUTE))
			.isNotNull();
}
 
Example #20
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 #21
Source File: PropertiesTagsProviderTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
	contextRunner
			.withConfiguration(
					AutoConfigurations.of(GatewayMetricsAutoConfiguration.class))
			.withPropertyValues("spring.cloud.gateway.metrics.tags.foo1=bar1",
					"spring.cloud.gateway.metrics.tags.foo2=bar2")
			.run(context -> {
				PropertiesTagsProvider provider = context
						.getBean(PropertiesTagsProvider.class);
				Tags tags = provider.apply(MockServerWebExchange
						.from(MockServerHttpRequest.get("").build()));
				assertThat(tags).isEqualTo(Tags.of("foo1", "bar1", "foo2", "bar2"));
			});

}
 
Example #22
Source File: RemoveRequestParameterGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void removeRequestParameterFilterShouldHandleRemainingParamsWhichRequiringEncoding() {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.queryParam("foo", "bar").queryParam("aaa", "abc xyz")
			.queryParam("bbb", "[xyz").queryParam("ccc", ",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("aaa",
			singletonList("abc xyz"));
	assertThat(actualRequest.getQueryParams()).containsEntry("bbb",
			singletonList("[xyz"));
	assertThat(actualRequest.getQueryParams()).containsEntry("ccc",
			singletonList(",xyz"));
}
 
Example #23
Source File: TraceResponseHttpHeadersFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void should_report_span_when_span_was_present_in_attribute() {
	HttpHeadersFilter filter = TraceResponseHttpHeadersFilter
			.create(this.httpTracing);
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.set("b3", "52f112af7472aff0-53e6ab6fc5dfee58");
	MockServerHttpRequest request = MockServerHttpRequest.post("foo/bar")
			.headers(httpHeaders).build();
	MockServerWebExchange exchange = MockServerWebExchange.builder(request).build();
	exchange.getAttributes().put(TraceResponseHttpHeadersFilter.SPAN_ATTRIBUTE,
			this.tracing.tracer().nextSpan());

	filter.filter(httpHeaders, exchange);

	BDDAssertions.then(this.spans).isNotEmpty();
}
 
Example #24
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 #25
Source File: RemoveRequestParameterGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void removeRequestParameterFilterWorksWhenParamIsNotPresentInRequest() {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost")
			.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");
}
 
Example #26
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 #27
Source File: ForwardedHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void forwardedHeaderExists() throws UnknownHostException {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost/get")
			.remoteAddress(
					new InetSocketAddress(InetAddress.getByName("10.0.0.1"), 80))
			.header(FORWARDED_HEADER,
					"for=12.34.56.78;host=example.com;proto=https; for=23.45.67.89")
			.build();

	ForwardedHeadersFilter filter = new ForwardedHeadersFilter();

	HttpHeaders headers = filter.filter(request.getHeaders(),
			MockServerWebExchange.from(request));

	assertThat(headers.get(FORWARDED_HEADER)).hasSize(2);

	List<Forwarded> forwardeds = ForwardedHeadersFilter
			.parse(headers.get(FORWARDED_HEADER));

	assertThat(forwardeds).hasSize(2);
	Forwarded addedForwardedHeader = forwardeds.get(0);
	Forwarded existingForwardedHeader = forwardeds.get(1);

	assertThat(existingForwardedHeader.getValues()).containsEntry("proto", "http")
			.containsEntry("for", "\"10.0.0.1:80\"");

	assertThat(addedForwardedHeader.getValues()).containsEntry("proto", "https")
			.containsEntry("for", "23.45.67.89");
}
 
Example #28
Source File: RemoveHopByHopHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void caseInsensitive() {
	MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest
			.get("http://localhost/get");

	HEADERS_REMOVED_ON_REQUEST
			.forEach(header -> builder.header(header.toLowerCase(), header + "1"));

	testFilter(MockServerWebExchange.from(builder));
}
 
Example #29
Source File: RemoveHopByHopHeadersFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void removesHeadersListedInConnectionHeader() {
	MockServerHttpRequest.BaseBuilder<?> builder = MockServerHttpRequest
			.get("http://localhost/get");

	builder.header(HttpHeaders.CONNECTION, "upgrade", "keep-alive");
	builder.header(HttpHeaders.UPGRADE, "WebSocket");
	builder.header("Keep-Alive", "timeout:5");

	testFilter(MockServerWebExchange.from(builder), "upgrade", "keep-alive");
}
 
Example #30
Source File: HttpHeadersFilterMixedTypeTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void relevantDownstreamFiltersShouldActOnHeaders() {
	MockServerHttpRequest mockRequest = MockServerHttpRequest.get("/get")
			.header("header1", "value1").header("header2", "value2")
			.header("header3", "value3").build();

	HttpHeadersFilter filter1 = filterRemovingHeaders(Type.RESPONSE, "header1");

	HttpHeadersFilter filter2 = filterRemovingHeaders(Type.REQUEST, "header2");

	HttpHeaders result = HttpHeadersFilter.filterRequest(
			Arrays.asList(filter1, filter2), MockServerWebExchange.from(mockRequest));

	assertThat(result).containsOnlyKeys("header1", "header3");
}