Refactor tests to use toExchange() shortcuts

Issue: SPR-15350
This commit is contained in:
Rossen Stoyanchev 2017-03-16 11:53:46 -04:00
parent 41c413a748
commit f6e2c585c8
71 changed files with 1277 additions and 1853 deletions

View File

@ -27,13 +27,11 @@ import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.tests.sample.beans.ITestBean;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static junit.framework.TestCase.assertFalse;
import static org.junit.Assert.assertEquals;
@ -173,8 +171,7 @@ public class WebExchangeDataBinderTests {
public void testBindingWithQueryParams() throws Exception {
String url = "/path?spouse=someValue&spouse.name=test";
MockServerHttpRequest request = MockServerHttpRequest.post(url).build();
ServerWebExchange exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
this.binder.bind(exchange).block(Duration.ofMillis(5000));
this.binder.bind(request.toExchange()).block(Duration.ofSeconds(5));
assertNotNull(this.testBean.getSpouse());
assertEquals("test", this.testBean.getSpouse().getName());
@ -208,13 +205,11 @@ public class WebExchangeDataBinderTests {
}
private ServerWebExchange exchange(MultiValueMap<String, String> formData) {
MockServerHttpRequest request = MockServerHttpRequest
return MockServerHttpRequest
.post("/")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(generateForm(formData));
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
.body(generateForm(formData))
.toExchange();
}

View File

@ -22,13 +22,19 @@ import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
import static org.junit.Assert.*;
import static org.springframework.http.HttpHeaders.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS;
import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN;
import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS;
import static org.springframework.http.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD;
/**
* {@link DefaultCorsProcessor} tests with simple or pre-flight CORS request.
@ -37,10 +43,6 @@ import static org.springframework.http.HttpHeaders.*;
*/
public class DefaultCorsProcessorTests {
private MockServerHttpRequest request;
private MockServerHttpResponse response;
private DefaultCorsProcessor processor;
private CorsConfiguration conf;
@ -49,297 +51,322 @@ public class DefaultCorsProcessorTests {
@Before
public void setup() {
this.conf = new CorsConfiguration();
this.response = new MockServerHttpResponse();
this.response.setStatusCode(HttpStatus.OK);
this.processor = new DefaultCorsProcessor();
}
@Test
public void actualRequestWithOriginHeader() throws Exception {
this.request = actualRequest().build();
this.processor.processRequest(this.conf, createExchange());
assertFalse(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.FORBIDDEN, this.response.getStatusCode());
ServerWebExchange exchange = actualRequest();
this.processor.processRequest(this.conf, exchange);
ServerHttpResponse response = exchange.getResponse();
assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
}
@Test
public void actualRequestWithOriginHeaderAndNullConfig() throws Exception {
this.request = actualRequest().build();
this.processor.processRequest(null, createExchange());
assertFalse(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
ServerWebExchange exchange = actualRequest();
this.processor.processRequest(null, exchange);
ServerHttpResponse response = exchange.getResponse();
assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertNull(response.getStatusCode());
}
@Test
public void actualRequestWithOriginHeaderAndAllowedOrigin() throws Exception {
this.request = actualRequest().build();
ServerWebExchange exchange = actualRequest();
this.conf.addAllowedOrigin("*");
this.processor.processRequest(this.conf, exchange);
this.processor.processRequest(this.conf, createExchange());
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("*", this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertFalse(this.response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
assertFalse(this.response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
ServerHttpResponse response = exchange.getResponse();
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("*", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertFalse(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
assertFalse(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS));
assertNull(response.getStatusCode());
}
@Test
public void actualRequestCredentials() throws Exception {
this.request = actualRequest().build();
ServerWebExchange exchange = actualRequest();
this.conf.addAllowedOrigin("http://domain1.com");
this.conf.addAllowedOrigin("http://domain2.com");
this.conf.addAllowedOrigin("http://domain3.com");
this.conf.setAllowCredentials(true);
this.processor.processRequest(this.conf, exchange);
this.processor.processRequest(this.conf, createExchange());
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("http://domain2.com", this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(this.response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertEquals("true", this.response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
ServerHttpResponse response = exchange.getResponse();
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("http://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertNull(response.getStatusCode());
}
@Test
public void actualRequestCredentialsWithOriginWildcard() throws Exception {
this.request = actualRequest().build();
ServerWebExchange exchange = actualRequest();
this.conf.addAllowedOrigin("*");
this.conf.setAllowCredentials(true);
this.processor.processRequest(this.conf, exchange);
this.processor.processRequest(this.conf, createExchange());
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("http://domain2.com", this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(this.response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertEquals("true", this.response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
ServerHttpResponse response = exchange.getResponse();
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("http://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertNull(response.getStatusCode());
}
@Test
public void actualRequestCaseInsensitiveOriginMatch() throws Exception {
this.request = actualRequest().build();
ServerWebExchange exchange = actualRequest();
this.conf.addAllowedOrigin("http://DOMAIN2.com");
this.processor.processRequest(this.conf, exchange);
this.processor.processRequest(this.conf, createExchange());
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
ServerHttpResponse response = exchange.getResponse();
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertNull(response.getStatusCode());
}
@Test
public void actualRequestExposedHeaders() throws Exception {
this.request = actualRequest().build();
ServerWebExchange exchange = actualRequest();
this.conf.addExposedHeader("header1");
this.conf.addExposedHeader("header2");
this.conf.addAllowedOrigin("http://domain2.com");
this.processor.processRequest(this.conf, exchange);
this.processor.processRequest(this.conf, createExchange());
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("http://domain2.com", this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(this.response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS));
assertTrue(this.response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header1"));
assertTrue(this.response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header2"));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
ServerHttpResponse response = exchange.getResponse();
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("http://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS));
assertTrue(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header1"));
assertTrue(response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).contains("header2"));
assertNull(response.getStatusCode());
}
@Test
public void preflightRequestAllOriginsAllowed() throws Exception {
this.request = preFlightRequest().header(ACCESS_CONTROL_REQUEST_METHOD, "GET").build();
ServerWebExchange exchange = preFlightRequest().header(ACCESS_CONTROL_REQUEST_METHOD, "GET").toExchange();
this.conf.addAllowedOrigin("*");
this.processor.processRequest(this.conf, exchange);
this.processor.processRequest(this.conf, createExchange());
assertEquals(HttpStatus.OK, this.response.getStatusCode());
assertNull(exchange.getResponse().getStatusCode());
}
@Test
public void preflightRequestWrongAllowedMethod() throws Exception {
this.request = preFlightRequest().header(ACCESS_CONTROL_REQUEST_METHOD, "DELETE").build();
ServerWebExchange exchange = preFlightRequest().header(ACCESS_CONTROL_REQUEST_METHOD, "DELETE").toExchange();
this.conf.addAllowedOrigin("*");
this.processor.processRequest(this.conf, exchange);
this.processor.processRequest(this.conf, createExchange());
assertEquals(HttpStatus.FORBIDDEN, this.response.getStatusCode());
assertEquals(HttpStatus.FORBIDDEN, exchange.getResponse().getStatusCode());
}
@Test
public void preflightRequestMatchedAllowedMethod() throws Exception {
this.request = preFlightRequest().header(ACCESS_CONTROL_REQUEST_METHOD, "GET").build();
ServerWebExchange exchange = preFlightRequest().header(ACCESS_CONTROL_REQUEST_METHOD, "GET").toExchange();
this.conf.addAllowedOrigin("*");
this.processor.processRequest(this.conf, exchange);
this.processor.processRequest(this.conf, createExchange());
assertEquals(HttpStatus.OK, this.response.getStatusCode());
assertEquals("GET,HEAD", this.response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS));
ServerHttpResponse response = exchange.getResponse();
assertNull(response.getStatusCode());
assertEquals("GET,HEAD", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS));
}
@Test
public void preflightRequestTestWithOriginButWithoutOtherHeaders() throws Exception {
this.request = preFlightRequest().build();
ServerWebExchange exchange = preFlightRequest().toExchange();
this.processor.processRequest(this.conf, exchange);
this.processor.processRequest(this.conf, createExchange());
assertFalse(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.FORBIDDEN, this.response.getStatusCode());
ServerHttpResponse response = exchange.getResponse();
assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
}
@Test
public void preflightRequestWithoutRequestMethod() throws Exception {
this.request = preFlightRequest().header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1").build();
ServerWebExchange exchange = preFlightRequest().header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1").toExchange();
this.processor.processRequest(this.conf, exchange);
this.processor.processRequest(this.conf, createExchange());
assertFalse(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.FORBIDDEN, this.response.getStatusCode());
ServerHttpResponse response = exchange.getResponse();
assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
}
@Test
public void preflightRequestWithRequestAndMethodHeaderButNoConfig() throws Exception {
this.request = preFlightRequest()
ServerWebExchange exchange = preFlightRequest()
.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1")
.build();
.toExchange();
this.processor.processRequest(this.conf, createExchange());
assertFalse(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.FORBIDDEN, this.response.getStatusCode());
this.processor.processRequest(this.conf, exchange);
ServerHttpResponse response = exchange.getResponse();
assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
}
@Test
public void preflightRequestValidRequestAndConfig() throws Exception {
this.request = preFlightRequest()
ServerWebExchange exchange = preFlightRequest()
.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1")
.build();
.toExchange();
this.conf.addAllowedOrigin("*");
this.conf.addAllowedMethod("GET");
this.conf.addAllowedMethod("PUT");
this.conf.addAllowedHeader("header1");
this.conf.addAllowedHeader("header2");
this.processor.processRequest(this.conf, createExchange());
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("*", this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(this.response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS));
assertEquals("GET,PUT", this.response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS));
assertFalse(this.response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
this.processor.processRequest(this.conf, exchange);
ServerHttpResponse response = exchange.getResponse();
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("*", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS));
assertEquals("GET,PUT", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS));
assertFalse(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
assertNull(response.getStatusCode());
}
@Test
public void preflightRequestCredentials() throws Exception {
this.request = preFlightRequest()
ServerWebExchange exchange = preFlightRequest()
.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1")
.build();
.toExchange();
this.conf.addAllowedOrigin("http://domain1.com");
this.conf.addAllowedOrigin("http://domain2.com");
this.conf.addAllowedOrigin("http://domain3.com");
this.conf.addAllowedHeader("Header1");
this.conf.setAllowCredentials(true);
this.processor.processRequest(this.conf, createExchange());
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("http://domain2.com", this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(this.response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertEquals("true", this.response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
this.processor.processRequest(this.conf, exchange);
ServerHttpResponse response = exchange.getResponse();
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("http://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(response.getHeaders().containsKey(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertEquals("true", response.getHeaders().getFirst(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS));
assertNull(response.getStatusCode());
}
@Test
public void preflightRequestCredentialsWithOriginWildcard() throws Exception {
this.request = preFlightRequest()
ServerWebExchange exchange = preFlightRequest()
.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1")
.build();
.toExchange();
this.conf.addAllowedOrigin("http://domain1.com");
this.conf.addAllowedOrigin("*");
this.conf.addAllowedOrigin("http://domain3.com");
this.conf.addAllowedHeader("Header1");
this.conf.setAllowCredentials(true);
this.processor.processRequest(this.conf, createExchange());
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("http://domain2.com", this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
this.processor.processRequest(this.conf, exchange);
ServerHttpResponse response = exchange.getResponse();
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals("http://domain2.com", response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_ORIGIN));
assertNull(response.getStatusCode());
}
@Test
public void preflightRequestAllowedHeaders() throws Exception {
this.request = preFlightRequest()
ServerWebExchange exchange = preFlightRequest()
.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1, Header2")
.build();
.toExchange();
this.conf.addAllowedHeader("Header1");
this.conf.addAllowedHeader("Header2");
this.conf.addAllowedHeader("Header3");
this.conf.addAllowedOrigin("http://domain2.com");
this.processor.processRequest(this.conf, createExchange());
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS));
assertTrue(this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1"));
assertTrue(this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2"));
assertFalse(this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header3"));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
this.processor.processRequest(this.conf, exchange);
ServerHttpResponse response = exchange.getResponse();
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS));
assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1"));
assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2"));
assertFalse(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header3"));
assertNull(response.getStatusCode());
}
@Test
public void preflightRequestAllowsAllHeaders() throws Exception {
this.request = preFlightRequest()
ServerWebExchange exchange = preFlightRequest()
.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(ACCESS_CONTROL_REQUEST_HEADERS, "Header1, Header2")
.build();
.toExchange();
this.conf.addAllowedHeader("*");
this.conf.addAllowedOrigin("http://domain2.com");
this.processor.processRequest(this.conf, createExchange());
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS));
assertTrue(this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1"));
assertTrue(this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2"));
assertFalse(this.response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("*"));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
this.processor.processRequest(this.conf, exchange);
ServerHttpResponse response = exchange.getResponse();
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS));
assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header1"));
assertTrue(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("Header2"));
assertFalse(response.getHeaders().getFirst(ACCESS_CONTROL_ALLOW_HEADERS).contains("*"));
assertNull(response.getStatusCode());
}
@Test
public void preflightRequestWithEmptyHeaders() throws Exception {
this.request = preFlightRequest()
ServerWebExchange exchange = preFlightRequest()
.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(ACCESS_CONTROL_REQUEST_HEADERS, "")
.build();
.toExchange();
this.conf.addAllowedHeader("*");
this.conf.addAllowedOrigin("http://domain2.com");
this.processor.processRequest(this.conf, createExchange());
assertTrue(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertFalse(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
this.processor.processRequest(this.conf, exchange);
ServerHttpResponse response = exchange.getResponse();
assertTrue(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_HEADERS));
assertNull(response.getStatusCode());
}
@Test
public void preflightRequestWithNullConfig() throws Exception {
this.request = preFlightRequest()
.header(ACCESS_CONTROL_REQUEST_METHOD, "GET")
.build();
ServerWebExchange exchange = preFlightRequest().header(ACCESS_CONTROL_REQUEST_METHOD, "GET").toExchange();
this.conf.addAllowedOrigin("*");
this.processor.processRequest(null, exchange);
this.processor.processRequest(null, createExchange());
assertFalse(this.response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.FORBIDDEN, this.response.getStatusCode());
ServerHttpResponse response = exchange.getResponse();
assertFalse(response.getHeaders().containsKey(ACCESS_CONTROL_ALLOW_ORIGIN));
assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
}
private MockServerHttpRequest.BaseBuilder<?> actualRequest() {
return corsRequest(HttpMethod.GET);
private ServerWebExchange actualRequest() {
return corsRequest(HttpMethod.GET).toExchange();
}
private MockServerHttpRequest.BaseBuilder<?> preFlightRequest() {
return corsRequest(HttpMethod.OPTIONS);
}
private MockServerHttpRequest.BaseBuilder<?> corsRequest(HttpMethod httpMethod) {
private MockServerHttpRequest.BaseBuilder<?> corsRequest(HttpMethod method) {
return MockServerHttpRequest
.method(httpMethod, "http://localhost/test.html")
.method(method, "http://localhost/test.html")
.header(HttpHeaders.ORIGIN, "http://domain2.com");
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, this.response);
}
}

View File

@ -18,13 +18,9 @@ package org.springframework.web.cors.reactive;
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@ -42,7 +38,7 @@ public class UrlBasedCorsConfigurationSourceTests {
@Test
public void empty() {
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/bar/test.html");
ServerWebExchange exchange = MockServerHttpRequest.get("/bar/test.html").toExchange();
assertNull(this.configSource.getCorsConfiguration(exchange));
}
@ -51,10 +47,10 @@ public class UrlBasedCorsConfigurationSourceTests {
CorsConfiguration config = new CorsConfiguration();
this.configSource.registerCorsConfiguration("/bar/**", config);
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/foo/test.html");
ServerWebExchange exchange = MockServerHttpRequest.get("/foo/test.html").toExchange();
assertNull(this.configSource.getCorsConfiguration(exchange));
exchange = createExchange(HttpMethod.GET, "/bar/test.html");
exchange = MockServerHttpRequest.get("/bar/test.html").toExchange();
assertEquals(config, this.configSource.getCorsConfiguration(exchange));
}
@ -63,10 +59,4 @@ public class UrlBasedCorsConfigurationSourceTests {
this.configSource.getCorsConfigurations().put("/**", new CorsConfiguration());
}
private ServerWebExchange createExchange(HttpMethod httpMethod, String url) {
ServerHttpRequest request = MockServerHttpRequest.method(httpMethod, url).build();
MockServerHttpResponse response = new MockServerHttpResponse();
return new DefaultServerWebExchange(request, response);
}
}

View File

@ -27,10 +27,8 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
@ -145,9 +143,7 @@ public class HiddenHttpMethodFilterTests {
.map(method -> builder.body(methodName + "=" + method))
.orElse(builder.build());
MockServerHttpResponse response = new MockServerHttpResponse();
return new DefaultServerWebExchange(request, response);
return request.toExchange();
}
}

View File

@ -34,9 +34,13 @@ import org.junit.runners.Parameterized.Parameters;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get;
/**
* "checkNotModified" unit tests for {@link DefaultServerWebExchange}.
@ -51,10 +55,6 @@ public class DefaultServerWebExchangeCheckNotModifiedTests {
private SimpleDateFormat dateFormat;
private MockServerHttpRequest request;
private MockServerHttpResponse response = new MockServerHttpResponse();
private Instant currentDate;
@Parameter
@ -79,75 +79,75 @@ public class DefaultServerWebExchangeCheckNotModifiedTests {
@Test
public void checkNotModifiedNon2xxStatus() {
this.request = request().ifModifiedSince(this.currentDate.toEpochMilli()).build();
this.response.setStatusCode(HttpStatus.NOT_MODIFIED);
MockServerWebExchange exchange = get("/").ifModifiedSince(this.currentDate.toEpochMilli()).toExchange();
exchange.getResponse().setStatusCode(HttpStatus.NOT_MODIFIED);
assertFalse(createExchange().checkNotModified(this.currentDate));
assertEquals(304, response.getStatusCode().value());
assertEquals(-1, response.getHeaders().getLastModified());
assertFalse(exchange.checkNotModified(this.currentDate));
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(-1, exchange.getResponse().getHeaders().getLastModified());
}
@Test // SPR-14559
public void checkNotModifiedInvalidIfNoneMatchHeader() {
String eTag = "\"etagvalue\"";
this.request = request().ifNoneMatch("missingquotes").build();
assertFalse(createExchange().checkNotModified(eTag));
assertNull(response.getStatusCode());
assertEquals(eTag, response.getHeaders().getETag());
MockServerWebExchange exchange = get("/").ifNoneMatch("missingquotes").toExchange();
assertFalse(exchange.checkNotModified(eTag));
assertNull(exchange.getResponse().getStatusCode());
assertEquals(eTag, exchange.getResponse().getHeaders().getETag());
}
@Test
public void checkNotModifiedHeaderAlreadySet() {
this.request = request().ifModifiedSince(currentDate.toEpochMilli()).build();
this.response.getHeaders().add("Last-Modified", CURRENT_TIME);
MockServerWebExchange exchange = get("/").ifModifiedSince(currentDate.toEpochMilli()).toExchange();
exchange.getResponse().getHeaders().add("Last-Modified", CURRENT_TIME);
assertTrue(createExchange().checkNotModified(currentDate));
assertEquals(304, response.getStatusCode().value());
assertEquals(1, response.getHeaders().get("Last-Modified").size());
assertEquals(CURRENT_TIME, response.getHeaders().getFirst("Last-Modified"));
assertTrue(exchange.checkNotModified(currentDate));
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(1, exchange.getResponse().getHeaders().get("Last-Modified").size());
assertEquals(CURRENT_TIME, exchange.getResponse().getHeaders().getFirst("Last-Modified"));
}
@Test
public void checkNotModifiedTimestamp() throws Exception {
this.request = request().ifModifiedSince(currentDate.toEpochMilli()).build();
MockServerWebExchange exchange = get("/").ifModifiedSince(currentDate.toEpochMilli()).toExchange();
assertTrue(createExchange().checkNotModified(currentDate));
assertTrue(exchange.checkNotModified(currentDate));
assertEquals(304, response.getStatusCode().value());
assertEquals(currentDate.toEpochMilli(), response.getHeaders().getLastModified());
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(currentDate.toEpochMilli(), exchange.getResponse().getHeaders().getLastModified());
}
@Test
public void checkModifiedTimestamp() {
Instant oneMinuteAgo = currentDate.minusSeconds(60);
this.request = request().ifModifiedSince(oneMinuteAgo.toEpochMilli()).build();
MockServerWebExchange exchange = get("/").ifModifiedSince(oneMinuteAgo.toEpochMilli()).toExchange();
assertFalse(createExchange().checkNotModified(currentDate));
assertFalse(exchange.checkNotModified(currentDate));
assertNull(response.getStatusCode());
assertEquals(currentDate.toEpochMilli(), response.getHeaders().getLastModified());
assertNull(exchange.getResponse().getStatusCode());
assertEquals(currentDate.toEpochMilli(), exchange.getResponse().getHeaders().getLastModified());
}
@Test
public void checkNotModifiedETag() {
String eTag = "\"Foo\"";
this.request = request().ifNoneMatch(eTag).build();
MockServerWebExchange exchange = get("/").ifNoneMatch(eTag).toExchange();
assertTrue(createExchange().checkNotModified(eTag));
assertTrue(exchange.checkNotModified(eTag));
assertEquals(304, response.getStatusCode().value());
assertEquals(eTag, response.getHeaders().getETag());
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(eTag, exchange.getResponse().getHeaders().getETag());
}
@Test
public void checkNotModifiedETagWithSeparatorChars() {
String eTag = "\"Foo, Bar\"";
this.request = request().ifNoneMatch(eTag).build();
MockServerWebExchange exchange = get("/").ifNoneMatch(eTag).toExchange();
assertTrue(createExchange().checkNotModified(eTag));
assertTrue(exchange.checkNotModified(eTag));
assertEquals(304, response.getStatusCode().value());
assertEquals(eTag, response.getHeaders().getETag());
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(eTag, exchange.getResponse().getHeaders().getETag());
}
@ -155,58 +155,59 @@ public class DefaultServerWebExchangeCheckNotModifiedTests {
public void checkModifiedETag() {
String currentETag = "\"Foo\"";
String oldEtag = "Bar";
this.request = request().ifNoneMatch(oldEtag).build();
MockServerWebExchange exchange = get("/").ifNoneMatch(oldEtag).toExchange();
assertFalse(createExchange().checkNotModified(currentETag));
assertFalse(exchange.checkNotModified(currentETag));
assertNull(response.getStatusCode());
assertEquals(currentETag, response.getHeaders().getETag());
assertNull(exchange.getResponse().getStatusCode());
assertEquals(currentETag, exchange.getResponse().getHeaders().getETag());
}
@Test
public void checkNotModifiedUnpaddedETag() {
String eTag = "Foo";
String paddedEtag = String.format("\"%s\"", eTag);
this.request = request().ifNoneMatch(paddedEtag).build();
MockServerWebExchange exchange = get("/").ifNoneMatch(paddedEtag).toExchange();
assertTrue(createExchange().checkNotModified(eTag));
assertTrue(exchange.checkNotModified(eTag));
assertEquals(304, response.getStatusCode().value());
assertEquals(paddedEtag, response.getHeaders().getETag());
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(paddedEtag, exchange.getResponse().getHeaders().getETag());
}
@Test
public void checkModifiedUnpaddedETag() {
String currentETag = "Foo";
String oldEtag = "Bar";
this.request = request().ifNoneMatch(oldEtag).build();
MockServerWebExchange exchange = get("/").ifNoneMatch(oldEtag).toExchange();
assertFalse(createExchange().checkNotModified(currentETag));
assertFalse(exchange.checkNotModified(currentETag));
assertNull(response.getStatusCode());
assertEquals(String.format("\"%s\"", currentETag), response.getHeaders().getETag());
assertNull(exchange.getResponse().getStatusCode());
assertEquals(String.format("\"%s\"", currentETag), exchange.getResponse().getHeaders().getETag());
}
@Test
public void checkNotModifiedWildcardIsIgnored() {
String eTag = "\"Foo\"";
this.request = request().ifNoneMatch("*").build();
assertFalse(createExchange().checkNotModified(eTag));
MockServerWebExchange exchange = get("/").ifNoneMatch("*").toExchange();
assertFalse(exchange.checkNotModified(eTag));
assertNull(response.getStatusCode());
assertEquals(eTag, response.getHeaders().getETag());
assertNull(exchange.getResponse().getStatusCode());
assertEquals(eTag, exchange.getResponse().getHeaders().getETag());
}
@Test
public void checkNotModifiedETagAndTimestamp() {
String eTag = "\"Foo\"";
this.request = request().ifNoneMatch(eTag).ifModifiedSince(currentDate.toEpochMilli()).build();
long time = currentDate.toEpochMilli();
MockServerWebExchange exchange = get("/").ifNoneMatch(eTag).ifModifiedSince(time).toExchange();
assertTrue(createExchange().checkNotModified(eTag, currentDate));
assertTrue(exchange.checkNotModified(eTag, currentDate));
assertEquals(304, response.getStatusCode().value());
assertEquals(eTag, response.getHeaders().getETag());
assertEquals(currentDate.toEpochMilli(), response.getHeaders().getLastModified());
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(eTag, exchange.getResponse().getHeaders().getETag());
assertEquals(time, exchange.getResponse().getHeaders().getLastModified());
}
// SPR-14224
@ -214,114 +215,111 @@ public class DefaultServerWebExchangeCheckNotModifiedTests {
public void checkNotModifiedETagAndModifiedTimestamp() {
String eTag = "\"Foo\"";
Instant oneMinuteAgo = currentDate.minusSeconds(60);
this.request = request().ifNoneMatch(eTag).ifModifiedSince(oneMinuteAgo.toEpochMilli()).build();
MockServerWebExchange exchange = get("/")
.ifNoneMatch(eTag)
.ifModifiedSince(oneMinuteAgo.toEpochMilli())
.toExchange();
assertTrue(createExchange().checkNotModified(eTag, currentDate));
assertTrue(exchange.checkNotModified(eTag, currentDate));
assertEquals(304, response.getStatusCode().value());
assertEquals(eTag, response.getHeaders().getETag());
assertEquals(currentDate.toEpochMilli(), response.getHeaders().getLastModified());
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(eTag, exchange.getResponse().getHeaders().getETag());
assertEquals(currentDate.toEpochMilli(), exchange.getResponse().getHeaders().getLastModified());
}
@Test
public void checkModifiedETagAndNotModifiedTimestamp() throws Exception {
String currentETag = "\"Foo\"";
String oldEtag = "\"Bar\"";
this.request = request().ifNoneMatch(oldEtag).ifModifiedSince(currentDate.toEpochMilli()).build();
long time = currentDate.toEpochMilli();
MockServerWebExchange exchange = get("/").ifNoneMatch(oldEtag).ifModifiedSince(time).toExchange();
assertFalse(createExchange().checkNotModified(currentETag, currentDate));
assertFalse(exchange.checkNotModified(currentETag, currentDate));
assertNull(response.getStatusCode());
assertEquals(currentETag, response.getHeaders().getETag());
assertEquals(currentDate.toEpochMilli(), response.getHeaders().getLastModified());
assertNull(exchange.getResponse().getStatusCode());
assertEquals(currentETag, exchange.getResponse().getHeaders().getETag());
assertEquals(time, exchange.getResponse().getHeaders().getLastModified());
}
@Test
public void checkNotModifiedETagWeakStrong() {
String eTag = "\"Foo\"";
String weakEtag = String.format("W/%s", eTag);
this.request = request().ifNoneMatch(eTag).build();
MockServerWebExchange exchange = get("/").ifNoneMatch(eTag).toExchange();
assertTrue(createExchange().checkNotModified(weakEtag));
assertTrue(exchange.checkNotModified(weakEtag));
assertEquals(304, response.getStatusCode().value());
assertEquals(weakEtag, response.getHeaders().getETag());
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(weakEtag, exchange.getResponse().getHeaders().getETag());
}
@Test
public void checkNotModifiedETagStrongWeak() {
String eTag = "\"Foo\"";
this.request = request().ifNoneMatch(String.format("W/%s", eTag)).build();
MockServerWebExchange exchange = get("/").ifNoneMatch(String.format("W/%s", eTag)).toExchange();
assertTrue(createExchange().checkNotModified(eTag));
assertTrue(exchange.checkNotModified(eTag));
assertEquals(304, response.getStatusCode().value());
assertEquals(eTag, response.getHeaders().getETag());
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(eTag, exchange.getResponse().getHeaders().getETag());
}
@Test
public void checkNotModifiedMultipleETags() {
String eTag = "\"Bar\"";
String multipleETags = String.format("\"Foo\", %s", eTag);
this.request = request().ifNoneMatch(multipleETags).build();
MockServerWebExchange exchange = get("/").ifNoneMatch(multipleETags).toExchange();
assertTrue(createExchange().checkNotModified(eTag));
assertTrue(exchange.checkNotModified(eTag));
assertEquals(304, response.getStatusCode().value());
assertEquals(eTag, response.getHeaders().getETag());
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(eTag, exchange.getResponse().getHeaders().getETag());
}
@Test
public void checkNotModifiedTimestampWithLengthPart() throws Exception {
long epochTime = dateFormat.parse(CURRENT_TIME).getTime();
this.request = request().header("If-Modified-Since", "Wed, 09 Apr 2014 09:57:42 GMT; length=13774").build();
String header = "Wed, 09 Apr 2014 09:57:42 GMT; length=13774";
MockServerWebExchange exchange = get("/").header("If-Modified-Since", header).toExchange();
assertTrue(createExchange().checkNotModified(Instant.ofEpochMilli(epochTime)));
assertTrue(exchange.checkNotModified(Instant.ofEpochMilli(epochTime)));
assertEquals(304, response.getStatusCode().value());
assertEquals(epochTime, response.getHeaders().getLastModified());
assertEquals(304, exchange.getResponse().getStatusCode().value());
assertEquals(epochTime, exchange.getResponse().getHeaders().getLastModified());
}
@Test
public void checkModifiedTimestampWithLengthPart() throws Exception {
long epochTime = dateFormat.parse(CURRENT_TIME).getTime();
this.request = request().header("If-Modified-Since", "Tue, 08 Apr 2014 09:57:42 GMT; length=13774").build();
String header = "Tue, 08 Apr 2014 09:57:42 GMT; length=13774";
MockServerWebExchange exchange = get("/").header("If-Modified-Since", header).toExchange();
assertFalse(createExchange().checkNotModified(Instant.ofEpochMilli(epochTime)));
assertFalse(exchange.checkNotModified(Instant.ofEpochMilli(epochTime)));
assertNull(response.getStatusCode());
assertEquals(epochTime, response.getHeaders().getLastModified());
assertNull(exchange.getResponse().getStatusCode());
assertEquals(epochTime, exchange.getResponse().getHeaders().getLastModified());
}
@Test
public void checkNotModifiedTimestampConditionalPut() throws Exception {
Instant oneMinuteAgo = currentDate.minusSeconds(60);
long millis = currentDate.toEpochMilli();
this.request = MockServerHttpRequest.put("http://example.org").ifUnmodifiedSince(millis).build();
MockServerWebExchange exchange = MockServerHttpRequest.put("/").ifUnmodifiedSince(millis).toExchange();
assertFalse(createExchange().checkNotModified(oneMinuteAgo));
assertNull(response.getStatusCode());
assertEquals(-1, response.getHeaders().getLastModified());
assertFalse(exchange.checkNotModified(oneMinuteAgo));
assertNull(exchange.getResponse().getStatusCode());
assertEquals(-1, exchange.getResponse().getHeaders().getLastModified());
}
@Test
public void checkNotModifiedTimestampConditionalPutConflict() throws Exception {
Instant oneMinuteAgo = currentDate.minusSeconds(60);
long millis = oneMinuteAgo.toEpochMilli();
this.request = MockServerHttpRequest.put("http://example.org").ifUnmodifiedSince(millis).build();
MockServerWebExchange exchange = MockServerHttpRequest.put("/").ifUnmodifiedSince(millis).toExchange();
assertTrue(createExchange().checkNotModified(currentDate));
assertEquals(412, response.getStatusCode().value());
assertEquals(-1, response.getHeaders().getLastModified());
}
private MockServerHttpRequest.BaseBuilder<?> request() {
return MockServerHttpRequest.get("http://example.org");
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, this.response);
assertTrue(exchange.checkNotModified(currentDate));
assertEquals(412, exchange.getResponse().getStatusCode().value());
assertEquals(-1, exchange.getResponse().getHeaders().getLastModified());
}
}

View File

@ -18,17 +18,15 @@ package org.springframework.web.server.handler;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import org.springframework.web.server.WebHandler;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
@ -38,20 +36,9 @@ import static org.junit.Assert.assertEquals;
*/
public class ExceptionHandlingHttpHandlerTests {
private MockServerHttpResponse response;
private final MockServerWebExchange exchange = MockServerHttpRequest.get("http://localhost:8080").toExchange();
private ServerWebExchange exchange;
private WebHandler targetHandler;
@Before
public void setUp() throws Exception {
MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost:8080").build();
this.response = new MockServerHttpResponse();
this.exchange = new DefaultServerWebExchange(request, this.response);
this.targetHandler = new StubWebHandler(new IllegalStateException("boo"));
}
private final WebHandler targetHandler = new StubWebHandler(new IllegalStateException("boo"));
@Test
@ -59,7 +46,7 @@ public class ExceptionHandlingHttpHandlerTests {
WebExceptionHandler exceptionHandler = new BadRequestExceptionHandler();
createWebHandler(exceptionHandler).handle(this.exchange).block();
assertEquals(HttpStatus.BAD_REQUEST, this.response.getStatusCode());
assertEquals(HttpStatus.BAD_REQUEST, this.exchange.getResponse().getStatusCode());
}
@Test
@ -72,7 +59,7 @@ public class ExceptionHandlingHttpHandlerTests {
};
createWebHandler(exceptionHandlers).handle(this.exchange).block();
assertEquals(HttpStatus.BAD_REQUEST, this.response.getStatusCode());
assertEquals(HttpStatus.BAD_REQUEST, this.exchange.getResponse().getStatusCode());
}
@Test
@ -80,7 +67,7 @@ public class ExceptionHandlingHttpHandlerTests {
WebExceptionHandler exceptionHandler = new UnresolvedExceptionHandler();
createWebHandler(exceptionHandler).handle(this.exchange).block();
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, this.response.getStatusCode());
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, this.exchange.getResponse().getStatusCode());
}
@Test
@ -88,7 +75,7 @@ public class ExceptionHandlingHttpHandlerTests {
WebExceptionHandler exceptionHandler = new BadRequestExceptionHandler();
createWebHandler(exceptionHandler).handle(this.exchange).block();
assertEquals(HttpStatus.BAD_REQUEST, this.response.getStatusCode());
assertEquals(HttpStatus.BAD_REQUEST, this.exchange.getResponse().getStatusCode());
}
private WebHandler createWebHandler(WebExceptionHandler... handlers) {

View File

@ -18,18 +18,17 @@ package org.springframework.web.server.handler;
import java.time.Duration;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
/**
* Unit tests for {@link ResponseStatusExceptionHandler}.
@ -38,38 +37,23 @@ import static org.junit.Assert.*;
*/
public class ResponseStatusExceptionHandlerTests {
private ResponseStatusExceptionHandler handler;
private final ResponseStatusExceptionHandler handler = new ResponseStatusExceptionHandler();
private MockServerHttpRequest request;
private MockServerHttpResponse response;
@Before
public void setup() throws Exception {
this.handler = new ResponseStatusExceptionHandler();
this.request = MockServerHttpRequest.get("/").build();
this.response = new MockServerHttpResponse();
}
private final MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
@Test
public void handleException() throws Exception {
Throwable ex = new ResponseStatusException(HttpStatus.BAD_REQUEST, "");
this.handler.handle(createExchange(), ex).block(Duration.ofSeconds(5));
assertEquals(HttpStatus.BAD_REQUEST, this.response.getStatusCode());
this.handler.handle(this.exchange, ex).block(Duration.ofSeconds(5));
assertEquals(HttpStatus.BAD_REQUEST, this.exchange.getResponse().getStatusCode());
}
@Test
public void unresolvedException() throws Exception {
Throwable expected = new IllegalStateException();
Mono<Void> mono = this.handler.handle(createExchange(), expected);
Mono<Void> mono = this.handler.handle(this.exchange, expected);
StepVerifier.create(mono).consumeErrorWith(actual -> assertSame(expected, actual)).verify();
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, this.response);
}
}

View File

@ -30,10 +30,6 @@ public class MockWebSessionManager implements WebSessionManager {
private final Mono<WebSession> session;
public MockWebSessionManager() {
this(Mono.empty());
}
public MockWebSessionManager(WebSession session) {
this(Mono.just(session));
}

View File

@ -33,7 +33,6 @@ import org.springframework.core.codec.CharSequenceEncoder;
import org.springframework.http.HttpStatus;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -48,14 +47,15 @@ import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.server.WebExceptionHandler;
import org.springframework.web.server.WebHandler;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.handler.ExceptionHandlingWebHandler;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.springframework.http.MediaType.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.springframework.http.MediaType.APPLICATION_JSON;
/**
@ -72,8 +72,6 @@ public class DispatcherHandlerErrorTests {
private DispatcherHandler dispatcherHandler;
private MockServerHttpRequest request;
@Before
public void setup() throws Exception {
@ -86,8 +84,8 @@ public class DispatcherHandlerErrorTests {
@Test
public void noHandler() throws Exception {
this.request = MockServerHttpRequest.get("/does-not-exist").build();
Mono<Void> publisher = this.dispatcherHandler.handle(createExchange());
ServerWebExchange exchange = MockServerHttpRequest.get("/does-not-exist").toExchange();
Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
StepVerifier.create(publisher)
.consumeErrorWith(error -> {
@ -100,8 +98,8 @@ public class DispatcherHandlerErrorTests {
@Test
public void controllerReturnsMonoError() throws Exception {
this.request = MockServerHttpRequest.get("/error-signal").build();
Mono<Void> publisher = this.dispatcherHandler.handle(createExchange());
ServerWebExchange exchange = MockServerHttpRequest.get("/error-signal").toExchange();
Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
StepVerifier.create(publisher)
.consumeErrorWith(error -> assertSame(EXCEPTION, error))
@ -110,8 +108,8 @@ public class DispatcherHandlerErrorTests {
@Test
public void controllerThrowsException() throws Exception {
this.request = MockServerHttpRequest.get("/raise-exception").build();
Mono<Void> publisher = this.dispatcherHandler.handle(createExchange());
ServerWebExchange exchange = MockServerHttpRequest.get("/raise-exception").toExchange();
Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
StepVerifier.create(publisher)
.consumeErrorWith(error -> assertSame(EXCEPTION, error))
@ -120,8 +118,8 @@ public class DispatcherHandlerErrorTests {
@Test
public void unknownReturnType() throws Exception {
this.request = MockServerHttpRequest.get("/unknown-return-type").build();
Mono<Void> publisher = this.dispatcherHandler.handle(createExchange());
ServerWebExchange exchange = MockServerHttpRequest.get("/unknown-return-type").toExchange();
Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
StepVerifier.create(publisher)
.consumeErrorWith(error -> {
@ -133,8 +131,11 @@ public class DispatcherHandlerErrorTests {
@Test
public void responseBodyMessageConversionError() throws Exception {
this.request = MockServerHttpRequest.post("/request-body").accept(APPLICATION_JSON).body("body");
Mono<Void> publisher = this.dispatcherHandler.handle(createExchange());
ServerWebExchange exchange = MockServerHttpRequest.post("/request-body")
.accept(APPLICATION_JSON).body("body")
.toExchange();
Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
StepVerifier.create(publisher)
.consumeErrorWith(error -> assertThat(error, instanceOf(NotAcceptableStatusException.class)))
@ -143,8 +144,11 @@ public class DispatcherHandlerErrorTests {
@Test
public void requestBodyError() throws Exception {
this.request = MockServerHttpRequest.post("/request-body").body(Mono.error(EXCEPTION));
Mono<Void> publisher = this.dispatcherHandler.handle(createExchange());
ServerWebExchange exchange = MockServerHttpRequest.post("/request-body")
.body(Mono.error(EXCEPTION))
.toExchange();
Mono<Void> publisher = this.dispatcherHandler.handle(exchange);
StepVerifier.create(publisher)
.consumeErrorWith(error -> {
@ -156,8 +160,7 @@ public class DispatcherHandlerErrorTests {
@Test
public void webExceptionHandler() throws Exception {
this.request = MockServerHttpRequest.get("/unknown-argument-type").build();
ServerWebExchange exchange = createExchange();
ServerWebExchange exchange = MockServerHttpRequest.get("/unknown-argument-type").toExchange();
List<WebExceptionHandler> handlers = Collections.singletonList(new ServerError500ExceptionHandler());
WebHandler webHandler = new ExceptionHandlingWebHandler(this.dispatcherHandler, handlers);
@ -167,11 +170,6 @@ public class DispatcherHandlerErrorTests {
}
private ServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
@Configuration
@SuppressWarnings({"unused", "WeakerAccess"})
static class TestConfig {

View File

@ -15,19 +15,16 @@
*/
package org.springframework.web.reactive.accept;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.server.NotAcceptableStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
@ -42,23 +39,22 @@ public class CompositeContentTypeResolverBuilderTests {
public void defaultSettings() throws Exception {
RequestedContentTypeResolver resolver = new RequestedContentTypeResolverBuilder().build();
ServerWebExchange exchange = createExchange("/flower.gif");
MockServerWebExchange exchange = MockServerHttpRequest.get("/flower.gif").toExchange();
assertEquals("Should be able to resolve file extensions by default",
Collections.singletonList(MediaType.IMAGE_GIF), resolver.resolveMediaTypes(exchange));
exchange = createExchange("/flower.xyz");
exchange = MockServerHttpRequest.get("/flower.xyz").toExchange();
assertEquals("Should ignore unknown extensions by default",
Collections.<MediaType>emptyList(), resolver.resolveMediaTypes(exchange));
exchange = createExchange("/flower?format=gif");
exchange = MockServerHttpRequest.get("/flower?format=gif").toExchange();
assertEquals("Should not resolve request parameters by default",
Collections.<MediaType>emptyList(), resolver.resolveMediaTypes(exchange));
ServerHttpRequest request = MockServerHttpRequest.get("/flower").accept(MediaType.IMAGE_GIF).build();
exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
exchange = MockServerHttpRequest.get("/flower").accept(MediaType.IMAGE_GIF).toExchange();
assertEquals("Should resolve Accept header by default",
Collections.singletonList(MediaType.IMAGE_GIF), resolver.resolveMediaTypes(exchange));
@ -72,15 +68,15 @@ public class CompositeContentTypeResolverBuilderTests {
.mediaType("bar", new MediaType("application", "bar"))
.build();
ServerWebExchange exchange = createExchange("/flower.foo");
ServerWebExchange exchange = MockServerHttpRequest.get("/flower.foo").toExchange();
assertEquals(Collections.singletonList(new MediaType("application", "foo")),
resolver.resolveMediaTypes(exchange));
exchange = createExchange("/flower.bar");
exchange = MockServerHttpRequest.get("/flower.bar").toExchange();
assertEquals(Collections.singletonList(new MediaType("application", "bar")),
resolver.resolveMediaTypes(exchange));
exchange = createExchange("/flower.gif");
exchange = MockServerHttpRequest.get("/flower.gif").toExchange();
assertEquals(Collections.singletonList(MediaType.IMAGE_GIF), resolver.resolveMediaTypes(exchange));
}
@ -91,10 +87,10 @@ public class CompositeContentTypeResolverBuilderTests {
.useJaf(false)
.build();
ServerWebExchange exchange = createExchange("/flower.foo");
ServerWebExchange exchange = MockServerHttpRequest.get("/flower.foo").toExchange();
assertEquals(Collections.emptyList(), resolver.resolveMediaTypes(exchange));
exchange = createExchange("/flower.gif");
exchange = MockServerHttpRequest.get("/flower.gif").toExchange();
assertEquals(Collections.emptyList(), resolver.resolveMediaTypes(exchange));
}
@ -105,7 +101,7 @@ public class CompositeContentTypeResolverBuilderTests {
.ignoreUnknownPathExtensions(false)
.build();
ServerWebExchange exchange = createExchange("/flower.xyz?format=json");
ServerWebExchange exchange = MockServerHttpRequest.get("/flower.xyz?format=json").toExchange();
resolver.resolveMediaTypes(exchange);
}
@ -116,7 +112,7 @@ public class CompositeContentTypeResolverBuilderTests {
.mediaType("json", MediaType.APPLICATION_JSON)
.build();
ServerWebExchange exchange = createExchange("/flower?format=json");
ServerWebExchange exchange = MockServerHttpRequest.get("/flower?format=json").toExchange();
assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), resolver.resolveMediaTypes(exchange));
}
@ -127,7 +123,7 @@ public class CompositeContentTypeResolverBuilderTests {
.favorParameter(true)
.build();
ServerWebExchange exchange = createExchange("/flower?format=xyz");
ServerWebExchange exchange = MockServerHttpRequest.get("/flower?format=xyz").toExchange();
resolver.resolveMediaTypes(exchange);
}
@ -137,8 +133,7 @@ public class CompositeContentTypeResolverBuilderTests {
.ignoreAcceptHeader(true)
.build();
ServerHttpRequest request = MockServerHttpRequest.get("/flower").accept(MediaType.IMAGE_GIF).build();
ServerWebExchange exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
ServerWebExchange exchange = MockServerHttpRequest.get("/flower").accept(MediaType.IMAGE_GIF).toExchange();
assertEquals(Collections.<MediaType>emptyList(), resolver.resolveMediaTypes(exchange));
}
@ -149,8 +144,7 @@ public class CompositeContentTypeResolverBuilderTests {
.defaultContentType(MediaType.APPLICATION_JSON)
.build();
ServerHttpRequest request = MockServerHttpRequest.get("/").accept(MediaType.ALL).build();
ServerWebExchange exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
ServerWebExchange exchange = MockServerHttpRequest.get("/").accept(MediaType.ALL).toExchange();
assertEquals(Collections.singletonList(MediaType.APPLICATION_JSON), resolver.resolveMediaTypes(exchange));
}
@ -163,18 +157,12 @@ public class CompositeContentTypeResolverBuilderTests {
List<MediaType> expected = Collections.singletonList(MediaType.APPLICATION_JSON);
ServerWebExchange exchange = createExchange("/");
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
assertEquals(expected, resolver.resolveMediaTypes(exchange));
ServerHttpRequest request = MockServerHttpRequest.get("/").accept(MediaType.ALL).build();
exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
exchange = MockServerHttpRequest.get("/").accept(MediaType.ALL).toExchange();
assertEquals(expected, resolver.resolveMediaTypes(exchange));
}
private ServerWebExchange createExchange(String url) throws URISyntaxException {
ServerHttpRequest request = MockServerHttpRequest.get(url).build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
}

View File

@ -15,19 +15,15 @@
*/
package org.springframework.web.reactive.accept;
import java.net.URISyntaxException;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.NotAcceptableStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
@ -49,7 +45,8 @@ public class HeaderContentTypeResolverTests {
@Test
public void resolveMediaTypes() throws Exception {
ServerWebExchange exchange = createExchange("text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c");
String header = "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c";
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("accept", header).toExchange();
List<MediaType> mediaTypes = this.resolver.resolveMediaTypes(exchange);
assertEquals(4, mediaTypes.size());
@ -61,18 +58,9 @@ public class HeaderContentTypeResolverTests {
@Test(expected = NotAcceptableStatusException.class)
public void resolveMediaTypesParseError() throws Exception {
ServerWebExchange exchange = createExchange("textplain; q=0.5");
String header = "textplain; q=0.5";
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("accept", header).toExchange();
this.resolver.resolveMediaTypes(exchange);
}
private ServerWebExchange createExchange(String accept) throws URISyntaxException {
ServerHttpRequest request = (accept != null ?
MockServerHttpRequest.get("/").header("accept", accept).build() :
MockServerHttpRequest.get("/").build());
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.web.reactive.accept;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@ -23,14 +22,9 @@ import java.util.Map;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.NotAcceptableStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager;
import org.springframework.web.server.session.WebSessionManager;
import static org.junit.Assert.assertEquals;
@ -43,7 +37,7 @@ public class PathExtensionContentTypeResolverTests {
@Test
public void resolveMediaTypesFromMapping() throws Exception {
ServerWebExchange exchange = createExchange("/test.html");
ServerWebExchange exchange = MockServerHttpRequest.get("/test.html").toExchange();
PathExtensionContentTypeResolver resolver = new PathExtensionContentTypeResolver();
List<MediaType> mediaTypes = resolver.resolveMediaTypes(exchange);
@ -58,7 +52,7 @@ public class PathExtensionContentTypeResolverTests {
@Test
public void resolveMediaTypesFromJaf() throws Exception {
ServerWebExchange exchange = createExchange("test.xls");
ServerWebExchange exchange = MockServerHttpRequest.get("test.xls").toExchange();
PathExtensionContentTypeResolver resolver = new PathExtensionContentTypeResolver();
List<MediaType> mediaTypes = resolver.resolveMediaTypes(exchange);
@ -69,7 +63,7 @@ public class PathExtensionContentTypeResolverTests {
@Test
public void getMediaTypeFromFilenameNoJaf() throws Exception {
ServerWebExchange exchange = createExchange("test.json");
ServerWebExchange exchange = MockServerHttpRequest.get("test.json").toExchange();
PathExtensionContentTypeResolver resolver = new PathExtensionContentTypeResolver();
resolver.setUseJaf(false);
List<MediaType> mediaTypes = resolver.resolveMediaTypes(exchange);
@ -81,7 +75,7 @@ public class PathExtensionContentTypeResolverTests {
@Test
public void getMediaTypeFilenameWithEncodedURI() throws Exception {
ServerWebExchange exchange = createExchange("/quo%20vadis%3f.html");
ServerWebExchange exchange = MockServerHttpRequest.get("/quo%20vadis%3f.html").toExchange();
PathExtensionContentTypeResolver resolver = new PathExtensionContentTypeResolver();
List<MediaType> result = resolver.resolveMediaTypes(exchange);
@ -92,7 +86,7 @@ public class PathExtensionContentTypeResolverTests {
@Test
public void resolveMediaTypesIgnoreUnknownExtension() throws Exception {
ServerWebExchange exchange = createExchange("test.xyz");
ServerWebExchange exchange = MockServerHttpRequest.get("test.xyz").toExchange();
PathExtensionContentTypeResolver resolver = new PathExtensionContentTypeResolver();
List<MediaType> mediaTypes = resolver.resolveMediaTypes(exchange);
@ -101,17 +95,10 @@ public class PathExtensionContentTypeResolverTests {
@Test(expected = NotAcceptableStatusException.class)
public void resolveMediaTypesDoNotIgnoreUnknownExtension() throws Exception {
ServerWebExchange exchange = createExchange("test.xyz");
ServerWebExchange exchange = MockServerHttpRequest.get("test.xyz").toExchange();
PathExtensionContentTypeResolver resolver = new PathExtensionContentTypeResolver();
resolver.setIgnoreUnknownExtensions(false);
resolver.resolveMediaTypes(exchange);
}
private ServerWebExchange createExchange(String path) throws URISyntaxException {
ServerHttpRequest request = MockServerHttpRequest.get(path).build();
WebSessionManager sessionManager = new MockWebSessionManager();
return new DefaultServerWebExchange(request, new MockServerHttpResponse(), sessionManager);
}
}

View File

@ -17,6 +17,7 @@
package org.springframework.web.reactive.config;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
@ -31,7 +32,7 @@ import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import org.springframework.http.CacheControl;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.resource.AppCacheManifestTransformer;
@ -44,10 +45,12 @@ import org.springframework.web.reactive.resource.ResourceTransformer;
import org.springframework.web.reactive.resource.ResourceWebHandler;
import org.springframework.web.reactive.resource.VersionResourceResolver;
import org.springframework.web.reactive.resource.WebJarsResourceResolver;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for {@link ResourceHandlerRegistry}.
@ -60,20 +63,12 @@ public class ResourceHandlerRegistryTests {
private ResourceHandlerRegistration registration;
private ServerWebExchange exchange;
private MockServerHttpResponse response;
@Before
public void setup() {
this.registry = new ResourceHandlerRegistry(new GenericApplicationContext());
this.registration = this.registry.addResourceHandler("/resources/**");
this.registration.addResourceLocations("classpath:org/springframework/web/reactive/config/");
MockServerHttpRequest request = MockServerHttpRequest.get("").build();
this.response = new MockServerHttpResponse();
this.exchange = new DefaultServerWebExchange(request, this.response);
}
@ -85,13 +80,13 @@ public class ResourceHandlerRegistryTests {
@Test
public void mapPathToLocation() throws Exception {
this.exchange.getAttributes().put(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/testStylesheet.css");
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
exchange.getAttributes().put(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/testStylesheet.css");
ResourceWebHandler handler = getHandler("/resources/**");
handler.handle(this.exchange).blockMillis(5000);
handler.handle(exchange).block(Duration.ofSeconds(5));
StepVerifier.create(this.response.getBody())
StepVerifier.create(exchange.getResponse().getBody())
.consumeNextWith(buf -> assertEquals("test stylesheet content",
DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8)))
.expectComplete()

View File

@ -21,7 +21,6 @@ import java.util.Collections;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
@ -43,7 +42,6 @@ import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.http.codec.xml.Jaxb2XmlDecoder;
import org.springframework.http.codec.xml.Jaxb2XmlEncoder;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.validation.Validator;
@ -62,11 +60,19 @@ import org.springframework.web.reactive.result.view.ViewResolutionResultHandler;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.springframework.http.MediaType.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM;
import static org.springframework.http.MediaType.APPLICATION_XML;
import static org.springframework.http.MediaType.IMAGE_PNG;
import static org.springframework.http.MediaType.TEXT_PLAIN;
/**
* Unit tests for {@link WebFluxConfigurationSupport}.
@ -74,14 +80,6 @@ import static org.springframework.http.MediaType.*;
*/
public class WebFluxConfigurationSupportTests {
private MockServerHttpRequest request;
@Before
public void setup() throws Exception {
this.request = MockServerHttpRequest.get("/").build();
}
@Test
public void requestMappingHandlerMapping() throws Exception {
@ -101,12 +99,12 @@ public class WebFluxConfigurationSupportTests {
RequestedContentTypeResolver resolver = context.getBean(name, RequestedContentTypeResolver.class);
assertSame(resolver, mapping.getContentTypeResolver());
this.request = MockServerHttpRequest.get("/path.json").build();
ServerWebExchange exchange = MockServerHttpRequest.get("/path.json").toExchange();
List<MediaType> list = Collections.singletonList(MediaType.APPLICATION_JSON);
assertEquals(list, resolver.resolveMediaTypes(createExchange()));
assertEquals(list, resolver.resolveMediaTypes(exchange));
this.request = MockServerHttpRequest.get("/path.xml").build();
assertEquals(Collections.emptyList(), resolver.resolveMediaTypes(createExchange()));
exchange = MockServerHttpRequest.get("/path.xml").toExchange();
assertEquals(Collections.emptyList(), resolver.resolveMediaTypes(exchange));
}
@Test
@ -261,24 +259,14 @@ public class WebFluxConfigurationSupportTests {
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
private void assertHasMessageReader(List<HttpMessageReader<?>> readers, Class<?> clazz, MediaType mediaType) {
ResolvableType type = ResolvableType.forClass(clazz);
assertTrue(readers.stream()
.filter(c -> mediaType == null || c.canRead(type, mediaType))
.findAny()
.isPresent());
assertTrue(readers.stream().anyMatch(c -> mediaType == null || c.canRead(type, mediaType)));
}
private void assertHasMessageWriter(List<HttpMessageWriter<?>> writers, Class<?> clazz, MediaType mediaType) {
ResolvableType type = ResolvableType.forClass(clazz);
assertTrue(writers.stream()
.filter(c -> mediaType == null || c.canWrite(type, mediaType))
.findAny()
.isPresent());
assertTrue(writers.stream().anyMatch(c -> mediaType == null || c.canWrite(type, mediaType)));
}
private ApplicationContext loadConfig(Class<?>... configurationClasses) {

View File

@ -42,14 +42,12 @@ import org.springframework.http.MediaType;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager;
import static java.nio.charset.StandardCharsets.*;
import static org.junit.Assert.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
/**
* @author Arjen Poutsma
@ -191,10 +189,7 @@ public class DefaultEntityResponseBuilderTests {
Mono<EntityResponse<Publisher<String>>> result = EntityResponse.fromPublisher(publisher, String.class).build();
MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost").build();
MockServerHttpResponse mockResponse = new MockServerHttpResponse();
ServerWebExchange exchange =
new DefaultServerWebExchange(request, mockResponse, new MockWebSessionManager());
MockServerWebExchange exchange = MockServerHttpRequest.get("http://localhost").toExchange();
HandlerStrategies strategies = HandlerStrategies.empty().messageWriter(new EncoderHttpMessageWriter<>(new CharSequenceEncoder())).build();
@ -209,7 +204,7 @@ public class DefaultEntityResponseBuilderTests {
.expectComplete()
.verify();
assertNotNull(mockResponse.getBody());
assertNotNull(exchange.getResponse().getBody());
}
}

View File

@ -29,14 +29,12 @@ import reactor.test.StepVerifier;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.reactive.result.view.View;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Arjen Poutsma
@ -111,10 +109,7 @@ public class DefaultRenderingResponseTests {
Map<String, Object> model = Collections.singletonMap("foo", "bar");
Mono<RenderingResponse> result = RenderingResponse.create("view").modelAttributes(model).build();
MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost").build();
MockServerHttpResponse mockResponse = new MockServerHttpResponse();
ServerWebExchange exchange =
new DefaultServerWebExchange(request, mockResponse, new MockWebSessionManager());
MockServerWebExchange exchange = MockServerHttpRequest.get("http://localhost").toExchange();
ViewResolver viewResolver = mock(ViewResolver.class);
View view = mock(View.class);
when(viewResolver.resolveViewName("view", Locale.ENGLISH)).thenReturn(Mono.just(view));

View File

@ -31,11 +31,10 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
/**
* @author Arjen Poutsma
@ -49,10 +48,8 @@ public class ResourceHandlerFunctionTests {
@Test
public void get() throws IOException {
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("http://localhost").build();
MockServerHttpResponse mockResponse = new MockServerHttpResponse();
ServerWebExchange exchange = new DefaultServerWebExchange(mockRequest, mockResponse,
new MockWebSessionManager());
MockServerWebExchange exchange = MockServerHttpRequest.get("http://localhost").toExchange();
MockServerHttpResponse mockResponse = exchange.getResponse();
ServerRequest request = new DefaultServerRequest(exchange, HandlerStrategies.withDefaults());
@ -90,10 +87,8 @@ public class ResourceHandlerFunctionTests {
@Test
public void head() throws IOException {
MockServerHttpRequest mockRequest = MockServerHttpRequest.head("http://localhost").build();
MockServerHttpResponse mockResponse = new MockServerHttpResponse();
ServerWebExchange exchange = new DefaultServerWebExchange(mockRequest, mockResponse,
new MockWebSessionManager());
MockServerWebExchange exchange = MockServerHttpRequest.head("http://localhost").toExchange();
MockServerHttpResponse mockResponse = exchange.getResponse();
ServerRequest request = new DefaultServerRequest(exchange, HandlerStrategies.withDefaults());
@ -119,10 +114,8 @@ public class ResourceHandlerFunctionTests {
@Test
public void options() {
MockServerHttpRequest mockRequest = MockServerHttpRequest.options("http://localhost").build();
MockServerHttpResponse mockResponse = new MockServerHttpResponse();
ServerWebExchange exchange = new DefaultServerWebExchange(mockRequest, mockResponse,
new MockWebSessionManager());
MockServerWebExchange exchange = MockServerHttpRequest.options("http://localhost").toExchange();
MockServerHttpResponse mockResponse = exchange.getResponse();
ServerRequest request = new DefaultServerRequest(exchange, HandlerStrategies.withDefaults());

View File

@ -22,13 +22,10 @@ import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@ -63,7 +60,7 @@ public class CorsUrlHandlerMappingTests {
@Test
public void actualRequestWithoutCorsConfigurationProvider() throws Exception {
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/welcome.html", origin, "GET");
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/welcome.html", origin);
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
@ -73,7 +70,7 @@ public class CorsUrlHandlerMappingTests {
@Test
public void preflightRequestWithoutCorsConfigurationProvider() throws Exception {
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", origin, "GET");
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", origin);
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
@ -84,7 +81,7 @@ public class CorsUrlHandlerMappingTests {
@Test
public void actualRequestWithCorsAwareHandler() throws Exception {
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/cors.html", origin, "GET");
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/cors.html", origin);
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
@ -95,7 +92,7 @@ public class CorsUrlHandlerMappingTests {
@Test
public void preFlightWithCorsAwareHandler() throws Exception {
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/cors.html", origin, "GET");
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/cors.html", origin);
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
@ -110,7 +107,7 @@ public class CorsUrlHandlerMappingTests {
this.handlerMapping.setCorsConfigurations(Collections.singletonMap("/welcome.html", mappedConfig));
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/welcome.html", origin, "GET");
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/welcome.html", origin);
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
@ -125,7 +122,7 @@ public class CorsUrlHandlerMappingTests {
this.handlerMapping.setCorsConfigurations(Collections.singletonMap("/welcome.html", mappedConfig));
String origin = "http://domain2.com";
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", origin, "GET");
ServerWebExchange exchange = createExchange(HttpMethod.OPTIONS, "/welcome.html", origin);
Object actual = this.handlerMapping.getHandler(exchange).block();
assertNotNull(actual);
@ -134,15 +131,13 @@ public class CorsUrlHandlerMappingTests {
}
private ServerWebExchange createExchange(HttpMethod method, String path, String origin,
String accessControlRequestMethod) {
private ServerWebExchange createExchange(HttpMethod method, String path, String origin) {
ServerHttpRequest request = MockServerHttpRequest
return MockServerHttpRequest
.method(method, "http://localhost" + path)
.header("Origin", origin)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, accessControlRequestMethod)
.build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")
.toExchange();
}

View File

@ -16,7 +16,6 @@
package org.springframework.web.reactive.handler;
import java.net.URI;
import java.net.URISyntaxException;
import org.junit.Test;
@ -25,12 +24,9 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@ -103,7 +99,7 @@ public class SimpleUrlHandlerMappingTests {
}
private void testUrl(String url, Object bean, HandlerMapping handlerMapping, String pathWithinMapping) {
ServerWebExchange exchange = createExchange(url);
ServerWebExchange exchange = MockServerHttpRequest.method(HttpMethod.GET, URI.create(url)).toExchange();
Object actual = handlerMapping.getHandler(exchange).block();
if (bean != null) {
assertNotNull(actual);
@ -116,11 +112,6 @@ public class SimpleUrlHandlerMappingTests {
}
}
private ServerWebExchange createExchange(String path) {
ServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, URI.create(path)).build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
@Configuration
static class WebConfig {

View File

@ -29,12 +29,9 @@ import reactor.core.publisher.Mono;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
@ -82,7 +79,7 @@ public class AppCacheManifestTransformerTests {
@Test
public void noTransformIfExtensionNoMatch() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/static/foobar.file");
ServerWebExchange exchange = MockServerHttpRequest.get("/static/foobar.file").toExchange();
this.chain = mock(ResourceTransformerChain.class);
Resource resource = mock(Resource.class);
given(resource.getFilename()).willReturn("foobar.file");
@ -94,7 +91,7 @@ public class AppCacheManifestTransformerTests {
@Test
public void syntaxErrorInManifest() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/static/error.appcache");
ServerWebExchange exchange = MockServerHttpRequest.get("/static/error.appcache").toExchange();
this.chain = mock(ResourceTransformerChain.class);
Resource resource = new ClassPathResource("test/error.appcache", getClass());
given(this.chain.transform(exchange, resource)).willReturn(Mono.just(resource));
@ -105,7 +102,7 @@ public class AppCacheManifestTransformerTests {
@Test
public void transformManifest() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/static/test.appcache");
ServerWebExchange exchange = MockServerHttpRequest.get("/static/test.appcache").toExchange();
VersionResourceResolver versionResolver = new VersionResourceResolver();
versionResolver.setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy()));
@ -140,8 +137,4 @@ public class AppCacheManifestTransformerTests {
Matchers.containsString("# Hash: 4bf0338bcbeb0a5b3a4ec9ed8864107d"));
}
private ServerWebExchange createExchange(HttpMethod method, String url) {
MockServerHttpRequest request = MockServerHttpRequest.method(method, url).build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
}

View File

@ -16,6 +16,7 @@
package org.springframework.web.reactive.resource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
@ -28,8 +29,7 @@ import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@ -42,14 +42,15 @@ import static org.junit.Assert.assertSame;
*/
public class CachingResourceResolverTests {
private static final Duration TIMEOUT = Duration.ofSeconds(5);
private Cache cache;
private ResourceResolverChain chain;
private List<Resource> locations;
private MockServerHttpRequest request;
@Before
public void setup() {
@ -63,8 +64,6 @@ public class CachingResourceResolverTests {
this.locations = new ArrayList<>();
this.locations.add(new ClassPathResource("test/", getClass()));
this.request = MockServerHttpRequest.get("").build();
}
@ -72,7 +71,8 @@ public class CachingResourceResolverTests {
public void resolveResourceInternal() {
String file = "bar.css";
Resource expected = new ClassPathResource("test/" + file, getClass());
Resource actual = this.chain.resolveResource(createExchange(), file, this.locations).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
Resource actual = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT);
assertEquals(expected, actual);
}
@ -84,20 +84,22 @@ public class CachingResourceResolverTests {
this.cache.put(CachingResourceResolver.RESOLVED_RESOURCE_CACHE_KEY_PREFIX + "bar.css", expected);
String file = "bar.css";
Resource actual = this.chain.resolveResource(createExchange(), file, this.locations).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
Resource actual = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT);
assertSame(expected, actual);
}
@Test
public void resolveResourceInternalNoMatch() {
assertNull(this.chain.resolveResource(createExchange(), "invalid.css", this.locations).blockMillis(5000));
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
assertNull(this.chain.resolveResource(exchange, "invalid.css", this.locations).block(TIMEOUT));
}
@Test
public void resolverUrlPath() {
String expected = "/foo.css";
String actual = this.chain.resolveUrlPath(expected, this.locations).blockMillis(5000);
String actual = this.chain.resolveUrlPath(expected, this.locations).block(TIMEOUT);
assertEquals(expected, actual);
}
@ -106,22 +108,23 @@ public class CachingResourceResolverTests {
public void resolverUrlPathFromCache() {
String expected = "cached-imaginary.css";
this.cache.put(CachingResourceResolver.RESOLVED_URL_PATH_CACHE_KEY_PREFIX + "imaginary.css", expected);
String actual = this.chain.resolveUrlPath("imaginary.css", this.locations).blockMillis(5000);
String actual = this.chain.resolveUrlPath("imaginary.css", this.locations).block(TIMEOUT);
assertEquals(expected, actual);
}
@Test
public void resolverUrlPathNoMatch() {
assertNull(this.chain.resolveUrlPath("invalid.css", this.locations).blockMillis(5000));
assertNull(this.chain.resolveUrlPath("invalid.css", this.locations).block(TIMEOUT));
}
@Test
public void resolveResourceAcceptEncodingInCacheKey() {
String file = "bar.css";
this.request = MockServerHttpRequest.get(file).header("Accept-Encoding", "gzip").build();
MockServerWebExchange exchange = MockServerHttpRequest.get(file)
.header("Accept-Encoding", "gzip").toExchange();
Resource expected = this.chain.resolveResource(createExchange(), file, this.locations).blockMillis(5000);
Resource expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT);
String cacheKey = CachingResourceResolver.RESOLVED_RESOURCE_CACHE_KEY_PREFIX + file + "+encoding=gzip";
assertEquals(expected, this.cache.get(cacheKey).get());
@ -130,9 +133,9 @@ public class CachingResourceResolverTests {
@Test
public void resolveResourceNoAcceptEncodingInCacheKey() {
String file = "bar.css";
this.request = MockServerHttpRequest.get(file).build();
MockServerWebExchange exchange = MockServerHttpRequest.get(file).toExchange();
Resource expected = this.chain.resolveResource(createExchange(), file, this.locations).blockMillis(5000);
Resource expected = this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT);
String cacheKey = CachingResourceResolver.RESOLVED_RESOURCE_CACHE_KEY_PREFIX + file;
assertEquals(expected, this.cache.get(cacheKey).get());
@ -146,16 +149,11 @@ public class CachingResourceResolverTests {
this.cache.put(CachingResourceResolver.RESOLVED_RESOURCE_CACHE_KEY_PREFIX + "bar.css+encoding=gzip", gzResource);
String file = "bar.css";
this.request = MockServerHttpRequest.get(file).build();
assertSame(resource, this.chain.resolveResource(createExchange(), file, this.locations).blockMillis(5000));
MockServerWebExchange exchange = MockServerHttpRequest.get(file).toExchange();
assertSame(resource, this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT));
this.request = MockServerHttpRequest.get(file).header("Accept-Encoding", "gzip").build();
assertSame(gzResource, this.chain.resolveResource(createExchange(), file, this.locations).blockMillis(5000));
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
exchange = MockServerHttpRequest.get(file).header("Accept-Encoding", "gzip").toExchange();
assertSame(gzResource, this.chain.resolveResource(exchange, file, this.locations).block(TIMEOUT));
}
}

View File

@ -32,15 +32,12 @@ import reactor.test.StepVerifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
/**
* Unit tests for {@link CssLinkResourceTransformer}.
@ -79,7 +76,7 @@ public class CssLinkResourceTransformerTests {
@Test
public void transform() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/static/main.css");
MockServerWebExchange exchange = MockServerHttpRequest.get("/static/main.css").toExchange();
Resource css = new ClassPathResource("test/main.css", getClass());
String expected = "\n" +
@ -101,7 +98,7 @@ public class CssLinkResourceTransformerTests {
@Test
public void transformNoLinks() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/static/foo.css");
MockServerWebExchange exchange = MockServerHttpRequest.get("/static/foo.css").toExchange();
Resource expected = new ClassPathResource("test/foo.css", getClass());
StepVerifier.create(this.transformerChain.transform(exchange, expected))
.consumeNextWith(resource -> assertSame(expected, resource))
@ -110,7 +107,7 @@ public class CssLinkResourceTransformerTests {
@Test
public void transformExtLinksNotAllowed() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/static/external.css");
MockServerWebExchange exchange = MockServerHttpRequest.get("/static/external.css").toExchange();
ResourceResolverChain resolverChain = Mockito.mock(DefaultResourceResolverChain.class);
ResourceTransformerChain transformerChain = new DefaultResourceTransformerChain(resolverChain,
Collections.singletonList(new CssLinkResourceTransformer()));
@ -136,7 +133,7 @@ public class CssLinkResourceTransformerTests {
@Test
public void transformWithNonCssResource() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/static/images/image.png");
MockServerWebExchange exchange = MockServerHttpRequest.get("/static/images/image.png").toExchange();
Resource expected = new ClassPathResource("test/images/image.png", getClass());
StepVerifier.create(this.transformerChain.transform(exchange, expected))
.expectNext(expected)
@ -145,7 +142,7 @@ public class CssLinkResourceTransformerTests {
@Test
public void transformWithGzippedResource() throws Exception {
ServerWebExchange exchange = createExchange(HttpMethod.GET, "/static/main.css");
MockServerWebExchange exchange = MockServerHttpRequest.get("/static/main.css").toExchange();
Resource original = new ClassPathResource("test/main.css", getClass());
createTempCopy("main.css", "main.css.gz");
GzipResourceResolver.GzippedResource expected = new GzipResourceResolver.GzippedResource(original);
@ -163,10 +160,4 @@ public class CssLinkResourceTransformerTests {
copy.toFile().deleteOnExit();
}
private ServerWebExchange createExchange(HttpMethod method, String url) {
MockServerHttpRequest request = MockServerHttpRequest.method(method, url).build();
ServerHttpResponse response = new MockServerHttpResponse();
return new DefaultServerWebExchange(request, response);
}
}

View File

@ -22,6 +22,7 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@ -38,11 +39,12 @@ import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
@ -52,12 +54,13 @@ import static org.junit.Assert.*;
*/
public class GzipResourceResolverTests {
private static final Duration TIMEOUT = Duration.ofSeconds(5);
private ResourceResolverChain resolver;
private List<Resource> locations;
private MockServerHttpRequest request;
@BeforeClass
public static void createGzippedResources() throws IOException {
@ -96,17 +99,16 @@ public class GzipResourceResolverTests {
this.locations = new ArrayList<>();
this.locations.add(new ClassPathResource("test/", getClass()));
this.locations.add(new ClassPathResource("testalternatepath/", getClass()));
this.request = MockServerHttpRequest.get("").build();
}
@Test
public void resolveGzippedFile() throws IOException {
this.request = MockServerHttpRequest.get("").header("Accept-Encoding", "gzip").build();
MockServerWebExchange exchange = MockServerHttpRequest.get("")
.header("Accept-Encoding", "gzip").toExchange();
String file = "js/foo.js";
Resource resolved = this.resolver.resolveResource(createExchange(), file, this.locations).blockMillis(5000);
Resource resolved = this.resolver.resolveResource(exchange, file, this.locations).block(TIMEOUT);
String gzFile = file+".gz";
Resource resource = new ClassPathResource("test/" + gzFile, getClass());
@ -118,10 +120,11 @@ public class GzipResourceResolverTests {
@Test
public void resolveFingerprintedGzippedFile() throws IOException {
this.request = MockServerHttpRequest.get("").header("Accept-Encoding", "gzip").build();
MockServerWebExchange exchange = MockServerHttpRequest.get("")
.header("Accept-Encoding", "gzip").toExchange();
String file = "foo-e36d2e05253c6c7085a91522ce43a0b4.css";
Resource resolved = this.resolver.resolveResource(createExchange(), file, this.locations).blockMillis(5000);
Resource resolved = this.resolver.resolveResource(exchange, file, this.locations).block(TIMEOUT);
String gzFile = file + ".gz";
Resource resource = new ClassPathResource("test/" + gzFile, getClass());
@ -133,10 +136,11 @@ public class GzipResourceResolverTests {
@Test
public void resolveFromCacheWithEncodingVariants() throws IOException {
this.request = MockServerHttpRequest.get("").header("Accept-Encoding", "gzip").build();
MockServerWebExchange exchange = MockServerHttpRequest.get("")
.header("Accept-Encoding", "gzip").toExchange();
String file = "js/foo.js";
Resource resolved = this.resolver.resolveResource(createExchange(), file, this.locations).blockMillis(5000);
Resource resolved = this.resolver.resolveResource(exchange, file, this.locations).block(TIMEOUT);
String gzFile = file+".gz";
Resource gzResource = new ClassPathResource("test/"+gzFile, getClass());
@ -147,8 +151,8 @@ public class GzipResourceResolverTests {
// resolved resource is now cached in CachingResourceResolver
this.request = MockServerHttpRequest.get("/js/foo.js").build();
resolved = this.resolver.resolveResource(createExchange(), file, this.locations).blockMillis(5000);
exchange = MockServerHttpRequest.get("/js/foo.js").toExchange();
resolved = this.resolver.resolveResource(exchange, file, this.locations).block(TIMEOUT);
Resource resource = new ClassPathResource("test/"+file, getClass());
assertEquals(resource.getDescription(), resolved.getDescription());
@ -160,7 +164,7 @@ public class GzipResourceResolverTests {
@Test // SPR-13149
public void resolveWithNullRequest() throws IOException {
String file = "js/foo.js";
Resource resolved = this.resolver.resolveResource(null, file, this.locations).blockMillis(5000);
Resource resolved = this.resolver.resolveResource(null, file, this.locations).block(TIMEOUT);
String gzFile = file+".gz";
Resource gzResource = new ClassPathResource("test/" + gzFile, getClass());
@ -170,9 +174,4 @@ public class GzipResourceResolverTests {
resolved instanceof HttpResource);
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
}

View File

@ -16,6 +16,7 @@
package org.springframework.web.reactive.resource;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@ -27,11 +28,10 @@ import reactor.core.publisher.Mono;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for {@code ResourceTransformerSupport}.
@ -45,8 +45,6 @@ public class ResourceTransformerSupportTests {
private TestResourceTransformerSupport transformer;
private MockServerHttpRequest request;
@Before
public void setup() {
@ -59,8 +57,6 @@ public class ResourceTransformerSupportTests {
this.transformer = new TestResourceTransformerSupport();
this.transformer.setResourceUrlProvider(createResourceUrlProvider(resolvers));
this.request = MockServerHttpRequest.get("").build();
}
private ResourceUrlProvider createResourceUrlProvider(List<ResourceResolver> resolvers) {
@ -75,11 +71,11 @@ public class ResourceTransformerSupportTests {
@Test
public void resolveUrlPath() throws Exception {
this.request = MockServerHttpRequest.get("/resources/main.css").build();
MockServerWebExchange exchange = MockServerHttpRequest.get("/resources/main.css").toExchange();
String resourcePath = "/resources/bar.css";
Resource css = new ClassPathResource("test/main.css", getClass());
String actual = this.transformer.resolveUrlPath(
resourcePath, createExchange(), css, this.transformerChain).blockMillis(5000);
resourcePath, exchange, css, this.transformerChain).block(Duration.ofSeconds(5));
assertEquals("/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", actual);
assertEquals("/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", actual);
@ -88,8 +84,9 @@ public class ResourceTransformerSupportTests {
@Test
public void resolveUrlPathWithRelativePath() throws Exception {
Resource css = new ClassPathResource("test/main.css", getClass());
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
String actual = this.transformer.resolveUrlPath(
"bar.css", createExchange(), css, this.transformerChain).blockMillis(5000);
"bar.css", exchange, css, this.transformerChain).block(Duration.ofSeconds(5));
assertEquals("bar-11e16cf79faee7ac698c805cf28248d2.css", actual);
}
@ -97,18 +94,14 @@ public class ResourceTransformerSupportTests {
@Test
public void resolveUrlPathWithRelativePathInParentDirectory() throws Exception {
Resource imagePng = new ClassPathResource("test/images/image.png", getClass());
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
String actual = this.transformer.resolveUrlPath(
"../bar.css", createExchange(), imagePng, this.transformerChain).blockMillis(5000);
"../bar.css", exchange, imagePng, this.transformerChain).block(Duration.ofSeconds(5));
assertEquals("../bar-11e16cf79faee7ac698c805cf28248d2.css", actual);
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
private static class TestResourceTransformerSupport extends ResourceTransformerSupport {
@Override

View File

@ -16,6 +16,7 @@
package org.springframework.web.reactive.resource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@ -30,14 +31,14 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
/**
@ -69,22 +70,20 @@ public class ResourceUrlProviderTests {
@Test
public void getStaticResourceUrl() {
String url = this.urlProvider.getForLookupPath("/resources/foo.css").blockMillis(5000);
String url = this.urlProvider.getForLookupPath("/resources/foo.css").block(Duration.ofSeconds(5));
assertEquals("/resources/foo.css", url);
}
@Test // SPR-13374
public void getStaticResourceUrlRequestWithQueryOrHash() {
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
ServerWebExchange exchange = new DefaultServerWebExchange(request, response);
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
String url = "/resources/foo.css?foo=bar&url=http://example.org";
String resolvedUrl = this.urlProvider.getForRequestUrl(exchange, url).blockMillis(5000);
String resolvedUrl = this.urlProvider.getForRequestUrl(exchange, url).block(Duration.ofSeconds(5));
assertEquals(url, resolvedUrl);
url = "/resources/foo.css#hash";
resolvedUrl = this.urlProvider.getForRequestUrl(exchange, url).blockMillis(5000);
resolvedUrl = this.urlProvider.getForRequestUrl(exchange, url).block(Duration.ofSeconds(5));
assertEquals(url, resolvedUrl);
}
@ -100,7 +99,7 @@ public class ResourceUrlProviderTests {
resolvers.add(new PathResourceResolver());
this.handler.setResourceResolvers(resolvers);
String url = this.urlProvider.getForLookupPath("/resources/foo.css").blockMillis(5000);
String url = this.urlProvider.getForLookupPath("/resources/foo.css").block(Duration.ofSeconds(5));
assertEquals("/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css", url);
}
@ -121,7 +120,7 @@ public class ResourceUrlProviderTests {
this.handlerMap.put("/resources/*.css", otherHandler);
this.urlProvider.setHandlerMap(this.handlerMap);
String url = this.urlProvider.getForLookupPath("/resources/foo.css").blockMillis(5000);
String url = this.urlProvider.getForLookupPath("/resources/foo.css").block(Duration.ofSeconds(5));
assertEquals("/resources/foo-e36d2e05253c6c7085a91522ce43a0b4.css", url);
}

View File

@ -18,6 +18,7 @@ package org.springframework.web.reactive.resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@ -45,15 +46,19 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.accept.CompositeContentTypeResolver;
import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
import org.springframework.web.server.MethodNotAllowedException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link ResourceWebHandler}.
@ -62,12 +67,11 @@ import static org.junit.Assert.*;
*/
public class ResourceWebHandlerTests {
private static final Duration TIMEOUT = Duration.ofSeconds(1);
private ResourceWebHandler handler;
private MockServerHttpRequest request;
private MockServerHttpResponse response;
private DataBufferFactory bufferFactory = new DefaultDataBufferFactory();
@ -83,18 +87,16 @@ public class ResourceWebHandlerTests {
this.handler.setCacheControl(CacheControl.maxAge(3600, TimeUnit.SECONDS));
this.handler.afterPropertiesSet();
this.handler.afterSingletonsInstantiated();
this.request = MockServerHttpRequest.get("").build();
this.response = new MockServerHttpResponse();
}
@Test
public void getResource() throws Exception {
ServerWebExchange exchange = createExchange("foo.css");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.handle(exchange).block(TIMEOUT);
HttpHeaders headers = this.response.getHeaders();
HttpHeaders headers = exchange.getResponse().getHeaders();
assertEquals(MediaType.parseMediaType("text/css"), headers.getContentType());
assertEquals(17, headers.getContentLength());
assertEquals("max-age=3600", headers.getCacheControl());
@ -102,17 +104,17 @@ public class ResourceWebHandlerTests {
assertEquals(headers.getLastModified() / 1000, resourceLastModifiedDate("test/foo.css") / 1000);
assertEquals("bytes", headers.getFirst("Accept-Ranges"));
assertEquals(1, headers.get("Accept-Ranges").size());
assertResponseBody("h1 { color:red; }");
assertResponseBody(exchange, "h1 { color:red; }");
}
@Test
public void getResourceHttpHeader() throws Exception {
this.request = MockServerHttpRequest.head("").build();
ServerWebExchange exchange = createExchange("foo.css");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.head("").toExchange();
setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.handle(exchange).block(TIMEOUT);
assertNull(this.response.getStatusCode());
HttpHeaders headers = this.response.getHeaders();
assertNull(exchange.getResponse().getStatusCode());
HttpHeaders headers = exchange.getResponse().getHeaders();
assertEquals(MediaType.parseMediaType("text/css"), headers.getContentType());
assertEquals(17, headers.getContentLength());
assertEquals("max-age=3600", headers.getCacheControl());
@ -121,32 +123,34 @@ public class ResourceWebHandlerTests {
assertEquals("bytes", headers.getFirst("Accept-Ranges"));
assertEquals(1, headers.get("Accept-Ranges").size());
StepVerifier.create(this.response.getBody())
StepVerifier.create(exchange.getResponse().getBody())
.expectErrorMatches(ex -> ex.getMessage().startsWith("The body is not set."))
.verify();
}
@Test
public void getResourceHttpOptions() throws Exception {
this.request = MockServerHttpRequest.options("").build();
ServerWebExchange exchange = createExchange("foo.css");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.options("").toExchange();
setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.handle(exchange).block(TIMEOUT);
assertNull(this.response.getStatusCode());
assertEquals("GET,HEAD,OPTIONS", this.response.getHeaders().getFirst("Allow"));
assertNull(exchange.getResponse().getStatusCode());
assertEquals("GET,HEAD,OPTIONS", exchange.getResponse().getHeaders().getFirst("Allow"));
}
@Test
public void getResourceNoCache() throws Exception {
ServerWebExchange exchange = createExchange("foo.css");
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.setCacheControl(CacheControl.noStore());
this.handler.handle(exchange).blockMillis(5000);
this.handler.handle(exchange).block(TIMEOUT);
assertEquals("no-store", this.response.getHeaders().getCacheControl());
assertTrue(this.response.getHeaders().containsKey("Last-Modified"));
assertEquals(this.response.getHeaders().getLastModified() / 1000, resourceLastModifiedDate("test/foo.css") / 1000);
assertEquals("bytes", this.response.getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, this.response.getHeaders().get("Accept-Ranges").size());
MockServerHttpResponse response = exchange.getResponse();
assertEquals("no-store", response.getHeaders().getCacheControl());
assertTrue(response.getHeaders().containsKey("Last-Modified"));
assertEquals(response.getHeaders().getLastModified() / 1000, resourceLastModifiedDate("test/foo.css") / 1000);
assertEquals("bytes", response.getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, response.getHeaders().get("Accept-Ranges").size());
}
@Test
@ -157,20 +161,22 @@ public class ResourceWebHandlerTests {
this.handler.afterPropertiesSet();
this.handler.afterSingletonsInstantiated();
ServerWebExchange exchange = createExchange("versionString/foo.css");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "versionString/foo.css");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals("\"versionString\"", this.response.getHeaders().getETag());
assertEquals("bytes", this.response.getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, this.response.getHeaders().get("Accept-Ranges").size());
assertEquals("\"versionString\"", exchange.getResponse().getHeaders().getETag());
assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size());
}
@Test
public void getResourceWithHtmlMediaType() throws Exception {
ServerWebExchange exchange = createExchange("foo.html");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "foo.html");
this.handler.handle(exchange).block(TIMEOUT);
HttpHeaders headers = this.response.getHeaders();
HttpHeaders headers = exchange.getResponse().getHeaders();
assertEquals(MediaType.TEXT_HTML, headers.getContentType());
assertEquals("max-age=3600", headers.getCacheControl());
assertTrue(headers.containsKey("Last-Modified"));
@ -181,10 +187,11 @@ public class ResourceWebHandlerTests {
@Test
public void getResourceFromAlternatePath() throws Exception {
ServerWebExchange exchange = createExchange("baz.css");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "baz.css");
this.handler.handle(exchange).block(TIMEOUT);
HttpHeaders headers = this.response.getHeaders();
HttpHeaders headers = exchange.getResponse().getHeaders();
assertEquals(MediaType.parseMediaType("text/css"), headers.getContentType());
assertEquals(17, headers.getContentLength());
assertEquals("max-age=3600", headers.getCacheControl());
@ -192,25 +199,27 @@ public class ResourceWebHandlerTests {
assertEquals(headers.getLastModified() / 1000, resourceLastModifiedDate("testalternatepath/baz.css") / 1000);
assertEquals("bytes", headers.getFirst("Accept-Ranges"));
assertEquals(1, headers.get("Accept-Ranges").size());
assertResponseBody("h1 { color:red; }");
assertResponseBody(exchange, "h1 { color:red; }");
}
@Test
public void getResourceFromSubDirectory() throws Exception {
ServerWebExchange exchange = createExchange("js/foo.js");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "js/foo.js");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(MediaType.parseMediaType("text/javascript"), this.response.getHeaders().getContentType());
assertResponseBody("function foo() { console.log(\"hello world\"); }");
assertEquals(MediaType.parseMediaType("text/javascript"), exchange.getResponse().getHeaders().getContentType());
assertResponseBody(exchange, "function foo() { console.log(\"hello world\"); }");
}
@Test
public void getResourceFromSubDirectoryOfAlternatePath() throws Exception {
ServerWebExchange exchange = createExchange("js/baz.js");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "js/baz.js");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(MediaType.parseMediaType("text/javascript"), this.response.getHeaders().getContentType());
assertResponseBody("function foo() { console.log(\"hello world\"); }");
assertEquals(MediaType.parseMediaType("text/javascript"), exchange.getResponse().getHeaders().getContentType());
assertResponseBody(exchange, "function foo() { console.log(\"hello world\"); }");
}
@Test // SPR-13658
@ -226,11 +235,12 @@ public class ResourceWebHandlerTests {
handler.afterPropertiesSet();
handler.afterSingletonsInstantiated();
ServerWebExchange exchange = createExchange("foo.css");
handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "foo.css");
handler.handle(exchange).block(TIMEOUT);
assertEquals(MediaType.parseMediaType("foo/bar"), this.response.getHeaders().getContentType());
assertResponseBody("h1 { color:red; }");
assertEquals(MediaType.parseMediaType("foo/bar"), exchange.getResponse().getHeaders().getContentType());
assertResponseBody(exchange, "h1 { color:red; }");
}
@Test // SPR-14577
@ -246,11 +256,12 @@ public class ResourceWebHandlerTests {
handler.afterPropertiesSet();
handler.afterSingletonsInstantiated();
this.request = MockServerHttpRequest.get("").header("Accept", "application/json,text/plain,*/*").build();
ServerWebExchange exchange = createExchange("foo.html");
handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("")
.header("Accept", "application/json,text/plain,*/*").toExchange();
setPathWithinHandlerMapping(exchange, "foo.html");
handler.handle(exchange).block(TIMEOUT);
assertEquals(MediaType.TEXT_HTML, this.response.getHeaders().getContentType());
assertEquals(MediaType.TEXT_HTML, exchange.getResponse().getHeaders().getContentType());
}
@Test
@ -287,21 +298,21 @@ public class ResourceWebHandlerTests {
}
private void testInvalidPath(HttpMethod httpMethod, String requestPath, Resource location) throws Exception {
this.request = MockServerHttpRequest.method(httpMethod, "").build();
this.response = new MockServerHttpResponse();
ServerWebExchange exchange = createExchange(requestPath);
this.handler.handle(exchange).blockMillis(5000);
ServerWebExchange exchange = MockServerHttpRequest.method(httpMethod, "").toExchange();
setPathWithinHandlerMapping(exchange, requestPath);
this.handler.handle(exchange).block(TIMEOUT);
if (!location.createRelative(requestPath).exists() && !requestPath.contains(":")) {
fail(requestPath + " doesn't actually exist as a relative path");
}
assertEquals(HttpStatus.NOT_FOUND, this.response.getStatusCode());
assertEquals(HttpStatus.NOT_FOUND, exchange.getResponse().getStatusCode());
}
@Test
public void ignoreInvalidEscapeSequence() throws Exception {
ServerWebExchange exchange = createExchange("/%foo%/bar.txt");
this.handler.handle(exchange).blockMillis(5000);
assertEquals(HttpStatus.NOT_FOUND, this.response.getStatusCode());
ServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "/%foo%/bar.txt");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(HttpStatus.NOT_FOUND, exchange.getResponse().getStatusCode());
}
@Test
@ -365,57 +376,61 @@ public class ResourceWebHandlerTests {
@Test
public void notModified() throws Exception {
this.request = MockServerHttpRequest.get("").ifModifiedSince(resourceLastModified("test/foo.css")).build();
ServerWebExchange exchange = createExchange("foo.css");
this.handler.handle(exchange).blockMillis(5000);
assertEquals(HttpStatus.NOT_MODIFIED, this.response.getStatusCode());
MockServerWebExchange exchange = MockServerHttpRequest.get("")
.ifModifiedSince(resourceLastModified("test/foo.css")).toExchange();
setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(HttpStatus.NOT_MODIFIED, exchange.getResponse().getStatusCode());
}
@Test
public void modified() throws Exception {
long timestamp = resourceLastModified("test/foo.css") / 1000 * 1000 - 1;
this.request = MockServerHttpRequest.get("").ifModifiedSince(timestamp).build();
ServerWebExchange exchange = createExchange("foo.css");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").ifModifiedSince(timestamp).toExchange();
setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.handle(exchange).block(TIMEOUT);
assertNull(this.response.getStatusCode());
assertResponseBody("h1 { color:red; }");
assertNull(exchange.getResponse().getStatusCode());
assertResponseBody(exchange, "h1 { color:red; }");
}
@Test
public void directory() throws Exception {
ServerWebExchange exchange = createExchange("js/");
this.handler.handle(exchange).blockMillis(5000);
assertEquals(HttpStatus.NOT_FOUND, this.response.getStatusCode());
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "js/");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(HttpStatus.NOT_FOUND, exchange.getResponse().getStatusCode());
}
@Test
public void directoryInJarFile() throws Exception {
ServerWebExchange exchange = createExchange("underscorejs/");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "underscorejs/");
this.handler.handle(exchange).block(TIMEOUT);
assertNull(this.response.getStatusCode());
assertEquals(0, this.response.getHeaders().getContentLength());
assertNull(exchange.getResponse().getStatusCode());
assertEquals(0, exchange.getResponse().getHeaders().getContentLength());
}
@Test
public void missingResourcePath() throws Exception {
ServerWebExchange exchange = createExchange("");
this.handler.handle(exchange).blockMillis(5000);
assertEquals(HttpStatus.NOT_FOUND, this.response.getStatusCode());
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
setPathWithinHandlerMapping(exchange, "");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(HttpStatus.NOT_FOUND, exchange.getResponse().getStatusCode());
}
@Test(expected = IllegalStateException.class)
public void noPathWithinHandlerMappingAttribute() throws Exception {
ServerWebExchange exchange = new DefaultServerWebExchange(this.request, this.response);
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
this.handler.handle(exchange).block(TIMEOUT);
}
@Test(expected = MethodNotAllowedException.class)
public void unsupportedHttpMethod() throws Exception {
this.request = MockServerHttpRequest.post("").build();
ServerWebExchange exchange = createExchange("foo.css");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.post("").toExchange();
setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.handle(exchange).block(TIMEOUT);
}
@Test
@ -426,115 +441,114 @@ public class ResourceWebHandlerTests {
}
private void resourceNotFound(HttpMethod httpMethod) throws Exception {
this.request = MockServerHttpRequest.method(httpMethod, "").build();
this.response = new MockServerHttpResponse();
ServerWebExchange exchange = createExchange("not-there.css");
this.handler.handle(exchange).blockMillis(5000);
assertEquals(HttpStatus.NOT_FOUND, this.response.getStatusCode());
MockServerWebExchange exchange = MockServerHttpRequest.method(httpMethod, "").toExchange();
setPathWithinHandlerMapping(exchange, "not-there.css");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(HttpStatus.NOT_FOUND, exchange.getResponse().getStatusCode());
}
@Test
public void partialContentByteRange() throws Exception {
this.request = MockServerHttpRequest.get("").header("Range", "bytes=0-1").build();
ServerWebExchange exchange = createExchange("foo.txt");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").header("Range", "bytes=0-1").toExchange();
setPathWithinHandlerMapping(exchange, "foo.txt");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(HttpStatus.PARTIAL_CONTENT, this.response.getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, this.response.getHeaders().getContentType());
assertEquals(2, this.response.getHeaders().getContentLength());
assertEquals("bytes 0-1/10", this.response.getHeaders().getFirst("Content-Range"));
assertEquals("bytes", this.response.getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, this.response.getHeaders().get("Accept-Ranges").size());
assertResponseBody("So");
assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, exchange.getResponse().getHeaders().getContentType());
assertEquals(2, exchange.getResponse().getHeaders().getContentLength());
assertEquals("bytes 0-1/10", exchange.getResponse().getHeaders().getFirst("Content-Range"));
assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size());
assertResponseBody(exchange, "So");
}
@Test
public void partialContentByteRangeNoEnd() throws Exception {
this.request = MockServerHttpRequest.get("").header("range", "bytes=9-").build();
ServerWebExchange exchange = createExchange("foo.txt");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").header("range", "bytes=9-").toExchange();
setPathWithinHandlerMapping(exchange, "foo.txt");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(HttpStatus.PARTIAL_CONTENT, this.response.getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, this.response.getHeaders().getContentType());
assertEquals(1, this.response.getHeaders().getContentLength());
assertEquals("bytes 9-9/10", this.response.getHeaders().getFirst("Content-Range"));
assertEquals("bytes", this.response.getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, this.response.getHeaders().get("Accept-Ranges").size());
assertResponseBody(".");
assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, exchange.getResponse().getHeaders().getContentType());
assertEquals(1, exchange.getResponse().getHeaders().getContentLength());
assertEquals("bytes 9-9/10", exchange.getResponse().getHeaders().getFirst("Content-Range"));
assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size());
assertResponseBody(exchange, ".");
}
@Test
public void partialContentByteRangeLargeEnd() throws Exception {
this.request = MockServerHttpRequest.get("").header("range", "bytes=9-10000").build();
ServerWebExchange exchange = createExchange("foo.txt");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").header("range", "bytes=9-10000").toExchange();
setPathWithinHandlerMapping(exchange, "foo.txt");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(HttpStatus.PARTIAL_CONTENT, this.response.getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, this.response.getHeaders().getContentType());
assertEquals(1, this.response.getHeaders().getContentLength());
assertEquals("bytes 9-9/10", this.response.getHeaders().getFirst("Content-Range"));
assertEquals("bytes", this.response.getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, this.response.getHeaders().get("Accept-Ranges").size());
assertResponseBody(".");
assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, exchange.getResponse().getHeaders().getContentType());
assertEquals(1, exchange.getResponse().getHeaders().getContentLength());
assertEquals("bytes 9-9/10", exchange.getResponse().getHeaders().getFirst("Content-Range"));
assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size());
assertResponseBody(exchange, ".");
}
@Test
public void partialContentSuffixRange() throws Exception {
this.request = MockServerHttpRequest.get("").header("range", "bytes=-1").build();
ServerWebExchange exchange = createExchange("foo.txt");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").header("range", "bytes=-1").toExchange();
setPathWithinHandlerMapping(exchange, "foo.txt");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(HttpStatus.PARTIAL_CONTENT, this.response.getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, this.response.getHeaders().getContentType());
assertEquals(1, this.response.getHeaders().getContentLength());
assertEquals("bytes 9-9/10", this.response.getHeaders().getFirst("Content-Range"));
assertEquals("bytes", this.response.getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, this.response.getHeaders().get("Accept-Ranges").size());
assertResponseBody(".");
assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, exchange.getResponse().getHeaders().getContentType());
assertEquals(1, exchange.getResponse().getHeaders().getContentLength());
assertEquals("bytes 9-9/10", exchange.getResponse().getHeaders().getFirst("Content-Range"));
assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size());
assertResponseBody(exchange, ".");
}
@Test
public void partialContentSuffixRangeLargeSuffix() throws Exception {
this.request = MockServerHttpRequest.get("").header("range", "bytes=-11").build();
ServerWebExchange exchange = createExchange("foo.txt");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").header("range", "bytes=-11").toExchange();
setPathWithinHandlerMapping(exchange, "foo.txt");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(HttpStatus.PARTIAL_CONTENT, this.response.getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, this.response.getHeaders().getContentType());
assertEquals(10, this.response.getHeaders().getContentLength());
assertEquals("bytes 0-9/10", this.response.getHeaders().getFirst("Content-Range"));
assertEquals("bytes", this.response.getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, this.response.getHeaders().get("Accept-Ranges").size());
assertResponseBody("Some text.");
assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, exchange.getResponse().getHeaders().getContentType());
assertEquals(10, exchange.getResponse().getHeaders().getContentLength());
assertEquals("bytes 0-9/10", exchange.getResponse().getHeaders().getFirst("Content-Range"));
assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges"));
assertEquals(1, exchange.getResponse().getHeaders().get("Accept-Ranges").size());
assertResponseBody(exchange, "Some text.");
}
@Test
public void partialContentInvalidRangeHeader() throws Exception {
this.request = MockServerHttpRequest.get("").header("range", "bytes=foo bar").build();
ServerWebExchange exchange = createExchange("foo.txt");
MockServerWebExchange exchange = MockServerHttpRequest.get("").header("range", "bytes=foo bar").toExchange();
setPathWithinHandlerMapping(exchange, "foo.txt");
StepVerifier.create(this.handler.handle(exchange))
.expectNextCount(0)
.expectComplete()
.verify();
assertEquals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE, this.response.getStatusCode());
assertEquals("bytes", this.response.getHeaders().getFirst("Accept-Ranges"));
assertEquals(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE, exchange.getResponse().getStatusCode());
assertEquals("bytes", exchange.getResponse().getHeaders().getFirst("Accept-Ranges"));
}
@Test
public void partialContentMultipleByteRanges() throws Exception {
this.request = MockServerHttpRequest.get("").header("Range", "bytes=0-1, 4-5, 8-9").build();
ServerWebExchange exchange = createExchange("foo.txt");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").header("Range", "bytes=0-1, 4-5, 8-9").toExchange();
setPathWithinHandlerMapping(exchange, "foo.txt");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals(HttpStatus.PARTIAL_CONTENT, this.response.getStatusCode());
assertTrue(this.response.getHeaders().getContentType().toString()
assertEquals(HttpStatus.PARTIAL_CONTENT, exchange.getResponse().getStatusCode());
assertTrue(exchange.getResponse().getHeaders().getContentType().toString()
.startsWith("multipart/byteranges;boundary="));
String boundary = "--" + this.response.getHeaders().getContentType().toString().substring(30);
String boundary = "--" + exchange.getResponse().getHeaders().getContentType().toString().substring(30);
Mono<DataBuffer> reduced = Flux.from(this.response.getBody())
Mono<DataBuffer> reduced = Flux.from(exchange.getResponse().getBody())
.reduce(this.bufferFactory.allocateBuffer(), (previous, current) -> {
previous.write(current);
DataBufferUtils.release(current);
@ -567,18 +581,17 @@ public class ResourceWebHandlerTests {
@Test // SPR-14005
public void doOverwriteExistingCacheControlHeaders() throws Exception {
this.response.getHeaders().setCacheControl(CacheControl.noStore().getHeaderValue());
ServerWebExchange exchange = createExchange("foo.css");
this.handler.handle(exchange).blockMillis(5000);
MockServerWebExchange exchange = MockServerHttpRequest.get("").toExchange();
exchange.getResponse().getHeaders().setCacheControl(CacheControl.noStore().getHeaderValue());
setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.handle(exchange).block(TIMEOUT);
assertEquals("max-age=3600", this.response.getHeaders().getCacheControl());
assertEquals("max-age=3600", exchange.getResponse().getHeaders().getCacheControl());
}
private ServerWebExchange createExchange(String path) {
ServerWebExchange exchange = new DefaultServerWebExchange(this.request, this.response);
private void setPathWithinHandlerMapping(ServerWebExchange exchange, String path) {
exchange.getAttributes().put(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, path);
return exchange;
}
private long resourceLastModified(String resourceName) throws IOException {
@ -589,8 +602,8 @@ public class ResourceWebHandlerTests {
return new ClassPathResource(resourceName, getClass()).getFile().lastModified();
}
private void assertResponseBody(String responseBody) {
StepVerifier.create(this.response.getBody())
private void assertResponseBody(MockServerWebExchange exchange, String responseBody) {
StepVerifier.create(exchange.getResponse().getBody())
.consumeNextWith(buf -> assertEquals(responseBody,
DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8)))
.expectComplete()

View File

@ -29,9 +29,7 @@ import reactor.core.publisher.Mono;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
@ -163,9 +161,7 @@ public class VersionResourceResolverTests {
String version = "version";
String file = "bar.css";
Resource expected = new ClassPathResource("test/" + file, getClass());
MockServerHttpRequest request = MockServerHttpRequest.get("/resources/bar-version.css").build();
MockServerHttpResponse response = new MockServerHttpResponse();
ServerWebExchange exchange = new DefaultServerWebExchange(request, response);
ServerWebExchange exchange = MockServerHttpRequest.get("/resources/bar-version.css").toExchange();
given(this.chain.resolveResource(exchange, versionFile, this.locations)).willReturn(Mono.empty());
given(this.chain.resolveResource(exchange, file, this.locations)).willReturn(Mono.just(expected));
given(this.versionStrategy.extractVersion(versionFile)).willReturn(version);

View File

@ -16,6 +16,7 @@
package org.springframework.web.reactive.resource;
import java.time.Duration;
import java.util.List;
import org.junit.Before;
@ -24,11 +25,8 @@ import reactor.core.publisher.Mono;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
@ -47,6 +45,9 @@ import static org.mockito.BDDMockito.verify;
*/
public class WebJarsResourceResolverTests {
private static final Duration TIMEOUT = Duration.ofSeconds(1);
private List<Resource> locations;
private WebJarsResourceResolver resolver;
@ -62,10 +63,7 @@ public class WebJarsResourceResolverTests {
this.locations = singletonList(new ClassPathResource("/META-INF/resources/webjars"));
this.resolver = new WebJarsResourceResolver();
this.chain = mock(ResourceResolverChain.class);
MockServerHttpRequest request = MockServerHttpRequest.get("").build();
ServerHttpResponse response = new MockServerHttpResponse();
this.exchange = new DefaultServerWebExchange(request, response);
this.exchange = MockServerHttpRequest.get("").toExchange();
}
@ -75,7 +73,7 @@ public class WebJarsResourceResolverTests {
String file = "/foo/2.3/foo.txt";
given(this.chain.resolveUrlPath(file, this.locations)).willReturn(Mono.just(file));
String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).blockMillis(5000);
String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).block(TIMEOUT);
assertEquals(file, actual);
verify(this.chain, times(1)).resolveUrlPath(file, this.locations);
@ -87,7 +85,7 @@ public class WebJarsResourceResolverTests {
String file = "foo/foo.txt";
given(this.chain.resolveUrlPath(file, this.locations)).willReturn(Mono.empty());
String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).blockMillis(5000);
String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).block(TIMEOUT);
assertNull(actual);
verify(this.chain, times(1)).resolveUrlPath(file, this.locations);
@ -101,7 +99,7 @@ public class WebJarsResourceResolverTests {
given(this.chain.resolveUrlPath(file, this.locations)).willReturn(Mono.empty());
given(this.chain.resolveUrlPath(expected, this.locations)).willReturn(Mono.just(expected));
String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).blockMillis(5000);
String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).block(TIMEOUT);
assertEquals(expected, actual);
verify(this.chain, times(1)).resolveUrlPath(file, this.locations);
@ -113,7 +111,7 @@ public class WebJarsResourceResolverTests {
String file = "something/something.js";
given(this.chain.resolveUrlPath(file, this.locations)).willReturn(Mono.empty());
String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).blockMillis(5000);
String actual = this.resolver.resolveUrlPath(file, this.locations, this.chain).block(TIMEOUT);
assertNull(actual);
verify(this.chain, times(1)).resolveUrlPath(file, this.locations);
@ -129,7 +127,7 @@ public class WebJarsResourceResolverTests {
Resource actual = this.resolver
.resolveResource(this.exchange, file, this.locations, this.chain)
.blockMillis(5000);
.block(TIMEOUT);
assertEquals(expected, actual);
verify(this.chain, times(1)).resolveResource(this.exchange, file, this.locations);
@ -142,7 +140,7 @@ public class WebJarsResourceResolverTests {
Resource actual = this.resolver
.resolveResource(this.exchange, file, this.locations, this.chain)
.blockMillis(5000);
.block(TIMEOUT);
assertNull(actual);
verify(this.chain, times(1)).resolveResource(this.exchange, file, this.locations);
@ -164,7 +162,7 @@ public class WebJarsResourceResolverTests {
Resource actual = this.resolver
.resolveResource(this.exchange, file, this.locations, this.chain)
.blockMillis(5000);
.block(TIMEOUT);
assertEquals(expected, actual);
verify(this.chain, times(1)).resolveResource(this.exchange, file, this.locations);

View File

@ -25,16 +25,20 @@ import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.accept.FixedContentTypeResolver;
import org.springframework.web.reactive.accept.HeaderContentTypeResolver;
import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.springframework.http.MediaType.*;
import static org.junit.Assert.assertEquals;
import static org.springframework.http.MediaType.ALL;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8;
import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM;
import static org.springframework.http.MediaType.IMAGE_GIF;
import static org.springframework.http.MediaType.IMAGE_JPEG;
import static org.springframework.http.MediaType.IMAGE_PNG;
import static org.springframework.http.MediaType.TEXT_PLAIN;
/**
* Unit tests for {@link HandlerResultHandlerSupport}.
@ -44,13 +48,10 @@ public class HandlerResultHandlerTests {
private TestResultHandler resultHandler;
private MockServerHttpRequest request;
@Before
public void setup() throws Exception {
this.resultHandler = new TestResultHandler();
this.request = MockServerHttpRequest.get("/path").build();
}
@ -58,16 +59,16 @@ public class HandlerResultHandlerTests {
public void usesContentTypeResolver() throws Exception {
TestResultHandler resultHandler = new TestResultHandler(new FixedContentTypeResolver(IMAGE_GIF));
List<MediaType> mediaTypes = Arrays.asList(IMAGE_JPEG, IMAGE_GIF, IMAGE_PNG);
MediaType actual = resultHandler.selectMediaType(exchange(), () -> mediaTypes);
MockServerWebExchange exchange = MockServerHttpRequest.get("/path").toExchange();
MediaType actual = resultHandler.selectMediaType(exchange, () -> mediaTypes);
assertEquals(IMAGE_GIF, actual);
}
@Test
public void producibleMediaTypesRequestAttribute() throws Exception {
ServerWebExchange exchange = exchange();
exchange.getAttributes().put(
HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(IMAGE_GIF));
MockServerWebExchange exchange = MockServerHttpRequest.get("/path").toExchange();
exchange.getAttributes().put(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(IMAGE_GIF));
List<MediaType> mediaTypes = Arrays.asList(IMAGE_JPEG, IMAGE_GIF, IMAGE_PNG);
MediaType actual = resultHandler.selectMediaType(exchange, () -> mediaTypes);
@ -77,12 +78,12 @@ public class HandlerResultHandlerTests {
@Test // SPR-9160
public void sortsByQuality() throws Exception {
this.request = MockServerHttpRequest.get("/path")
MockServerWebExchange exchange = MockServerHttpRequest.get("/path")
.header("Accept", "text/plain; q=0.5, application/json")
.build();
.toExchange();
List<MediaType> mediaTypes = Arrays.asList(TEXT_PLAIN, APPLICATION_JSON_UTF8);
MediaType actual = this.resultHandler.selectMediaType(exchange(), () -> mediaTypes);
MediaType actual = this.resultHandler.selectMediaType(exchange, () -> mediaTypes);
assertEquals(APPLICATION_JSON_UTF8, actual);
}
@ -91,8 +92,8 @@ public class HandlerResultHandlerTests {
public void charsetFromAcceptHeader() throws Exception {
MediaType text8859 = MediaType.parseMediaType("text/plain;charset=ISO-8859-1");
MediaType textUtf8 = MediaType.parseMediaType("text/plain;charset=UTF-8");
this.request = MockServerHttpRequest.get("/path").accept(text8859).build();
MediaType actual = this.resultHandler.selectMediaType(exchange(), () -> Collections.singletonList(textUtf8));
MockServerWebExchange exchange = MockServerHttpRequest.get("/path").accept(text8859).toExchange();
MediaType actual = this.resultHandler.selectMediaType(exchange, () -> Collections.singletonList(textUtf8));
assertEquals(text8859, actual);
}
@ -100,17 +101,13 @@ public class HandlerResultHandlerTests {
@Test // SPR-12894
public void noConcreteMediaType() throws Exception {
List<MediaType> producible = Collections.singletonList(ALL);
MediaType actual = this.resultHandler.selectMediaType(exchange(), () -> producible);
MockServerWebExchange exchange = MockServerHttpRequest.get("/path").toExchange();
MediaType actual = this.resultHandler.selectMediaType(exchange, () -> producible);
assertEquals(APPLICATION_OCTET_STREAM, actual);
}
private DefaultServerWebExchange exchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
@SuppressWarnings("WeakerAccess")
private static class TestResultHandler extends HandlerResultHandlerSupport {

View File

@ -19,14 +19,13 @@ package org.springframework.web.reactive.result.condition;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
/**
* Unit tests for {@link CompositeRequestCondition}.
@ -35,8 +34,6 @@ import static org.junit.Assert.*;
*/
public class CompositeRequestConditionTests {
private ServerHttpRequest request;
private ParamsRequestCondition param1;
private ParamsRequestCondition param2;
private ParamsRequestCondition param3;
@ -48,8 +45,6 @@ public class CompositeRequestConditionTests {
@Before
public void setup() throws Exception {
this.request = MockServerHttpRequest.get("/").build();
this.param1 = new ParamsRequestCondition("param1");
this.param2 = new ParamsRequestCondition("param2");
this.param3 = this.param1.combine(this.param2);
@ -88,7 +83,7 @@ public class CompositeRequestConditionTests {
@Test
public void match() {
this.request = MockServerHttpRequest.get("/path?param1=paramValue1").build();
MockServerWebExchange exchange = MockServerHttpRequest.get("/path?param1=paramValue1").toExchange();
RequestCondition<?> condition1 = new RequestMethodsRequestCondition(RequestMethod.GET, RequestMethod.POST);
RequestCondition<?> condition2 = new RequestMethodsRequestCondition(RequestMethod.GET);
@ -96,26 +91,26 @@ public class CompositeRequestConditionTests {
CompositeRequestCondition composite1 = new CompositeRequestCondition(this.param1, condition1);
CompositeRequestCondition composite2 = new CompositeRequestCondition(this.param1, condition2);
assertEquals(composite2, composite1.getMatchingCondition(createExchange()));
assertEquals(composite2, composite1.getMatchingCondition(exchange));
}
@Test
public void noMatch() {
CompositeRequestCondition cond = new CompositeRequestCondition(this.param1);
assertNull(cond.getMatchingCondition(createExchange()));
assertNull(cond.getMatchingCondition(MockServerHttpRequest.get("/").toExchange()));
}
@Test
public void matchEmpty() {
CompositeRequestCondition empty = new CompositeRequestCondition();
assertSame(empty, empty.getMatchingCondition(createExchange()));
assertSame(empty, empty.getMatchingCondition(MockServerHttpRequest.get("/").toExchange()));
}
@Test
public void compare() {
CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1);
CompositeRequestCondition cond3 = new CompositeRequestCondition(this.param3);
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
assertEquals(1, cond1.compareTo(cond3, exchange));
assertEquals(-1, cond3.compareTo(cond1, exchange));
@ -125,7 +120,7 @@ public class CompositeRequestConditionTests {
public void compareEmpty() {
CompositeRequestCondition empty = new CompositeRequestCondition();
CompositeRequestCondition notEmpty = new CompositeRequestCondition(this.param1);
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
assertEquals(0, empty.compareTo(empty, exchange));
assertEquals(-1, notEmpty.compareTo(empty, exchange));
@ -136,12 +131,8 @@ public class CompositeRequestConditionTests {
public void compareDifferentLength() {
CompositeRequestCondition cond1 = new CompositeRequestCondition(this.param1);
CompositeRequestCondition cond2 = new CompositeRequestCondition(this.param1, this.header1);
cond1.compareTo(cond2, createExchange());
cond1.compareTo(cond2, MockServerHttpRequest.get("/").toExchange());
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
}

View File

@ -16,7 +16,6 @@
package org.springframework.web.reactive.result.condition;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Collections;
@ -24,10 +23,8 @@ import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.reactive.result.condition.ConsumesRequestCondition.ConsumeMediaTypeExpression;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@ -42,7 +39,7 @@ public class ConsumesRequestConditionTests {
@Test
public void consumesMatch() throws Exception {
ServerWebExchange exchange = createExchange("text/plain");
MockServerWebExchange exchange = postExchange("text/plain");
ConsumesRequestCondition condition = new ConsumesRequestCondition("text/plain");
assertNotNull(condition.getMatchingCondition(exchange));
@ -50,7 +47,7 @@ public class ConsumesRequestConditionTests {
@Test
public void negatedConsumesMatch() throws Exception {
ServerWebExchange exchange = createExchange("text/plain");
MockServerWebExchange exchange = postExchange("text/plain");
ConsumesRequestCondition condition = new ConsumesRequestCondition("!text/plain");
assertNull(condition.getMatchingCondition(exchange));
@ -64,7 +61,7 @@ public class ConsumesRequestConditionTests {
@Test
public void consumesWildcardMatch() throws Exception {
ServerWebExchange exchange = createExchange("text/plain");
MockServerWebExchange exchange = postExchange("text/plain");
ConsumesRequestCondition condition = new ConsumesRequestCondition("text/*");
assertNotNull(condition.getMatchingCondition(exchange));
@ -72,7 +69,7 @@ public class ConsumesRequestConditionTests {
@Test
public void consumesMultipleMatch() throws Exception {
ServerWebExchange exchange = createExchange("text/plain");
MockServerWebExchange exchange = postExchange("text/plain");
ConsumesRequestCondition condition = new ConsumesRequestCondition("text/plain", "application/xml");
assertNotNull(condition.getMatchingCondition(exchange));
@ -80,7 +77,7 @@ public class ConsumesRequestConditionTests {
@Test
public void consumesSingleNoMatch() throws Exception {
ServerWebExchange exchange = createExchange("application/xml");
MockServerWebExchange exchange = postExchange("application/xml");
ConsumesRequestCondition condition = new ConsumesRequestCondition("text/plain");
assertNull(condition.getMatchingCondition(exchange));
@ -88,7 +85,7 @@ public class ConsumesRequestConditionTests {
@Test
public void consumesParseError() throws Exception {
ServerWebExchange exchange = createExchange("01");
MockServerWebExchange exchange = postExchange("01");
ConsumesRequestCondition condition = new ConsumesRequestCondition("text/plain");
assertNull(condition.getMatchingCondition(exchange));
@ -96,7 +93,7 @@ public class ConsumesRequestConditionTests {
@Test
public void consumesParseErrorWithNegation() throws Exception {
ServerWebExchange exchange = createExchange("01");
MockServerWebExchange exchange = postExchange("01");
ConsumesRequestCondition condition = new ConsumesRequestCondition("!text/plain");
assertNull(condition.getMatchingCondition(exchange));
@ -104,7 +101,7 @@ public class ConsumesRequestConditionTests {
@Test
public void compareToSingle() throws Exception {
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
ConsumesRequestCondition condition1 = new ConsumesRequestCondition("text/plain");
ConsumesRequestCondition condition2 = new ConsumesRequestCondition("text/*");
@ -118,7 +115,7 @@ public class ConsumesRequestConditionTests {
@Test
public void compareToMultiple() throws Exception {
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
ConsumesRequestCondition condition1 = new ConsumesRequestCondition("*/*", "text/plain");
ConsumesRequestCondition condition2 = new ConsumesRequestCondition("text/*", "text/plain;q=0.7");
@ -160,7 +157,7 @@ public class ConsumesRequestConditionTests {
@Test
public void getMatchingCondition() throws Exception {
ServerWebExchange exchange = createExchange("text/plain");
MockServerWebExchange exchange = postExchange("text/plain");
ConsumesRequestCondition condition = new ConsumesRequestCondition("text/plain", "application/xml");
ConsumesRequestCondition result = condition.getMatchingCondition(exchange);
@ -190,17 +187,8 @@ public class ConsumesRequestConditionTests {
}
}
private ServerWebExchange createExchange() throws URISyntaxException {
return createExchange(null);
}
private ServerWebExchange createExchange(String contentType) {
MockServerHttpRequest request = (contentType != null ?
MockServerHttpRequest.post("/").header(HttpHeaders.CONTENT_TYPE, contentType).build() :
MockServerHttpRequest.get("/").build());
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
private MockServerWebExchange postExchange(String contentType) {
return MockServerHttpRequest.post("/").header(HttpHeaders.CONTENT_TYPE, contentType).toExchange();
}
}

View File

@ -16,16 +16,12 @@
package org.springframework.web.reactive.result.condition;
import java.net.URISyntaxException;
import java.util.Collection;
import org.junit.Test;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -51,7 +47,7 @@ public class HeadersRequestConditionTests {
@Test
public void headerPresent() throws Exception {
ServerWebExchange exchange = createExchange("Accept", "");
MockServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "").toExchange();
HeadersRequestCondition condition = new HeadersRequestCondition("accept");
assertNotNull(condition.getMatchingCondition(exchange));
@ -59,7 +55,7 @@ public class HeadersRequestConditionTests {
@Test
public void headerPresentNoMatch() throws Exception {
ServerWebExchange exchange = createExchange("bar", "");
MockServerWebExchange exchange = MockServerHttpRequest.get("/").header("bar", "").toExchange();
HeadersRequestCondition condition = new HeadersRequestCondition("foo");
assertNull(condition.getMatchingCondition(exchange));
@ -67,7 +63,7 @@ public class HeadersRequestConditionTests {
@Test
public void headerNotPresent() throws Exception {
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
HeadersRequestCondition condition = new HeadersRequestCondition("!accept");
assertNotNull(condition.getMatchingCondition(exchange));
@ -75,7 +71,7 @@ public class HeadersRequestConditionTests {
@Test
public void headerValueMatch() throws Exception {
ServerWebExchange exchange = createExchange("foo", "bar");
MockServerWebExchange exchange = MockServerHttpRequest.get("/").header("foo", "bar").toExchange();
HeadersRequestCondition condition = new HeadersRequestCondition("foo=bar");
assertNotNull(condition.getMatchingCondition(exchange));
@ -83,7 +79,7 @@ public class HeadersRequestConditionTests {
@Test
public void headerValueNoMatch() throws Exception {
ServerWebExchange exchange = createExchange("foo", "bazz");
MockServerWebExchange exchange = MockServerHttpRequest.get("/").header("foo", "bazz").toExchange();
HeadersRequestCondition condition = new HeadersRequestCondition("foo=bar");
assertNull(condition.getMatchingCondition(exchange));
@ -91,7 +87,7 @@ public class HeadersRequestConditionTests {
@Test
public void headerCaseSensitiveValueMatch() throws Exception {
ServerWebExchange exchange = createExchange("foo", "bar");
MockServerWebExchange exchange = MockServerHttpRequest.get("/").header("foo", "bar").toExchange();
HeadersRequestCondition condition = new HeadersRequestCondition("foo=Bar");
assertNull(condition.getMatchingCondition(exchange));
@ -99,7 +95,7 @@ public class HeadersRequestConditionTests {
@Test
public void headerValueMatchNegated() throws Exception {
ServerWebExchange exchange = createExchange("foo", "baz");
MockServerWebExchange exchange = MockServerHttpRequest.get("/").header("foo", "baz").toExchange();
HeadersRequestCondition condition = new HeadersRequestCondition("foo!=bar");
assertNotNull(condition.getMatchingCondition(exchange));
@ -107,7 +103,7 @@ public class HeadersRequestConditionTests {
@Test
public void headerValueNoMatchNegated() throws Exception {
ServerWebExchange exchange = createExchange("foo", "bar");
MockServerWebExchange exchange = MockServerHttpRequest.get("/").header("foo", "bar").toExchange();
HeadersRequestCondition condition = new HeadersRequestCondition("foo!=bar");
assertNull(condition.getMatchingCondition(exchange));
@ -115,7 +111,7 @@ public class HeadersRequestConditionTests {
@Test
public void compareTo() throws Exception {
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
HeadersRequestCondition condition1 = new HeadersRequestCondition("foo", "bar", "baz");
HeadersRequestCondition condition2 = new HeadersRequestCondition("foo", "bar");
@ -140,7 +136,7 @@ public class HeadersRequestConditionTests {
@Test
public void getMatchingCondition() throws Exception {
ServerWebExchange exchange = createExchange("foo", "bar");
MockServerWebExchange exchange = MockServerHttpRequest.get("/").header("foo", "bar").toExchange();
HeadersRequestCondition condition = new HeadersRequestCondition("foo");
HeadersRequestCondition result = condition.getMatchingCondition(exchange);
@ -152,18 +148,4 @@ public class HeadersRequestConditionTests {
assertNull(result);
}
private ServerWebExchange createExchange() throws URISyntaxException {
return createExchange(null, null);
}
private ServerWebExchange createExchange(String headerName, String headerValue) {
ServerHttpRequest request = headerName != null ?
MockServerHttpRequest.get("/").header(headerName, headerValue).build() :
MockServerHttpRequest.get("/").build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
}

View File

@ -16,23 +16,21 @@
package org.springframework.web.reactive.result.condition;
import java.net.URISyntaxException;
import java.util.Collection;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get;
/**
* Unit tests for {@link ParamsRequestCondition}.
@ -53,21 +51,21 @@ public class ParamsRequestConditionTests {
public void paramPresent() throws Exception {
ParamsRequestCondition condition = new ParamsRequestCondition("foo");
assertNotNull(condition.getMatchingCondition(exchangeWithQuery("foo=")));
assertNotNull(condition.getMatchingCondition(exchangeWithFormData("foo=")));
assertNotNull(condition.getMatchingCondition(get("/path?foo=").toExchange()));
assertNotNull(condition.getMatchingCondition(postForm("foo=")));
}
@Test
public void paramPresentNoMatch() throws Exception {
ParamsRequestCondition condition = new ParamsRequestCondition("foo");
assertNull(condition.getMatchingCondition(exchangeWithQuery("bar=")));
assertNull(condition.getMatchingCondition(exchangeWithFormData("bar=")));
assertNull(condition.getMatchingCondition(get("/path?bar=").toExchange()));
assertNull(condition.getMatchingCondition(postForm("bar=")));
}
@Test
public void paramNotPresent() throws Exception {
ServerWebExchange exchange = exchange();
MockServerWebExchange exchange = get("/").toExchange();
assertNotNull(new ParamsRequestCondition("!foo").getMatchingCondition(exchange));
}
@ -75,22 +73,21 @@ public class ParamsRequestConditionTests {
public void paramValueMatch() throws Exception {
ParamsRequestCondition condition = new ParamsRequestCondition("foo=bar");
assertNotNull(condition.getMatchingCondition(exchangeWithQuery("foo=bar")));
assertNotNull(condition.getMatchingCondition(exchangeWithFormData("foo=bar")));
assertNotNull(condition.getMatchingCondition(get("/path?foo=bar").toExchange()));
assertNotNull(condition.getMatchingCondition(postForm("foo=bar")));
}
@Test
public void paramValueNoMatch() throws Exception {
ParamsRequestCondition condition = new ParamsRequestCondition("foo=bar");
assertNull(condition.getMatchingCondition(exchangeWithQuery("foo=bazz")));
assertNull(condition.getMatchingCondition(exchangeWithFormData("foo=bazz")));
assertNull(condition.getMatchingCondition(get("/path?foo=bazz").toExchange()));
assertNull(condition.getMatchingCondition(postForm("foo=bazz")));
}
@Test
public void compareTo() throws Exception {
ServerHttpRequest request = MockServerHttpRequest.get("/").build();
ServerWebExchange exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
ServerWebExchange exchange = get("/").toExchange();
ParamsRequestCondition condition1 = new ParamsRequestCondition("foo", "bar", "baz");
ParamsRequestCondition condition2 = new ParamsRequestCondition("foo", "bar");
@ -113,21 +110,11 @@ public class ParamsRequestConditionTests {
}
private ServerWebExchange exchangeWithQuery(String query) throws URISyntaxException {
ServerHttpRequest request = MockServerHttpRequest.get("/path?" + query).build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
private ServerWebExchange exchangeWithFormData(String formData) throws URISyntaxException {
MockServerHttpRequest request = MockServerHttpRequest.post("/")
private static MockServerWebExchange postForm(String formData) {
return MockServerHttpRequest.post("/")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(formData);
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
private ServerWebExchange exchange() {
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
.body(formData)
.toExchange();
}
}

View File

@ -16,21 +16,18 @@
package org.springframework.web.reactive.result.condition;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Set;
import org.junit.Test;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get;
/**
* Unit tests for {@link PatternsRequestCondition}.
@ -83,7 +80,7 @@ public class PatternsRequestConditionTests {
@Test
public void matchDirectPath() throws Exception {
PatternsRequestCondition condition = new PatternsRequestCondition("/foo");
PatternsRequestCondition match = condition.getMatchingCondition(createExchange("/foo"));
PatternsRequestCondition match = condition.getMatchingCondition(get("/foo").toExchange());
assertNotNull(match);
}
@ -91,7 +88,7 @@ public class PatternsRequestConditionTests {
@Test
public void matchPattern() throws Exception {
PatternsRequestCondition condition = new PatternsRequestCondition("/foo/*");
PatternsRequestCondition match = condition.getMatchingCondition(createExchange("/foo/bar"));
PatternsRequestCondition match = condition.getMatchingCondition(get("/foo/bar").toExchange());
assertNotNull(match);
}
@ -99,7 +96,7 @@ public class PatternsRequestConditionTests {
@Test
public void matchSortPatterns() throws Exception {
PatternsRequestCondition condition = new PatternsRequestCondition("/*/*", "/foo/bar", "/foo/*");
PatternsRequestCondition match = condition.getMatchingCondition(createExchange("/foo/bar"));
PatternsRequestCondition match = condition.getMatchingCondition(get("/foo/bar").toExchange());
PatternsRequestCondition expected = new PatternsRequestCondition("/foo/bar", "/foo/*", "/*/*");
assertEquals(expected, match);
@ -107,7 +104,7 @@ public class PatternsRequestConditionTests {
@Test
public void matchSuffixPattern() throws Exception {
ServerWebExchange exchange = createExchange("/foo.html");
ServerWebExchange exchange = get("/foo.html").toExchange();
PatternsRequestCondition condition = new PatternsRequestCondition("/{foo}");
PatternsRequestCondition match = condition.getMatchingCondition(exchange);
@ -130,13 +127,13 @@ public class PatternsRequestConditionTests {
Set<String> extensions = Collections.singleton("json");
PatternsRequestCondition condition = new PatternsRequestCondition(patterns, null, null, true, false, extensions);
ServerWebExchange exchange = createExchange("/jobs/my.job");
MockServerWebExchange exchange = get("/jobs/my.job").toExchange();
PatternsRequestCondition match = condition.getMatchingCondition(exchange);
assertNotNull(match);
assertEquals("/jobs/{jobName}", match.getPatterns().iterator().next());
exchange = createExchange("/jobs/my.job.json");
exchange = get("/jobs/my.job.json").toExchange();
match = condition.getMatchingCondition(exchange);
assertNotNull(match);
@ -153,7 +150,7 @@ public class PatternsRequestConditionTests {
PatternsRequestCondition combined = condition1.combine(condition2);
ServerWebExchange exchange = createExchange("/prefix/suffix.json");
MockServerWebExchange exchange = get("/prefix/suffix.json").toExchange();
PatternsRequestCondition match = combined.getMatchingCondition(exchange);
assertNotNull(match);
@ -161,7 +158,7 @@ public class PatternsRequestConditionTests {
@Test
public void matchTrailingSlash() throws Exception {
ServerWebExchange exchange = createExchange("/foo/");
MockServerWebExchange exchange = get("/foo/").toExchange();
PatternsRequestCondition condition = new PatternsRequestCondition("/foo");
PatternsRequestCondition match = condition.getMatchingCondition(exchange);
@ -185,7 +182,7 @@ public class PatternsRequestConditionTests {
@Test
public void matchPatternContainsExtension() throws Exception {
PatternsRequestCondition condition = new PatternsRequestCondition("/foo.jpg");
PatternsRequestCondition match = condition.getMatchingCondition(createExchange("/foo.html"));
PatternsRequestCondition match = condition.getMatchingCondition(get("/foo.html").toExchange());
assertNull(match);
}
@ -195,7 +192,7 @@ public class PatternsRequestConditionTests {
PatternsRequestCondition c1 = new PatternsRequestCondition("/foo*");
PatternsRequestCondition c2 = new PatternsRequestCondition("/foo*");
assertEquals(0, c1.compareTo(c2, createExchange("/foo")));
assertEquals(0, c1.compareTo(c2, get("/foo").toExchange()));
}
@Test
@ -203,12 +200,12 @@ public class PatternsRequestConditionTests {
PatternsRequestCondition c1 = new PatternsRequestCondition("/fo*");
PatternsRequestCondition c2 = new PatternsRequestCondition("/foo");
assertEquals(1, c1.compareTo(c2, createExchange("/foo")));
assertEquals(1, c1.compareTo(c2, get("/foo").toExchange()));
}
@Test
public void compareNumberOfMatchingPatterns() throws Exception {
ServerWebExchange exchange = createExchange("/foo.html");
ServerWebExchange exchange = get("/foo.html").toExchange();
PatternsRequestCondition c1 = new PatternsRequestCondition("/foo", "*.jpeg");
PatternsRequestCondition c2 = new PatternsRequestCondition("/foo", "*.html");
@ -221,9 +218,4 @@ public class PatternsRequestConditionTests {
}
private ServerWebExchange createExchange(String path) throws URISyntaxException {
ServerHttpRequest request = MockServerHttpRequest.get(path).build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
}

View File

@ -16,23 +16,21 @@
package org.springframework.web.reactive.result.condition;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Collections;
import org.junit.Test;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get;
/**
* Unit tests for {@link ProducesRequestCondition}.
@ -43,7 +41,7 @@ public class ProducesRequestConditionTests {
@Test
public void match() throws Exception {
ServerWebExchange exchange = createExchange("text/plain");
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "text/plain").toExchange();
ProducesRequestCondition condition = new ProducesRequestCondition("text/plain");
assertNotNull(condition.getMatchingCondition(exchange));
@ -51,7 +49,7 @@ public class ProducesRequestConditionTests {
@Test
public void matchNegated() throws Exception {
ServerWebExchange exchange = createExchange("text/plain");
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "text/plain").toExchange();
ProducesRequestCondition condition = new ProducesRequestCondition("!text/plain");
assertNull(condition.getMatchingCondition(exchange));
@ -65,7 +63,7 @@ public class ProducesRequestConditionTests {
@Test
public void matchWildcard() throws Exception {
ServerWebExchange exchange = createExchange("text/plain");
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "text/plain").toExchange();
ProducesRequestCondition condition = new ProducesRequestCondition("text/*");
assertNotNull(condition.getMatchingCondition(exchange));
@ -73,7 +71,7 @@ public class ProducesRequestConditionTests {
@Test
public void matchMultiple() throws Exception {
ServerWebExchange exchange = createExchange("text/plain");
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "text/plain").toExchange();
ProducesRequestCondition condition = new ProducesRequestCondition("text/plain", "application/xml");
assertNotNull(condition.getMatchingCondition(exchange));
@ -81,7 +79,7 @@ public class ProducesRequestConditionTests {
@Test
public void matchSingle() throws Exception {
ServerWebExchange exchange = createExchange("application/xml");
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "application/xml").toExchange();
ProducesRequestCondition condition = new ProducesRequestCondition("text/plain");
assertNull(condition.getMatchingCondition(exchange));
@ -89,7 +87,7 @@ public class ProducesRequestConditionTests {
@Test
public void matchParseError() throws Exception {
ServerWebExchange exchange = createExchange("bogus");
MockServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "bogus").toExchange();
ProducesRequestCondition condition = new ProducesRequestCondition("text/plain");
assertNull(condition.getMatchingCondition(exchange));
@ -97,7 +95,7 @@ public class ProducesRequestConditionTests {
@Test
public void matchParseErrorWithNegation() throws Exception {
ServerWebExchange exchange = createExchange("bogus");
MockServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "bogus").toExchange();
ProducesRequestCondition condition = new ProducesRequestCondition("!text/plain");
assertNull(condition.getMatchingCondition(exchange));
@ -109,7 +107,7 @@ public class ProducesRequestConditionTests {
ProducesRequestCondition xml = new ProducesRequestCondition("application/xml");
ProducesRequestCondition none = new ProducesRequestCondition();
ServerWebExchange exchange = createExchange("application/xml, text/html");
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "application/xml, text/html").toExchange();
assertTrue(html.compareTo(xml, exchange) > 0);
assertTrue(xml.compareTo(html, exchange) < 0);
@ -118,18 +116,18 @@ public class ProducesRequestConditionTests {
assertTrue(html.compareTo(none, exchange) < 0);
assertTrue(none.compareTo(html, exchange) > 0);
exchange = createExchange("application/xml, text/*");
exchange = MockServerHttpRequest.get("/").header("Accept", "application/xml, text/*").toExchange();
assertTrue(html.compareTo(xml, exchange) > 0);
assertTrue(xml.compareTo(html, exchange) < 0);
exchange = createExchange("application/pdf");
exchange = MockServerHttpRequest.get("/").header("Accept", "application/pdf").toExchange();
assertTrue(html.compareTo(xml, exchange) == 0);
assertTrue(xml.compareTo(html, exchange) == 0);
// See SPR-7000
exchange = createExchange("text/html;q=0.9,application/xml");
exchange = MockServerHttpRequest.get("/").header("Accept", "text/html;q=0.9,application/xml").toExchange();
assertTrue(html.compareTo(xml, exchange) > 0);
assertTrue(xml.compareTo(html, exchange) < 0);
@ -137,7 +135,7 @@ public class ProducesRequestConditionTests {
@Test
public void compareToWithSingleExpression() throws Exception {
ServerWebExchange exchange = createExchange("text/plain");
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "text/plain").toExchange();
ProducesRequestCondition condition1 = new ProducesRequestCondition("text/plain");
ProducesRequestCondition condition2 = new ProducesRequestCondition("text/*");
@ -154,7 +152,7 @@ public class ProducesRequestConditionTests {
ProducesRequestCondition condition1 = new ProducesRequestCondition("*/*", "text/plain");
ProducesRequestCondition condition2 = new ProducesRequestCondition("text/*", "text/plain;q=0.7");
ServerWebExchange exchange = createExchange("text/plain");
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "text/plain").toExchange();
int result = condition1.compareTo(condition2, exchange);
assertTrue("Invalid comparison result: " + result, result < 0);
@ -168,7 +166,7 @@ public class ProducesRequestConditionTests {
ProducesRequestCondition condition1 = new ProducesRequestCondition("text/*", "text/plain");
ProducesRequestCondition condition2 = new ProducesRequestCondition("application/*", "application/xml");
ServerWebExchange exchange = createExchange("text/plain", "application/xml");
ServerWebExchange exchange = get("/").header("Accept", "text/plain", "application/xml").toExchange();
int result = condition1.compareTo(condition2, exchange);
assertTrue("Invalid comparison result: " + result, result < 0);
@ -176,7 +174,7 @@ public class ProducesRequestConditionTests {
result = condition2.compareTo(condition1, exchange);
assertTrue("Invalid comparison result: " + result, result > 0);
exchange = createExchange("application/xml", "text/plain");
exchange = MockServerHttpRequest.get("/").header("Accept", "application/xml", "text/plain").toExchange();
result = condition1.compareTo(condition2, exchange);
assertTrue("Invalid comparison result: " + result, result > 0);
@ -189,7 +187,7 @@ public class ProducesRequestConditionTests {
@Test
public void compareToMediaTypeAll() throws Exception {
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
ProducesRequestCondition condition1 = new ProducesRequestCondition();
ProducesRequestCondition condition2 = new ProducesRequestCondition("application/json");
@ -205,7 +203,7 @@ public class ProducesRequestConditionTests {
assertTrue(condition1.compareTo(condition2, exchange) < 0);
assertTrue(condition2.compareTo(condition1, exchange) > 0);
exchange = createExchange("*/*");
exchange = MockServerHttpRequest.get("/").header("Accept", "*/*").toExchange();
condition1 = new ProducesRequestCondition();
condition2 = new ProducesRequestCondition("application/json");
@ -224,7 +222,7 @@ public class ProducesRequestConditionTests {
@Test
public void compareToMediaTypeAllWithParameter() throws Exception {
ServerWebExchange exchange = createExchange("*/*;q=0.9");
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "*/*;q=0.9").toExchange();
ProducesRequestCondition condition1 = new ProducesRequestCondition();
ProducesRequestCondition condition2 = new ProducesRequestCondition("application/json");
@ -235,7 +233,7 @@ public class ProducesRequestConditionTests {
@Test
public void compareToEqualMatch() throws Exception {
ServerWebExchange exchange = createExchange("text/*");
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "text/*").toExchange();
ProducesRequestCondition condition1 = new ProducesRequestCondition("text/plain");
ProducesRequestCondition condition2 = new ProducesRequestCondition("text/xhtml");
@ -276,7 +274,7 @@ public class ProducesRequestConditionTests {
@Test
public void getMatchingCondition() throws Exception {
ServerWebExchange exchange = createExchange("text/plain");
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("Accept", "text/plain").toExchange();
ProducesRequestCondition condition = new ProducesRequestCondition("text/plain", "application/xml");
@ -308,14 +306,4 @@ public class ProducesRequestConditionTests {
}
}
private ServerWebExchange createExchange(String... accept) throws URISyntaxException {
ServerHttpRequest request = (accept != null ?
MockServerHttpRequest.get("/").header("Accept", accept).build() :
MockServerHttpRequest.get("/").build());
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
}

View File

@ -16,15 +16,11 @@
package org.springframework.web.reactive.result.condition;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@ -38,15 +34,7 @@ import static org.junit.Assert.assertSame;
*/
public class RequestConditionHolderTests {
private ServerWebExchange exchange;
@Before
public void setup() throws Exception {
ServerHttpRequest request = MockServerHttpRequest.get("/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
this.exchange = new DefaultServerWebExchange(request, response);
}
private final MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
@Test

View File

@ -20,24 +20,24 @@ import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.reactive.result.method.RequestMappingInfo;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager;
import org.springframework.web.server.session.WebSessionManager;
import static java.util.Arrays.*;
import static org.junit.Assert.*;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.springframework.web.reactive.result.method.RequestMappingInfo.paths;
/**
* Unit tests for {@link RequestMappingInfo}.
@ -46,20 +46,12 @@ import static org.junit.Assert.*;
*/
public class RequestMappingInfoTests {
private ServerHttpRequest request;
// TODO: CORS pre-flight (see @Ignored)
@Before
public void setup() throws Exception {
this.request = MockServerHttpRequest.get("/foo").build();
}
@Test
public void createEmpty() {
RequestMappingInfo info = new RequestMappingInfo(null, null, null, null, null, null, null);
RequestMappingInfo info = paths().build();
assertEquals(0, info.getPatternsCondition().getPatterns().size());
assertEquals(0, info.getMethodsCondition().getMethods().size());
@ -72,136 +64,108 @@ public class RequestMappingInfoTests {
@Test
public void matchPatternsCondition() {
RequestMappingInfo info = new RequestMappingInfo(
new PatternsRequestCondition("/foo*", "/bar"), null, null, null, null, null, null);
RequestMappingInfo expected = new RequestMappingInfo(
new PatternsRequestCondition("/foo*"), null, null, null, null, null, null);
MockServerWebExchange exchange = MockServerHttpRequest.get("/foo").toExchange();
assertEquals(expected, info.getMatchingCondition(createExchange()));
RequestMappingInfo info = paths("/foo*", "/bar").build();
RequestMappingInfo expected = paths("/foo*").build();
info = new RequestMappingInfo(
new PatternsRequestCondition("/**", "/foo*", "/foo"), null, null, null, null, null, null);
expected = new RequestMappingInfo(
new PatternsRequestCondition("/foo", "/foo*", "/**"), null, null, null, null, null, null);
assertEquals(expected, info.getMatchingCondition(exchange));
assertEquals(expected, info.getMatchingCondition(createExchange()));
info = paths("/**", "/foo*", "/foo").build();
expected = paths("/foo", "/foo*", "/**").build();
assertEquals(expected, info.getMatchingCondition(exchange));
}
@Test
public void matchParamsCondition() {
this.request = MockServerHttpRequest.get("/foo?foo=bar").build();
ServerWebExchange exchange = MockServerHttpRequest.get("/foo?foo=bar").toExchange();
RequestMappingInfo info = new RequestMappingInfo(
new PatternsRequestCondition("/foo"), null,
new ParamsRequestCondition("foo=bar"), null, null, null, null);
RequestMappingInfo match = info.getMatchingCondition(createExchange());
RequestMappingInfo info = paths("/foo").params("foo=bar").build();
RequestMappingInfo match = info.getMatchingCondition(exchange);
assertNotNull(match);
info = new RequestMappingInfo(
new PatternsRequestCondition("/foo"), null,
new ParamsRequestCondition("foo!=bar"), null, null, null, null);
match = info.getMatchingCondition(createExchange());
info = paths("/foo").params("foo!=bar").build();
match = info.getMatchingCondition(exchange);
assertNull(match);
}
@Test
public void matchHeadersCondition() {
this.request = MockServerHttpRequest.get("/foo").header("foo", "bar").build();
ServerWebExchange exchange = MockServerHttpRequest.get("/foo").header("foo", "bar").toExchange();
RequestMappingInfo info =
new RequestMappingInfo(
new PatternsRequestCondition("/foo"), null, null,
new HeadersRequestCondition("foo=bar"), null, null, null);
RequestMappingInfo match = info.getMatchingCondition(createExchange());
RequestMappingInfo info = paths("/foo").headers("foo=bar").build();
RequestMappingInfo match = info.getMatchingCondition(exchange);
assertNotNull(match);
info = new RequestMappingInfo(
new PatternsRequestCondition("/foo"), null, null,
new HeadersRequestCondition("foo!=bar"), null, null, null);
match = info.getMatchingCondition(createExchange());
info = paths("/foo").headers("foo!=bar").build();
match = info.getMatchingCondition(exchange);
assertNull(match);
}
@Test
public void matchConsumesCondition() {
this.request = MockServerHttpRequest.post("/foo").contentType(MediaType.TEXT_PLAIN).build();
ServerWebExchange exchange = MockServerHttpRequest.post("/foo").contentType(MediaType.TEXT_PLAIN).toExchange();
RequestMappingInfo info =
new RequestMappingInfo(
new PatternsRequestCondition("/foo"), null, null, null,
new ConsumesRequestCondition("text/plain"), null, null);
RequestMappingInfo match = info.getMatchingCondition(createExchange());
RequestMappingInfo info = paths("/foo").consumes("text/plain").build();
RequestMappingInfo match = info.getMatchingCondition(exchange);
assertNotNull(match);
info = new RequestMappingInfo(
new PatternsRequestCondition("/foo"), null, null, null,
new ConsumesRequestCondition("application/xml"), null, null);
match = info.getMatchingCondition(createExchange());
info = paths("/foo").consumes("application/xml").build();
match = info.getMatchingCondition(exchange);
assertNull(match);
}
@Test
public void matchProducesCondition() {
this.request = MockServerHttpRequest.get("/foo").accept(MediaType.TEXT_PLAIN).build();
ServerWebExchange exchange = MockServerHttpRequest.get("/foo").accept(MediaType.TEXT_PLAIN).toExchange();
RequestMappingInfo info = new RequestMappingInfo(
new PatternsRequestCondition("/foo"), null, null, null, null,
new ProducesRequestCondition("text/plain"), null);
RequestMappingInfo match = info.getMatchingCondition(createExchange());
RequestMappingInfo info = paths("/foo").produces("text/plain").build();
RequestMappingInfo match = info.getMatchingCondition(exchange);
assertNotNull(match);
info = new RequestMappingInfo(
new PatternsRequestCondition("/foo"), null, null, null, null,
new ProducesRequestCondition("application/xml"), null);
match = info.getMatchingCondition(createExchange());
info = paths("/foo").produces("application/xml").build();
match = info.getMatchingCondition(exchange);
assertNull(match);
}
@Test
public void matchCustomCondition() {
this.request = MockServerHttpRequest.get("/foo?foo=bar").build();
ServerWebExchange exchange = MockServerHttpRequest.get("/foo?foo=bar").toExchange();
RequestMappingInfo info =
new RequestMappingInfo(
new PatternsRequestCondition("/foo"), null, null, null, null, null,
new ParamsRequestCondition("foo=bar"));
RequestMappingInfo match = info.getMatchingCondition(createExchange());
RequestMappingInfo info = paths("/foo").params("foo=bar").build();
RequestMappingInfo match = info.getMatchingCondition(exchange);
assertNotNull(match);
info = new RequestMappingInfo(
new PatternsRequestCondition("/foo"), null,
new ParamsRequestCondition("foo!=bar"), null, null, null,
new ParamsRequestCondition("foo!=bar"));
match = info.getMatchingCondition(createExchange());
info = paths("/foo").params("foo!=bar")
.customCondition(new ParamsRequestCondition("foo!=bar")).build();
match = info.getMatchingCondition(exchange);
assertNull(match);
}
@Test
public void compareTwoHttpMethodsOneParam() {
RequestMappingInfo none = new RequestMappingInfo(null, null, null, null, null, null, null);
RequestMappingInfo oneMethod =
new RequestMappingInfo(null,
new RequestMethodsRequestCondition(RequestMethod.GET), null, null, null, null, null);
RequestMappingInfo oneMethodOneParam =
new RequestMappingInfo(null,
new RequestMethodsRequestCondition(RequestMethod.GET),
new ParamsRequestCondition("foo"), null, null, null, null);
RequestMappingInfo none = paths().build();
RequestMappingInfo oneMethod = paths().methods(RequestMethod.GET).build();
RequestMappingInfo oneMethodOneParam = paths().methods(RequestMethod.GET).params("foo").build();
Comparator<RequestMappingInfo> comparator = (info, otherInfo) -> info.compareTo(otherInfo, createExchange());
ServerWebExchange exchange = MockServerHttpRequest.get("/foo").toExchange();
Comparator<RequestMappingInfo> comparator = (info, otherInfo) -> info.compareTo(otherInfo, exchange);
List<RequestMappingInfo> list = asList(none, oneMethod, oneMethodOneParam);
Collections.shuffle(list);
Collections.sort(list, comparator);
list.sort(comparator);
assertEquals(oneMethodOneParam, list.get(0));
assertEquals(oneMethod, list.get(1));
@ -210,107 +174,80 @@ public class RequestMappingInfoTests {
@Test
public void equals() {
RequestMappingInfo info1 = new RequestMappingInfo(
new PatternsRequestCondition("/foo"),
new RequestMethodsRequestCondition(RequestMethod.GET),
new ParamsRequestCondition("foo=bar"),
new HeadersRequestCondition("foo=bar"),
new ConsumesRequestCondition("text/plain"),
new ProducesRequestCondition("text/plain"),
new ParamsRequestCondition("customFoo=customBar"));
RequestMappingInfo info1 = paths("/foo").methods(RequestMethod.GET)
.params("foo=bar").headers("foo=bar")
.consumes("text/plain").produces("text/plain")
.customCondition(new ParamsRequestCondition("customFoo=customBar"))
.build();
RequestMappingInfo info2 = new RequestMappingInfo(
new PatternsRequestCondition("/foo"),
new RequestMethodsRequestCondition(RequestMethod.GET),
new ParamsRequestCondition("foo=bar"),
new HeadersRequestCondition("foo=bar"),
new ConsumesRequestCondition("text/plain"),
new ProducesRequestCondition("text/plain"),
new ParamsRequestCondition("customFoo=customBar"));
RequestMappingInfo info2 = paths("/foo").methods(RequestMethod.GET)
.params("foo=bar").headers("foo=bar")
.consumes("text/plain").produces("text/plain")
.customCondition(new ParamsRequestCondition("customFoo=customBar"))
.build();
assertEquals(info1, info2);
assertEquals(info1.hashCode(), info2.hashCode());
info2 = new RequestMappingInfo(
new PatternsRequestCondition("/foo", "/NOOOOOO"),
new RequestMethodsRequestCondition(RequestMethod.GET),
new ParamsRequestCondition("foo=bar"),
new HeadersRequestCondition("foo=bar"),
new ConsumesRequestCondition("text/plain"),
new ProducesRequestCondition("text/plain"),
new ParamsRequestCondition("customFoo=customBar"));
info2 = paths("/foo", "/NOOOOOO").methods(RequestMethod.GET)
.params("foo=bar").headers("foo=bar")
.consumes("text/plain").produces("text/plain")
.customCondition(new ParamsRequestCondition("customFoo=customBar"))
.build();
assertFalse(info1.equals(info2));
assertNotEquals(info1.hashCode(), info2.hashCode());
info2 = new RequestMappingInfo(
new PatternsRequestCondition("/foo"),
new RequestMethodsRequestCondition(RequestMethod.GET, RequestMethod.POST),
new ParamsRequestCondition("foo=bar"),
new HeadersRequestCondition("foo=bar"),
new ConsumesRequestCondition("text/plain"),
new ProducesRequestCondition("text/plain"),
new ParamsRequestCondition("customFoo=customBar"));
info2 = paths("/foo").methods(RequestMethod.GET, RequestMethod.POST)
.params("foo=bar").headers("foo=bar")
.consumes("text/plain").produces("text/plain")
.customCondition(new ParamsRequestCondition("customFoo=customBar"))
.build();
assertFalse(info1.equals(info2));
assertNotEquals(info1.hashCode(), info2.hashCode());
info2 = new RequestMappingInfo(
new PatternsRequestCondition("/foo"),
new RequestMethodsRequestCondition(RequestMethod.GET),
new ParamsRequestCondition("/NOOOOOO"),
new HeadersRequestCondition("foo=bar"),
new ConsumesRequestCondition("text/plain"),
new ProducesRequestCondition("text/plain"),
new ParamsRequestCondition("customFoo=customBar"));
info2 = paths("/foo").methods(RequestMethod.GET)
.params("/NOOOOOO").headers("foo=bar")
.consumes("text/plain").produces("text/plain")
.customCondition(new ParamsRequestCondition("customFoo=customBar"))
.build();
assertFalse(info1.equals(info2));
assertNotEquals(info1.hashCode(), info2.hashCode());
info2 = new RequestMappingInfo(
new PatternsRequestCondition("/foo"),
new RequestMethodsRequestCondition(RequestMethod.GET),
new ParamsRequestCondition("foo=bar"),
new HeadersRequestCondition("/NOOOOOO"),
new ConsumesRequestCondition("text/plain"),
new ProducesRequestCondition("text/plain"),
new ParamsRequestCondition("customFoo=customBar"));
info2 = paths("/foo").methods(RequestMethod.GET)
.params("foo=bar").headers("/NOOOOOO")
.consumes("text/plain").produces("text/plain")
.customCondition(new ParamsRequestCondition("customFoo=customBar"))
.build();
assertFalse(info1.equals(info2));
assertNotEquals(info1.hashCode(), info2.hashCode());
info2 = new RequestMappingInfo(
new PatternsRequestCondition("/foo"),
new RequestMethodsRequestCondition(RequestMethod.GET),
new ParamsRequestCondition("foo=bar"),
new HeadersRequestCondition("foo=bar"),
new ConsumesRequestCondition("text/NOOOOOO"),
new ProducesRequestCondition("text/plain"),
new ParamsRequestCondition("customFoo=customBar"));
info2 = paths("/foo").methods(RequestMethod.GET)
.params("foo=bar").headers("foo=bar")
.consumes("text/NOOOOOO").produces("text/plain")
.customCondition(new ParamsRequestCondition("customFoo=customBar"))
.build();
assertFalse(info1.equals(info2));
assertNotEquals(info1.hashCode(), info2.hashCode());
info2 = new RequestMappingInfo(
new PatternsRequestCondition("/foo"),
new RequestMethodsRequestCondition(RequestMethod.GET),
new ParamsRequestCondition("foo=bar"),
new HeadersRequestCondition("foo=bar"),
new ConsumesRequestCondition("text/plain"),
new ProducesRequestCondition("text/NOOOOOO"),
new ParamsRequestCondition("customFoo=customBar"));
info2 = paths("/foo").methods(RequestMethod.GET)
.params("foo=bar").headers("foo=bar")
.consumes("text/plain").produces("text/NOOOOOO")
.customCondition(new ParamsRequestCondition("customFoo=customBar"))
.build();
assertFalse(info1.equals(info2));
assertNotEquals(info1.hashCode(), info2.hashCode());
info2 = new RequestMappingInfo(
new PatternsRequestCondition("/foo"),
new RequestMethodsRequestCondition(RequestMethod.GET),
new ParamsRequestCondition("foo=bar"),
new HeadersRequestCondition("foo=bar"),
new ConsumesRequestCondition("text/plain"),
new ProducesRequestCondition("text/plain"),
new ParamsRequestCondition("customFoo=NOOOOOO"));
info2 = paths("/foo").methods(RequestMethod.GET)
.params("foo=bar").headers("foo=bar")
.consumes("text/plain").produces("text/plain")
.customCondition(new ParamsRequestCondition("customFoo=NOOOOOO"))
.build();
assertFalse(info1.equals(info2));
assertNotEquals(info1.hashCode(), info2.hashCode());
@ -319,31 +256,18 @@ public class RequestMappingInfoTests {
@Test
@Ignore
public void preFlightRequest() throws Exception {
ServerHttpRequest request = MockServerHttpRequest.options("/foo")
MockServerWebExchange exchange = MockServerHttpRequest.options("/foo")
.header("Origin", "http://domain.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "POST")
.build();
.toExchange();
WebSessionManager manager = new MockWebSessionManager();
MockServerHttpResponse response = new MockServerHttpResponse();
ServerWebExchange exchange = new DefaultServerWebExchange(request, response, manager);
RequestMappingInfo info = new RequestMappingInfo(
new PatternsRequestCondition("/foo"), new RequestMethodsRequestCondition(RequestMethod.POST), null,
null, null, null, null);
RequestMappingInfo info = paths("/foo").methods(RequestMethod.POST).build();
RequestMappingInfo match = info.getMatchingCondition(exchange);
assertNotNull(match);
info = new RequestMappingInfo(
new PatternsRequestCondition("/foo"), new RequestMethodsRequestCondition(RequestMethod.OPTIONS), null,
null, null, null, null);
info = paths("/foo").methods(RequestMethod.OPTIONS).build();
match = info.getMatchingCondition(exchange);
assertNull("Pre-flight should match the ACCESS_CONTROL_REQUEST_METHOD", match);
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
}

View File

@ -24,12 +24,9 @@ import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@ -70,7 +67,7 @@ public class RequestMethodsRequestConditionTests {
RequestMethodsRequestCondition condition = new RequestMethodsRequestCondition();
for (RequestMethod method : RequestMethod.values()) {
if (!OPTIONS.equals(method)) {
ServerWebExchange exchange = createExchange(method.name());
ServerWebExchange exchange = getExchange(method.name());
assertNotNull(condition.getMatchingCondition(exchange));
}
}
@ -80,7 +77,7 @@ public class RequestMethodsRequestConditionTests {
@Test
@Ignore
public void getMatchingConditionWithCustomMethod() throws Exception {
ServerWebExchange exchange = createExchange("PROPFIND");
ServerWebExchange exchange = getExchange("PROPFIND");
assertNotNull(new RequestMethodsRequestCondition().getMatchingCondition(exchange));
assertNull(new RequestMethodsRequestCondition(GET, POST).getMatchingCondition(exchange));
}
@ -88,7 +85,7 @@ public class RequestMethodsRequestConditionTests {
@Test
@Ignore
public void getMatchingConditionWithCorsPreFlight() throws Exception {
ServerWebExchange exchange = createExchange("OPTIONS");
ServerWebExchange exchange = getExchange("OPTIONS");
exchange.getRequest().getHeaders().add("Origin", "http://example.com");
exchange.getRequest().getHeaders().add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PUT");
@ -103,7 +100,7 @@ public class RequestMethodsRequestConditionTests {
RequestMethodsRequestCondition c2 = new RequestMethodsRequestCondition(POST);
RequestMethodsRequestCondition c3 = new RequestMethodsRequestCondition();
ServerWebExchange exchange = createExchange("GET");
ServerWebExchange exchange = getExchange("GET");
int result = c1.compareTo(c2, exchange);
assertTrue("Invalid comparison result: " + result, result < 0);
@ -129,20 +126,19 @@ public class RequestMethodsRequestConditionTests {
private void testMatch(RequestMethodsRequestCondition condition, RequestMethod method) throws Exception {
ServerWebExchange exchange = createExchange(method.name());
ServerWebExchange exchange = getExchange(method.name());
RequestMethodsRequestCondition actual = condition.getMatchingCondition(exchange);
assertNotNull(actual);
assertEquals(Collections.singleton(method), actual.getContent());
}
private void testNoMatch(RequestMethodsRequestCondition condition, RequestMethod method) throws Exception {
ServerWebExchange exchange = createExchange(method.name());
ServerWebExchange exchange = getExchange(method.name());
assertNull(condition.getMatchingCondition(exchange));
}
private ServerWebExchange createExchange(String method) throws URISyntaxException {
ServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.valueOf(method), "/").build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
private ServerWebExchange getExchange(String method) throws URISyntaxException {
return MockServerHttpRequest.method(HttpMethod.valueOf(method), "/").toExchange();
}
}

View File

@ -17,7 +17,6 @@
package org.springframework.web.reactive.result.method;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@ -28,21 +27,17 @@ import org.junit.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.PathMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager;
import org.springframework.web.server.session.WebSessionManager;
import org.springframework.web.util.ParsingPathMatcher;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* Unit tests for {@link AbstractHandlerMethodMapping}.
@ -79,7 +74,7 @@ public class HandlerMethodMappingTests {
public void directMatch() throws Exception {
String key = "foo";
this.mapping.registerMapping(key, this.handler, this.method1);
Mono<Object> result = this.mapping.getHandler(createExchange(HttpMethod.GET, key));
Mono<Object> result = this.mapping.getHandler(MockServerHttpRequest.get(key).toExchange());
assertEquals(this.method1, ((HandlerMethod) result.block()).getMethod());
}
@ -89,7 +84,7 @@ public class HandlerMethodMappingTests {
this.mapping.registerMapping("/fo*", this.handler, this.method1);
this.mapping.registerMapping("/f*", this.handler, this.method2);
Mono<Object> result = this.mapping.getHandler(createExchange(HttpMethod.GET, "/foo"));
Mono<Object> result = this.mapping.getHandler(MockServerHttpRequest.get("/foo").toExchange());
assertEquals(this.method1, ((HandlerMethod) result.block()).getMethod());
}
@ -97,7 +92,7 @@ public class HandlerMethodMappingTests {
public void ambiguousMatch() throws Exception {
this.mapping.registerMapping("/f?o", this.handler, this.method1);
this.mapping.registerMapping("/fo?", this.handler, this.method2);
Mono<Object> result = this.mapping.getHandler(createExchange(HttpMethod.GET, "/foo"));
Mono<Object> result = this.mapping.getHandler(MockServerHttpRequest.get("/foo").toExchange());
StepVerifier.create(result).expectError(IllegalStateException.class).verify();
}
@ -136,25 +131,18 @@ public class HandlerMethodMappingTests {
public void unregisterMapping() throws Exception {
String key = "foo";
this.mapping.registerMapping(key, this.handler, this.method1);
Mono<Object> result = this.mapping.getHandler(createExchange(HttpMethod.GET, key));
Mono<Object> result = this.mapping.getHandler(MockServerHttpRequest.get(key).toExchange());
assertNotNull(result.block());
this.mapping.unregisterMapping(key);
result = this.mapping.getHandler(createExchange(HttpMethod.GET, key));
result = this.mapping.getHandler(MockServerHttpRequest.get(key).toExchange());
assertNull(result.block());
assertNull(this.mapping.getMappingRegistry().getMappingsByUrl(key));
}
private ServerWebExchange createExchange(HttpMethod httpMethod, String path) throws URISyntaxException {
ServerHttpRequest request = MockServerHttpRequest.method(httpMethod, path).build();
WebSessionManager sessionManager = new MockWebSessionManager();
return new DefaultServerWebExchange(request, new MockServerHttpResponse(), sessionManager);
}
private static class MyHandlerMethodMapping extends AbstractHandlerMethodMapping<String> {
private PathMatcher pathMatcher = new ParsingPathMatcher();

View File

@ -20,21 +20,17 @@ import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.HandlerResult;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.UnsupportedMediaTypeStatusException;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
@ -54,16 +50,8 @@ import static org.springframework.web.method.ResolvableMethod.on;
*/
public class InvocableHandlerMethodTests {
private ServerWebExchange exchange;
@Before
public void setup() throws Exception {
this.exchange = new DefaultServerWebExchange(
MockServerHttpRequest.get("http://localhost:8080/path").build(),
new MockServerHttpResponse(),
new MockWebSessionManager());
}
private final MockServerWebExchange exchange =
MockServerHttpRequest.get("http://localhost:8080/path").toExchange();
@Test

View File

@ -36,9 +36,7 @@ import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
@ -55,7 +53,6 @@ import org.springframework.web.server.NotAcceptableStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.server.UnsupportedMediaTypeStatusException;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.support.HttpRequestPathHelper;
import static org.hamcrest.CoreMatchers.containsString;
@ -64,6 +61,7 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.HEAD;
import static org.springframework.web.bind.annotation.RequestMethod.OPTIONS;
@ -81,8 +79,6 @@ public class RequestMappingInfoHandlerMappingTests {
private TestRequestMappingInfoHandlerMapping handlerMapping;
private ServerHttpRequest request;
@Before
public void setup() throws Exception {
@ -103,8 +99,8 @@ public class RequestMappingInfoHandlerMappingTests {
@Test
public void getHandlerDirectMatch() throws Exception {
Method expected = on(TestController.class).annot(getMapping("/foo").params()).resolveMethod();
this.request = MockServerHttpRequest.get("/foo").build();
HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(createExchange()).block();
ServerWebExchange exchange = get("/foo").toExchange();
HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(exchange).block();
assertEquals(expected, hm.getMethod());
}
@ -112,8 +108,8 @@ public class RequestMappingInfoHandlerMappingTests {
@Test
public void getHandlerGlobMatch() throws Exception {
Method expected = on(TestController.class).annot(requestMapping("/ba*").method(GET, HEAD)).resolveMethod();
this.request = MockServerHttpRequest.get("/bar").build();
HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(createExchange()).block();
ServerWebExchange exchange = get("/bar").toExchange();
HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(exchange).block();
assertEquals(expected, hm.getMethod());
}
@ -121,28 +117,28 @@ public class RequestMappingInfoHandlerMappingTests {
@Test
public void getHandlerEmptyPathMatch() throws Exception {
Method expected = on(TestController.class).annot(requestMapping("")).resolveMethod();
this.request = MockServerHttpRequest.get("").build();
HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(createExchange()).block();
ServerWebExchange exchange = get("").toExchange();
HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(exchange).block();
assertEquals(expected, hm.getMethod());
this.request = MockServerHttpRequest.get("/").build();
hm = (HandlerMethod) this.handlerMapping.getHandler(createExchange()).block();
exchange = get("/").toExchange();
hm = (HandlerMethod) this.handlerMapping.getHandler(exchange).block();
assertEquals(expected, hm.getMethod());
}
@Test
public void getHandlerBestMatch() throws Exception {
Method expected = on(TestController.class).annot(getMapping("/foo").params("p")).resolveMethod();
this.request = MockServerHttpRequest.get("/foo?p=anything").build();
HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(createExchange()).block();
ServerWebExchange exchange = get("/foo?p=anything").toExchange();
HandlerMethod hm = (HandlerMethod) this.handlerMapping.getHandler(exchange).block();
assertEquals(expected, hm.getMethod());
}
@Test
public void getHandlerRequestMethodNotAllowed() throws Exception {
this.request = MockServerHttpRequest.post("/bar").build();
Mono<Object> mono = this.handlerMapping.getHandler(createExchange());
ServerWebExchange exchange = MockServerHttpRequest.post("/bar").toExchange();
Mono<Object> mono = this.handlerMapping.getHandler(exchange);
assertError(mono, MethodNotAllowedException.class,
ex -> assertEquals(new HashSet<>(Arrays.asList("GET", "HEAD")), ex.getSupportedMethods()));
@ -150,9 +146,9 @@ public class RequestMappingInfoHandlerMappingTests {
@Test // SPR-9603
public void getHandlerRequestMethodMatchFalsePositive() throws Exception {
this.request = MockServerHttpRequest.get("/users").accept(MediaType.APPLICATION_XML).build();
ServerWebExchange exchange = get("/users").accept(MediaType.APPLICATION_XML).toExchange();
this.handlerMapping.registerHandler(new UserController());
Mono<Object> mono = this.handlerMapping.getHandler(createExchange());
Mono<Object> mono = this.handlerMapping.getHandler(exchange);
StepVerifier.create(mono)
.expectError(NotAcceptableStatusException.class)
@ -168,8 +164,8 @@ public class RequestMappingInfoHandlerMappingTests {
@Test
public void getHandlerTestInvalidContentType() throws Exception {
this.request = MockServerHttpRequest.put("/person/1").header("content-type", "bogus").build();
Mono<Object> mono = this.handlerMapping.getHandler(createExchange());
ServerWebExchange exchange = MockServerHttpRequest.put("/person/1").header("content-type", "bogus").toExchange();
Mono<Object> mono = this.handlerMapping.getHandler(exchange);
assertError(mono, UnsupportedMediaTypeStatusException.class,
ex -> assertEquals("Request failure [status: 415, " +
@ -186,8 +182,8 @@ public class RequestMappingInfoHandlerMappingTests {
@Test // SPR-12854
public void getHandlerTestRequestParamMismatch() throws Exception {
this.request = MockServerHttpRequest.get("/params").build();
Mono<Object> mono = this.handlerMapping.getHandler(createExchange());
ServerWebExchange exchange = get("/params").toExchange();
Mono<Object> mono = this.handlerMapping.getHandler(exchange);
assertError(mono, ServerWebInputException.class, ex -> {
assertThat(ex.getReason(), containsString("[foo=bar]"));
assertThat(ex.getReason(), containsString("[bar=baz]"));
@ -204,15 +200,13 @@ public class RequestMappingInfoHandlerMappingTests {
@Test
public void getHandlerProducibleMediaTypesAttribute() throws Exception {
this.request = MockServerHttpRequest.get("/content").accept(MediaType.APPLICATION_XML).build();
ServerWebExchange exchange = createExchange();
ServerWebExchange exchange = get("/content").accept(MediaType.APPLICATION_XML).toExchange();
this.handlerMapping.getHandler(exchange).block();
String name = HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;
assertEquals(Collections.singleton(MediaType.APPLICATION_XML), exchange.getAttributes().get(name));
this.request = MockServerHttpRequest.get("/content").accept(MediaType.APPLICATION_JSON).build();
exchange = createExchange();
exchange = get("/content").accept(MediaType.APPLICATION_JSON).toExchange();
this.handlerMapping.getHandler(exchange).block();
assertNull("Negated expression shouldn't be listed as producible type",
@ -223,8 +217,7 @@ public class RequestMappingInfoHandlerMappingTests {
@SuppressWarnings("unchecked")
public void handleMatchUriTemplateVariables() throws Exception {
String lookupPath = "/1/2";
this.request = MockServerHttpRequest.get(lookupPath).build();
ServerWebExchange exchange = createExchange();
ServerWebExchange exchange = get(lookupPath).toExchange();
RequestMappingInfo key = paths("/{path1}/{path2}").build();
this.handlerMapping.handleMatch(key, lookupPath, exchange);
@ -240,8 +233,8 @@ public class RequestMappingInfoHandlerMappingTests {
@Test // SPR-9098
public void handleMatchUriTemplateVariablesDecode() throws Exception {
RequestMappingInfo key = paths("/{group}/{identifier}").build();
this.request = MockServerHttpRequest.method(HttpMethod.GET, URI.create("/group/a%2Fb")).build();
ServerWebExchange exchange = createExchange();
URI url = URI.create("/group/a%2Fb");
ServerWebExchange exchange = MockServerHttpRequest.method(HttpMethod.GET, url).toExchange();
HttpRequestPathHelper pathHelper = new HttpRequestPathHelper();
pathHelper.setUrlDecode(false);
@ -262,8 +255,7 @@ public class RequestMappingInfoHandlerMappingTests {
@Test
public void handleMatchBestMatchingPatternAttribute() throws Exception {
RequestMappingInfo key = paths("/{path1}/2", "/**").build();
this.request = MockServerHttpRequest.get("/1/2").build();
ServerWebExchange exchange = createExchange();
ServerWebExchange exchange = get("/1/2").toExchange();
this.handlerMapping.handleMatch(key, "/1/2", exchange);
assertEquals("/{path1}/2", exchange.getAttributes().get(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE));
@ -272,8 +264,7 @@ public class RequestMappingInfoHandlerMappingTests {
@Test
public void handleMatchBestMatchingPatternAttributeNoPatternsDefined() throws Exception {
RequestMappingInfo key = paths().build();
this.request = MockServerHttpRequest.get("/1/2").build();
ServerWebExchange exchange = createExchange();
ServerWebExchange exchange = get("/1/2").toExchange();
this.handlerMapping.handleMatch(key, "/1/2", exchange);
@ -282,12 +273,10 @@ public class RequestMappingInfoHandlerMappingTests {
@Test
public void handleMatchMatrixVariables() throws Exception {
ServerWebExchange exchange;
MultiValueMap<String, String> matrixVariables;
Map<String, String> uriVariables;
this.request = MockServerHttpRequest.get("/").build();
exchange = createExchange();
ServerWebExchange exchange = get("/").toExchange();
handleMatch(exchange, "/{cars}", "/cars;colors=red,blue,green;year=2012");
matrixVariables = getMatrixVariables(exchange, "cars");
@ -298,8 +287,7 @@ public class RequestMappingInfoHandlerMappingTests {
assertEquals("2012", matrixVariables.getFirst("year"));
assertEquals("cars", uriVariables.get("cars"));
this.request = MockServerHttpRequest.get("/").build();
exchange = createExchange();
exchange = get("/").toExchange();
handleMatch(exchange, "/{cars:[^;]+}{params}", "/cars;colors=red,blue,green;year=2012");
matrixVariables = getMatrixVariables(exchange, "params");
@ -311,8 +299,7 @@ public class RequestMappingInfoHandlerMappingTests {
assertEquals("cars", uriVariables.get("cars"));
assertEquals(";colors=red,blue,green;year=2012", uriVariables.get("params"));
this.request = MockServerHttpRequest.get("/").build();
exchange = createExchange();
exchange = get("/").toExchange();
handleMatch(exchange, "/{cars:[^;]+}{params}", "/cars");
matrixVariables = getMatrixVariables(exchange, "params");
@ -329,8 +316,7 @@ public class RequestMappingInfoHandlerMappingTests {
urlPathHelper.setUrlDecode(false);
this.handlerMapping.setPathHelper(urlPathHelper);
this.request = MockServerHttpRequest.get("/").build();
ServerWebExchange exchange = createExchange();
ServerWebExchange exchange = get("/").toExchange();
handleMatch(exchange, "/path{filter}", "/path;mvar=a%2fb");
MultiValueMap<String, String> matrixVariables = getMatrixVariables(exchange, "filter");
@ -342,10 +328,6 @@ public class RequestMappingInfoHandlerMappingTests {
}
private ServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
@SuppressWarnings("unchecked")
private <T> void assertError(Mono<Object> mono, final Class<T> exceptionClass, final Consumer<T> consumer) {
StepVerifier.create(mono)
@ -358,8 +340,8 @@ public class RequestMappingInfoHandlerMappingTests {
}
private void testHttpMediaTypeNotSupportedException(String url) throws Exception {
this.request = MockServerHttpRequest.put(url).contentType(MediaType.APPLICATION_JSON).build();
Mono<Object> mono = this.handlerMapping.getHandler(createExchange());
ServerWebExchange exchange = MockServerHttpRequest.put(url).contentType(MediaType.APPLICATION_JSON).toExchange();
Mono<Object> mono = this.handlerMapping.getHandler(exchange);
assertError(mono, UnsupportedMediaTypeStatusException.class, ex ->
assertEquals("Invalid supported consumable media types",
@ -368,9 +350,8 @@ public class RequestMappingInfoHandlerMappingTests {
}
private void testHttpOptions(String requestURI, String allowHeader) throws Exception {
this.request = MockServerHttpRequest.options(requestURI).build();
ServerWebExchange exchange = createExchange();
HandlerMethod handlerMethod = (HandlerMethod) this.handlerMapping.getHandler(createExchange()).block();
ServerWebExchange exchange = MockServerHttpRequest.options(requestURI).toExchange();
HandlerMethod handlerMethod = (HandlerMethod) this.handlerMapping.getHandler(exchange).block();
BindingContext bindingContext = new BindingContext();
InvocableHandlerMethod invocable = new InvocableHandlerMethod(handlerMethod);
@ -386,8 +367,8 @@ public class RequestMappingInfoHandlerMappingTests {
}
private void testMediaTypeNotAcceptable(String url) throws Exception {
this.request = MockServerHttpRequest.get(url).accept(MediaType.APPLICATION_JSON).build();
Mono<Object> mono = this.handlerMapping.getHandler(createExchange());
ServerWebExchange exchange = get(url).accept(MediaType.APPLICATION_JSON).toExchange();
Mono<Object> mono = this.handlerMapping.getHandler(exchange);
assertError(mono, NotAcceptableStatusException.class, ex ->
assertEquals("Invalid supported producible media types",

View File

@ -19,7 +19,6 @@ import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Collections;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.FatalBeanException;
@ -29,7 +28,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
@ -44,8 +43,6 @@ import org.springframework.web.bind.support.WebExchangeDataBinder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.HandlerResult;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
@ -56,15 +53,7 @@ import static org.mockito.Mockito.mock;
*/
public class ControllerAdviceTests {
private ServerWebExchange exchange;
@Before
public void setUp() throws Exception {
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
this.exchange = new DefaultServerWebExchange(request, response);
}
private final MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
@Test

View File

@ -28,16 +28,18 @@ import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Test fixture with {@link CookieValueMethodArgumentResolver}.
@ -48,8 +50,6 @@ public class CookieValueMethodArgumentResolverTests {
private CookieValueMethodArgumentResolver resolver;
private ServerHttpRequest request;
private BindingContext bindingContext;
private MethodParameter cookieParameter;
@ -65,7 +65,6 @@ public class CookieValueMethodArgumentResolverTests {
ReactiveAdapterRegistry adapterRegistry = new ReactiveAdapterRegistry();
this.resolver = new CookieValueMethodArgumentResolver(context.getBeanFactory(), adapterRegistry);
this.request = MockServerHttpRequest.get("/").build();
this.bindingContext = new BindingContext();
Method method = ReflectionUtils.findMethod(getClass(), "params", (Class<?>[]) null);
@ -99,10 +98,10 @@ public class CookieValueMethodArgumentResolverTests {
@Test
public void resolveCookieArgument() {
HttpCookie expected = new HttpCookie("name", "foo");
this.request = MockServerHttpRequest.get("/").cookie(expected.getName(), expected).build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").cookie(expected.getName(), expected).toExchange();
Mono<Object> mono = this.resolver.resolveArgument(
this.cookieParameter, this.bindingContext, createExchange());
this.cookieParameter, this.bindingContext, exchange);
assertEquals(expected, mono.block());
}
@ -110,18 +109,18 @@ public class CookieValueMethodArgumentResolverTests {
@Test
public void resolveCookieStringArgument() {
HttpCookie cookie = new HttpCookie("name", "foo");
this.request = MockServerHttpRequest.get("/").cookie(cookie.getName(), cookie).build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").cookie(cookie.getName(), cookie).toExchange();
Mono<Object> mono = this.resolver.resolveArgument(
this.cookieStringParameter, this.bindingContext, createExchange());
this.cookieStringParameter, this.bindingContext, exchange);
assertEquals("Invalid result", cookie.getValue(), mono.block());
}
@Test
public void resolveCookieDefaultValue() {
Object result = this.resolver.resolveArgument(
this.cookieStringParameter, this.bindingContext, createExchange()).block();
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
Object result = this.resolver.resolveArgument(this.cookieStringParameter, this.bindingContext, exchange).block();
assertTrue(result instanceof String);
assertEquals("bar", result);
@ -129,7 +128,8 @@ public class CookieValueMethodArgumentResolverTests {
@Test
public void notFound() {
Mono<Object> mono = resolver.resolveArgument(this.cookieParameter, this.bindingContext, createExchange());
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
Mono<Object> mono = resolver.resolveArgument(this.cookieParameter, this.bindingContext, exchange);
StepVerifier.create(mono)
.expectNextCount(0)
.expectError(ServerWebInputException.class)
@ -137,11 +137,6 @@ public class CookieValueMethodArgumentResolverTests {
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
@SuppressWarnings("unused")
public void params(
@CookieValue("name") HttpCookie cookie,

View File

@ -25,15 +25,13 @@ import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.ResolvableType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.support.WebExchangeDataBinder;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.method.ResolvableMethod;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.reactive.BindingContext;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
@ -53,7 +51,7 @@ public class ErrorsArgumentResolverTests {
private BindingResult bindingResult;
private ServerWebExchange exchange;
private MockServerWebExchange exchange = MockServerHttpRequest.post("/path").toExchange();
private final ResolvableMethod testMethod = ResolvableMethod.on(getClass()).named("handle").build();
@ -61,11 +59,6 @@ public class ErrorsArgumentResolverTests {
@Before
public void setup() throws Exception {
this.resolver = new ErrorsMethodArgumentResolver(new ReactiveAdapterRegistry());
MockServerHttpRequest request = MockServerHttpRequest.post("/path").build();
MockServerHttpResponse response = new MockServerHttpResponse();
this.exchange = new DefaultServerWebExchange(request, response);
Foo foo = new Foo();
WebExchangeDataBinder binder = this.bindingContext.createDataBinder(this.exchange, foo, "foo");
this.bindingResult = binder.getBindingResult();

View File

@ -26,15 +26,15 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link ExpressionValueMethodArgumentResolver}.
@ -45,7 +45,7 @@ public class ExpressionValueMethodArgumentResolverTests {
private ExpressionValueMethodArgumentResolver resolver;
private ServerWebExchange exchange;
private final MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
private MethodParameter paramSystemProperty;
private MethodParameter paramNotSupported;
@ -59,9 +59,6 @@ public class ExpressionValueMethodArgumentResolverTests {
ReactiveAdapterRegistry adapterRegistry = new ReactiveAdapterRegistry();
this.resolver = new ExpressionValueMethodArgumentResolver(context.getBeanFactory(), adapterRegistry);
ServerHttpRequest request = MockServerHttpRequest.get("/").build();
this.exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
Method method = ReflectionUtils.findMethod(getClass(), "params", (Class<?>[]) null);
this.paramSystemProperty = new MethodParameter(method, 0);
this.paramNotSupported = new MethodParameter(method, 1);

View File

@ -24,7 +24,6 @@ import java.util.concurrent.CompletableFuture;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.Maybe;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@ -38,18 +37,15 @@ import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.StringDecoder;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.codec.DecoderHttpMessageReader;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.ResolvableMethod;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -58,6 +54,8 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.core.ResolvableType.forClassWithGenerics;
import static org.springframework.http.MediaType.TEXT_PLAIN;
import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.post;
/**
* Unit tests for {@link HttpEntityArgumentResolver}.When adding a test also
@ -71,16 +69,9 @@ public class HttpEntityArgumentResolverTests {
private HttpEntityArgumentResolver resolver = createResolver();
private MockServerHttpRequest request;
private final ResolvableMethod testMethod = ResolvableMethod.on(getClass()).named("handle").build();
@Before
public void setup() throws Exception {
this.request = MockServerHttpRequest.post("/path").build();
}
private HttpEntityArgumentResolver createResolver() {
List<HttpMessageReader<?>> readers = new ArrayList<>();
readers.add(new DecoderHttpMessageReader<>(new StringDecoder()));
@ -225,71 +216,71 @@ public class HttpEntityArgumentResolverTests {
@Test
public void httpEntityWithStringBody() throws Exception {
String body = "line1";
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEntityType(String.class);
HttpEntity<String> httpEntity = resolveValue(type, body);
HttpEntity<String> httpEntity = resolveValue(exchange, type);
assertEquals(this.request.getHeaders(), httpEntity.getHeaders());
assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders());
assertEquals("line1", httpEntity.getBody());
}
@Test
public void httpEntityWithMonoBody() throws Exception {
String body = "line1";
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEntityType(Mono.class, String.class);
HttpEntity<Mono<String>> httpEntity = resolveValue(type, body);
HttpEntity<Mono<String>> httpEntity = resolveValue(exchange, type);
assertEquals(this.request.getHeaders(), httpEntity.getHeaders());
assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders());
assertEquals("line1", httpEntity.getBody().block());
}
@Test
public void httpEntityWithSingleBody() throws Exception {
String body = "line1";
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEntityType(Single.class, String.class);
HttpEntity<Single<String>> httpEntity = resolveValue(type, body);
HttpEntity<Single<String>> httpEntity = resolveValue(exchange, type);
assertEquals(this.request.getHeaders(), httpEntity.getHeaders());
assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders());
assertEquals("line1", httpEntity.getBody().toBlocking().value());
}
@Test
public void httpEntityWithRxJava2SingleBody() throws Exception {
String body = "line1";
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEntityType(io.reactivex.Single.class, String.class);
HttpEntity<io.reactivex.Single<String>> httpEntity = resolveValue(type, body);
HttpEntity<io.reactivex.Single<String>> httpEntity = resolveValue(exchange, type);
assertEquals(this.request.getHeaders(), httpEntity.getHeaders());
assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders());
assertEquals("line1", httpEntity.getBody().blockingGet());
}
@Test
public void httpEntityWithRxJava2MaybeBody() throws Exception {
String body = "line1";
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEntityType(Maybe.class, String.class);
HttpEntity<Maybe<String>> httpEntity = resolveValue(type, body);
HttpEntity<Maybe<String>> httpEntity = resolveValue(exchange, type);
assertEquals(this.request.getHeaders(), httpEntity.getHeaders());
assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders());
assertEquals("line1", httpEntity.getBody().blockingGet());
}
@Test
public void httpEntityWithCompletableFutureBody() throws Exception {
String body = "line1";
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = httpEntityType(CompletableFuture.class, String.class);
HttpEntity<CompletableFuture<String>> httpEntity = resolveValue(type, body);
HttpEntity<CompletableFuture<String>> httpEntity = resolveValue(exchange, type);
assertEquals(this.request.getHeaders(), httpEntity.getHeaders());
assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders());
assertEquals("line1", httpEntity.getBody().get());
}
@Test
public void httpEntityWithFluxBody() throws Exception {
String body = "line1\nline2\nline3\n";
ServerWebExchange exchange = postExchange("line1\nline2\nline3\n");
ResolvableType type = httpEntityType(Flux.class, String.class);
HttpEntity<Flux<String>> httpEntity = resolveValue(type, body);
HttpEntity<Flux<String>> httpEntity = resolveValue(exchange, type);
assertEquals(this.request.getHeaders(), httpEntity.getHeaders());
assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders());
StepVerifier.create(httpEntity.getBody())
.expectNext("line1\n")
.expectNext("line2\n")
@ -300,17 +291,21 @@ public class HttpEntityArgumentResolverTests {
@Test
public void requestEntity() throws Exception {
String body = "line1";
ServerWebExchange exchange = postExchange("line1");
ResolvableType type = forClassWithGenerics(RequestEntity.class, String.class);
RequestEntity<String> requestEntity = resolveValue(type, body);
RequestEntity<String> requestEntity = resolveValue(exchange, type);
assertEquals(this.request.getMethod(), requestEntity.getMethod());
assertEquals(this.request.getURI(), requestEntity.getUrl());
assertEquals(this.request.getHeaders(), requestEntity.getHeaders());
assertEquals(exchange.getRequest().getMethod(), requestEntity.getMethod());
assertEquals(exchange.getRequest().getURI(), requestEntity.getUrl());
assertEquals(exchange.getRequest().getHeaders(), requestEntity.getHeaders());
assertEquals("line1", requestEntity.getBody());
}
private MockServerWebExchange postExchange(String body) {
return post("/path").header("foo", "bar").contentType(TEXT_PLAIN).body(body).toExchange();
}
private ResolvableType httpEntityType(Class<?> bodyType, Class<?>... generics) {
return ResolvableType.forClassWithGenerics(HttpEntity.class,
ObjectUtils.isEmpty(generics) ?
@ -318,14 +313,8 @@ public class HttpEntityArgumentResolverTests {
ResolvableType.forClassWithGenerics(bodyType, generics));
}
@SuppressWarnings("unchecked")
private <T> T resolveValue(ResolvableType type, String body) {
this.request = MockServerHttpRequest.post("/path").header("foo", "bar")
.contentType(MediaType.TEXT_PLAIN)
.body(body);
ServerWebExchange exchange = new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
private <T> T resolveValue(ServerWebExchange exchange, ResolvableType type) {
MethodParameter param = this.testMethod.arg(type);
Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);
Object value = result.block(Duration.ofSeconds(5));
@ -339,12 +328,12 @@ public class HttpEntityArgumentResolverTests {
@SuppressWarnings("unchecked")
private <T> HttpEntity<T> resolveValueWithEmptyBody(ResolvableType type) {
ServerWebExchange exchange = new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
ServerWebExchange exchange = post("/path").toExchange();
MethodParameter param = this.testMethod.arg(type);
Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);
HttpEntity<String> httpEntity = (HttpEntity<String>) result.block(Duration.ofSeconds(5));
assertEquals(this.request.getHeaders(), httpEntity.getHeaders());
assertEquals(exchange.getRequest().getHeaders(), httpEntity.getHeaders());
return (HttpEntity<T>) httpEntity;
}

View File

@ -21,7 +21,6 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
@ -29,7 +28,6 @@ import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.convert.ConversionService;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestParam;
@ -37,9 +35,12 @@ import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.result.method.SyncHandlerMethodArgumentResolver;
import org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
/**
* Unit tests for {@link InitBinderBindingContext}.
@ -51,18 +52,12 @@ public class InitBinderBindingContextTests {
private final List<SyncHandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>();
private MockServerHttpRequest request;
@Before
public void setup() throws Exception {
this.request = MockServerHttpRequest.get("/").build();
}
@Test
public void createBinder() throws Exception {
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
BindingContext context = createBindingContext("initBinder", WebDataBinder.class);
WebDataBinder dataBinder = context.createDataBinder(createExchange(), null, null);
WebDataBinder dataBinder = context.createDataBinder(exchange, null, null);
assertNotNull(dataBinder.getDisallowedFields());
assertEquals("id", dataBinder.getDisallowedFields()[0]);
@ -73,16 +68,18 @@ public class InitBinderBindingContextTests {
ConversionService conversionService = new DefaultFormattingConversionService();
bindingInitializer.setConversionService(conversionService);
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
BindingContext context = createBindingContext("initBinder", WebDataBinder.class);
WebDataBinder dataBinder = context.createDataBinder(createExchange(), null, null);
WebDataBinder dataBinder = context.createDataBinder(exchange, null, null);
assertSame(conversionService, dataBinder.getConversionService());
}
@Test
public void createBinderWithAttrName() throws Exception {
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
BindingContext context = createBindingContext("initBinderWithAttributeName", WebDataBinder.class);
WebDataBinder dataBinder = context.createDataBinder(createExchange(), null, "foo");
WebDataBinder dataBinder = context.createDataBinder(exchange, null, "foo");
assertNotNull(dataBinder.getDisallowedFields());
assertEquals("id", dataBinder.getDisallowedFields()[0]);
@ -90,44 +87,43 @@ public class InitBinderBindingContextTests {
@Test
public void createBinderWithAttrNameNoMatch() throws Exception {
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
BindingContext context = createBindingContext("initBinderWithAttributeName", WebDataBinder.class);
WebDataBinder dataBinder = context.createDataBinder(createExchange(), null, "invalidName");
WebDataBinder dataBinder = context.createDataBinder(exchange, null, "invalidName");
assertNull(dataBinder.getDisallowedFields());
}
@Test
public void createBinderNullAttrName() throws Exception {
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
BindingContext context = createBindingContext("initBinderWithAttributeName", WebDataBinder.class);
WebDataBinder dataBinder = context.createDataBinder(createExchange(), null, null);
WebDataBinder dataBinder = context.createDataBinder(exchange, null, null);
assertNull(dataBinder.getDisallowedFields());
}
@Test(expected = IllegalStateException.class)
public void returnValueNotExpected() throws Exception {
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
BindingContext context = createBindingContext("initBinderReturnValue", WebDataBinder.class);
context.createDataBinder(createExchange(), null, "invalidName");
context.createDataBinder(exchange, null, "invalidName");
}
@Test
public void createBinderTypeConversion() throws Exception {
this.request = MockServerHttpRequest.get("/path?requestParam=22").build();
ServerWebExchange exchange = MockServerHttpRequest.get("/path?requestParam=22").toExchange();
ReactiveAdapterRegistry adapterRegistry = new ReactiveAdapterRegistry();
this.argumentResolvers.add(new RequestParamMethodArgumentResolver(null, adapterRegistry, false));
BindingContext context = createBindingContext("initBinderTypeConversion", WebDataBinder.class, int.class);
WebDataBinder dataBinder = context.createDataBinder(createExchange(), null, "foo");
WebDataBinder dataBinder = context.createDataBinder(exchange, null, "foo");
assertNotNull(dataBinder.getDisallowedFields());
assertEquals("requestParam-22", dataBinder.getDisallowedFields()[0]);
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
private BindingContext createBindingContext(String methodName, Class<?>... parameterTypes) throws Exception {
Object handler = new InitBinderHandler();
Method method = handler.getClass().getMethod(methodName, parameterTypes);

View File

@ -54,6 +54,7 @@ import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.method.ResolvableMethod;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.server.UnsupportedMediaTypeStatusException;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
@ -63,6 +64,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.core.ResolvableType.forClassWithGenerics;
import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.post;
/**
* Unit tests for {@link AbstractMessageReaderArgumentResolver}.
@ -73,8 +75,6 @@ public class MessageReaderArgumentResolverTests {
private AbstractMessageReaderArgumentResolver resolver = resolver(new Jackson2JsonDecoder());
private MockServerHttpRequest request;
private BindingContext bindingContext;
private ResolvableMethod testMethod = ResolvableMethod.on(getClass()).named("handle").build();
@ -82,7 +82,6 @@ public class MessageReaderArgumentResolverTests {
@Before
public void setup() throws Exception {
this.request = request().build();
ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
initializer.setValidator(new TestBeanValidator());
this.bindingContext = new BindingContext(initializer);
@ -91,10 +90,10 @@ public class MessageReaderArgumentResolverTests {
@Test
public void missingContentType() throws Exception {
this.request = request().body("{\"bar\":\"BARBAR\",\"foo\":\"FOOFOO\"}");
ServerWebExchange exchange = post("/path").body("{\"bar\":\"BARBAR\",\"foo\":\"FOOFOO\"}").toExchange();
ResolvableType type = forClassWithGenerics(Mono.class, TestBean.class);
MethodParameter param = this.testMethod.arg(type);
Mono<Object> result = this.resolver.readBody(param, true, this.bindingContext, exchange());
Mono<Object> result = this.resolver.readBody(param, true, this.bindingContext, exchange);
StepVerifier.create(result).expectError(UnsupportedMediaTypeStatusException.class).verify();
}
@ -103,11 +102,11 @@ public class MessageReaderArgumentResolverTests {
@Test @SuppressWarnings("unchecked") // SPR-9942
public void emptyBody() throws Exception {
this.request = request().header("Content-Type", "application/json").build();
ServerWebExchange exchange = post("/path").contentType(MediaType.APPLICATION_JSON).toExchange();
ResolvableType type = forClassWithGenerics(Mono.class, TestBean.class);
MethodParameter param = this.testMethod.arg(type);
Mono<TestBean> result = (Mono<TestBean>) this.resolver.readBody(
param, true, this.bindingContext, exchange()).block();
param, true, this.bindingContext, exchange).block();
StepVerifier.create(result).expectError(ServerWebInputException.class).verify();
}
@ -296,8 +295,8 @@ public class MessageReaderArgumentResolverTests {
@SuppressWarnings("unchecked")
private <T> T resolveValue(MethodParameter param, String body) {
this.request = request().contentType(MediaType.APPLICATION_JSON).body(body);
Mono<Object> result = this.resolver.readBody(param, true, this.bindingContext, exchange());
ServerWebExchange exchange = post("/path").contentType(MediaType.APPLICATION_JSON).body(body).toExchange();
Mono<Object> result = this.resolver.readBody(param, true, this.bindingContext, exchange);
Object value = result.block(Duration.ofSeconds(5));
assertNotNull(value);
@ -307,14 +306,6 @@ public class MessageReaderArgumentResolverTests {
return (T) value;
}
private MockServerHttpRequest.BodyBuilder request() {
return MockServerHttpRequest.post("/path");
}
private DefaultServerWebExchange exchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
@SuppressWarnings("Convert2MethodRef")
private AbstractMessageReaderArgumentResolver resolver(Decoder<?>... decoders) {
List<HttpMessageReader<?>> readers = new ArrayList<>();

View File

@ -29,7 +29,6 @@ import java.util.List;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import io.reactivex.Flowable;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@ -42,23 +41,20 @@ import org.springframework.core.codec.ByteBufferEncoder;
import org.springframework.core.codec.CharSequenceEncoder;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.ResourceHttpMessageWriter;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.http.codec.xml.Jaxb2XmlEncoder;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.ObjectUtils;
import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.springframework.core.io.buffer.support.DataBufferTestUtils.dumpString;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8;
import static org.springframework.web.method.ResolvableMethod.on;
@ -70,18 +66,26 @@ import static org.springframework.web.reactive.HandlerMapping.PRODUCIBLE_MEDIA_T
*/
public class MessageWriterResultHandlerTests {
private AbstractMessageWriterResultHandler resultHandler;
private final AbstractMessageWriterResultHandler resultHandler = initResultHandler();
private MockServerHttpResponse response = new MockServerHttpResponse();
private ServerWebExchange exchange;
private final MockServerWebExchange exchange = MockServerHttpRequest.get("/path").toExchange();
@Before
public void setup() throws Exception {
this.resultHandler = createResultHandler();
ServerHttpRequest request = MockServerHttpRequest.get("/path").build();
this.exchange = new DefaultServerWebExchange(request, this.response);
private AbstractMessageWriterResultHandler initResultHandler(HttpMessageWriter<?>... writers) {
List<HttpMessageWriter<?>> writerList;
if (ObjectUtils.isEmpty(writers)) {
writerList = new ArrayList<>();
writerList.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
writerList.add(new EncoderHttpMessageWriter<>(new CharSequenceEncoder()));
writerList.add(new ResourceHttpMessageWriter());
writerList.add(new EncoderHttpMessageWriter<>(new Jaxb2XmlEncoder()));
writerList.add(new EncoderHttpMessageWriter<>(new Jackson2JsonEncoder()));
}
else {
writerList = Arrays.asList(writers);
}
RequestedContentTypeResolver resolver = new RequestedContentTypeResolverBuilder().build();
return new AbstractMessageWriterResultHandler(writerList, resolver) {};
}
@ -91,7 +95,7 @@ public class MessageWriterResultHandlerTests {
MethodParameter type = on(TestController.class).resolveReturnType(Resource.class);
this.resultHandler.writeBody(body, type, this.exchange).block(Duration.ofSeconds(5));
assertEquals("image/x-png", this.response.getHeaders().getFirst("Content-Type"));
assertEquals("image/x-png", this.exchange.getResponse().getHeaders().getFirst("Content-Type"));
}
@Test // SPR-13631
@ -103,7 +107,7 @@ public class MessageWriterResultHandlerTests {
MethodParameter type = on(TestController.class).resolveReturnType(String.class);
this.resultHandler.writeBody(body, type, this.exchange).block(Duration.ofSeconds(5));
assertEquals(APPLICATION_JSON_UTF8, this.response.getHeaders().getContentType());
assertEquals(APPLICATION_JSON_UTF8, this.exchange.getResponse().getHeaders().getContentType());
}
@Test
@ -127,8 +131,8 @@ public class MessageWriterResultHandlerTests {
private void testVoid(Object body, MethodParameter returnType) {
this.resultHandler.writeBody(body, returnType, this.exchange).block(Duration.ofSeconds(5));
assertNull(this.response.getHeaders().get("Content-Type"));
StepVerifier.create(this.response.getBody())
assertNull(this.exchange.getResponse().getHeaders().get("Content-Type"));
StepVerifier.create(this.exchange.getResponse().getBody())
.expectErrorMatches(ex -> ex.getMessage().startsWith("The body is not set.")).verify();
}
@ -138,7 +142,7 @@ public class MessageWriterResultHandlerTests {
MethodParameter type = on(TestController.class).resolveReturnType(OutputStream.class);
HttpMessageWriter<?> writer = new EncoderHttpMessageWriter<>(new ByteBufferEncoder());
Mono<Void> mono = createResultHandler(writer).writeBody(body, type, this.exchange);
Mono<Void> mono = initResultHandler(writer).writeBody(body, type, this.exchange);
StepVerifier.create(mono).expectError(IllegalStateException.class).verify();
}
@ -150,7 +154,7 @@ public class MessageWriterResultHandlerTests {
List<ParentClass> body = Arrays.asList(new Foo("foo"), new Bar("bar"));
this.resultHandler.writeBody(body, returnType, this.exchange).block(Duration.ofSeconds(5));
assertEquals(APPLICATION_JSON_UTF8, this.response.getHeaders().getContentType());
assertEquals(APPLICATION_JSON_UTF8, this.exchange.getResponse().getHeaders().getContentType());
assertResponseBody("[{\"type\":\"foo\",\"parentProperty\":\"foo\"}," +
"{\"type\":\"bar\",\"parentProperty\":\"bar\"}]");
}
@ -161,7 +165,7 @@ public class MessageWriterResultHandlerTests {
MethodParameter type = on(TestController.class).resolveReturnType(Identifiable.class);
this.resultHandler.writeBody(body, type, this.exchange).block(Duration.ofSeconds(5));
assertEquals(APPLICATION_JSON_UTF8, this.response.getHeaders().getContentType());
assertEquals(APPLICATION_JSON_UTF8, this.exchange.getResponse().getHeaders().getContentType());
assertResponseBody("{\"id\":123,\"name\":\"foo\"}");
}
@ -173,32 +177,14 @@ public class MessageWriterResultHandlerTests {
List<SimpleBean> body = Arrays.asList(new SimpleBean(123L, "foo"), new SimpleBean(456L, "bar"));
this.resultHandler.writeBody(body, returnType, this.exchange).block(Duration.ofSeconds(5));
assertEquals(APPLICATION_JSON_UTF8, this.response.getHeaders().getContentType());
assertEquals(APPLICATION_JSON_UTF8, this.exchange.getResponse().getHeaders().getContentType());
assertResponseBody("[{\"id\":123,\"name\":\"foo\"},{\"id\":456,\"name\":\"bar\"}]");
}
private AbstractMessageWriterResultHandler createResultHandler(HttpMessageWriter<?>... writers) {
List<HttpMessageWriter<?>> writerList;
if (ObjectUtils.isEmpty(writers)) {
writerList = new ArrayList<>();
writerList.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
writerList.add(new EncoderHttpMessageWriter<>(new CharSequenceEncoder()));
writerList.add(new ResourceHttpMessageWriter());
writerList.add(new EncoderHttpMessageWriter<>(new Jaxb2XmlEncoder()));
writerList.add(new EncoderHttpMessageWriter<>(new Jackson2JsonEncoder()));
}
else {
writerList = Arrays.asList(writers);
}
RequestedContentTypeResolver resolver = new RequestedContentTypeResolverBuilder().build();
return new AbstractMessageWriterResultHandler(writerList, resolver) {};
}
private void assertResponseBody(String responseBody) {
StepVerifier.create(this.response.getBody())
.consumeNextWith(buf -> assertEquals(responseBody,
DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8)))
StepVerifier.create(this.exchange.getResponse().getBody())
.consumeNextWith(buf -> assertEquals(responseBody, dumpString(buf, StandardCharsets.UTF_8)))
.expectComplete()
.verify();
}

View File

@ -17,6 +17,7 @@
package org.springframework.web.reactive.result.method.annotation;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.Map;
import java.util.function.Function;
@ -31,7 +32,6 @@ import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@ -41,7 +41,6 @@ import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.method.ResolvableMethod;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -123,7 +122,7 @@ public class ModelAttributeMethodArgumentResolverTests {
testBindFoo(parameter, mono -> {
assertTrue(mono.getClass().getName(), mono instanceof Mono);
Object value = ((Mono<?>) mono).blockMillis(5000);
Object value = ((Mono<?>) mono).block(Duration.ofSeconds(5));
assertEquals(Foo.class, value.getClass());
return (Foo) value;
});
@ -199,7 +198,7 @@ public class ModelAttributeMethodArgumentResolverTests {
testBindFoo(parameter, mono -> {
assertTrue(mono.getClass().getName(), mono instanceof Mono);
Object value = ((Mono<?>) mono).blockMillis(5000);
Object value = ((Mono<?>) mono).block(Duration.ofSeconds(5));
assertEquals(Foo.class, value.getClass());
return (Foo) value;
});
@ -207,8 +206,8 @@ public class ModelAttributeMethodArgumentResolverTests {
private void testBindFoo(MethodParameter param, Function<Object, Foo> valueExtractor) throws Exception {
Object value = createResolver()
.resolveArgument(param, this.bindContext, exchange("name=Robert&age=25"))
.blockMillis(0);
.resolveArgument(param, this.bindContext, postForm("name=Robert&age=25"))
.block(Duration.ZERO);
Foo foo = valueExtractor.apply(value);
assertEquals("Robert", foo.getName());
@ -238,7 +237,7 @@ public class ModelAttributeMethodArgumentResolverTests {
testValidationError(parameter,
resolvedArgumentMono -> {
Object value = resolvedArgumentMono.blockMillis(5000);
Object value = resolvedArgumentMono.block(Duration.ofSeconds(5));
assertNotNull(value);
assertTrue(value instanceof Mono);
return (Mono<?>) value;
@ -254,7 +253,7 @@ public class ModelAttributeMethodArgumentResolverTests {
testValidationError(parameter,
resolvedArgumentMono -> {
Object value = resolvedArgumentMono.blockMillis(5000);
Object value = resolvedArgumentMono.block(Duration.ofSeconds(5));
assertNotNull(value);
assertTrue(value instanceof Single);
return Mono.from(RxReactiveStreams.toPublisher((Single) value));
@ -264,7 +263,7 @@ public class ModelAttributeMethodArgumentResolverTests {
private void testValidationError(MethodParameter param, Function<Mono<?>, Mono<?>> valueMonoExtractor)
throws URISyntaxException {
ServerWebExchange exchange = exchange("age=invalid");
ServerWebExchange exchange = postForm("age=invalid");
Mono<?> mono = createResolver().resolveArgument(param, this.bindContext, exchange);
mono = valueMonoExtractor.apply(mono);
@ -284,10 +283,11 @@ public class ModelAttributeMethodArgumentResolverTests {
return new ModelAttributeMethodArgumentResolver(new ReactiveAdapterRegistry(), false);
}
private ServerWebExchange exchange(String formData) throws URISyntaxException {
MediaType mediaType = MediaType.APPLICATION_FORM_URLENCODED;
MockServerHttpRequest request = MockServerHttpRequest.post("/").contentType(mediaType).body(formData);
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
private ServerWebExchange postForm(String formData) throws URISyntaxException {
return MockServerHttpRequest.post("/")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(formData)
.toExchange();
}

View File

@ -22,7 +22,6 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Mono;
import rx.Single;
@ -30,7 +29,6 @@ import rx.Single;
import org.springframework.core.MethodIntrospector;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.ui.Model;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
@ -44,7 +42,6 @@ import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.result.method.InvocableHandlerMethod;
import org.springframework.web.reactive.result.method.SyncInvocableHandlerMethod;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
@ -57,20 +54,9 @@ import static org.springframework.web.reactive.result.method.annotation.RequestM
*/
public class ModelInitializerTests {
private ModelInitializer modelInitializer;
private final ModelInitializer modelInitializer = new ModelInitializer(new ReactiveAdapterRegistry());
private ServerWebExchange exchange;
@Before
public void setup() throws Exception {
this.modelInitializer = new ModelInitializer(new ReactiveAdapterRegistry());
MockServerHttpRequest request = MockServerHttpRequest.get("/path").build();
MockServerHttpResponse response = new MockServerHttpResponse();
this.exchange = new DefaultServerWebExchange(request, response);
}
private final ServerWebExchange exchange = MockServerHttpRequest.get("/path").toExchange();
@SuppressWarnings("unchecked")

View File

@ -27,15 +27,12 @@ import reactor.core.publisher.Mono;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -51,7 +48,7 @@ public class PathVariableMapMethodArgumentResolverTests {
private PathVariableMapMethodArgumentResolver resolver;
private ServerWebExchange exchange;
private final MockServerWebExchange exchange= MockServerHttpRequest.get("/").toExchange();
private MethodParameter paramMap;
private MethodParameter paramNamedMap;
@ -63,9 +60,6 @@ public class PathVariableMapMethodArgumentResolverTests {
public void setup() throws Exception {
this.resolver = new PathVariableMapMethodArgumentResolver(new ReactiveAdapterRegistry());
ServerHttpRequest request = MockServerHttpRequest.get("/").build();
this.exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
Method method = ReflectionUtils.findMethod(getClass(), "handle", (Class<?>[]) null);
this.paramMap = new MethodParameter(method, 0);
this.paramNamedMap = new MethodParameter(method, 1);

View File

@ -30,17 +30,14 @@ import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.server.ServerErrorException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -57,7 +54,7 @@ public class PathVariableMethodArgumentResolverTests {
private PathVariableMethodArgumentResolver resolver;
private ServerWebExchange exchange;
private final MockServerWebExchange exchange= MockServerHttpRequest.get("/").toExchange();
private MethodParameter paramNamedString;
private MethodParameter paramString;
@ -70,9 +67,6 @@ public class PathVariableMethodArgumentResolverTests {
public void setup() throws Exception {
this.resolver = new PathVariableMethodArgumentResolver(null, new ReactiveAdapterRegistry());
ServerHttpRequest request = MockServerHttpRequest.get("/").build();
this.exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
Method method = ReflectionUtils.findMethod(getClass(), "handle", (Class<?>[]) null);
paramNamedString = new SynthesizingMethodParameter(method, 0);
paramString = new SynthesizingMethodParameter(method, 1);

View File

@ -31,18 +31,21 @@ import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link RequestAttributeMethodArgumentResolver}.
@ -53,7 +56,7 @@ public class RequestAttributeMethodArgumentResolverTests {
private RequestAttributeMethodArgumentResolver resolver;
private ServerWebExchange exchange;
private final MockServerWebExchange exchange= MockServerHttpRequest.get("/").toExchange();
private Method handleMethod;
@ -64,10 +67,6 @@ public class RequestAttributeMethodArgumentResolverTests {
context.refresh();
ReactiveAdapterRegistry adapterRegistry = new ReactiveAdapterRegistry();
this.resolver = new RequestAttributeMethodArgumentResolver(context.getBeanFactory(), adapterRegistry);
ServerHttpRequest request = MockServerHttpRequest.get("/").build();
this.exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
this.handleMethod = ReflectionUtils.findMethod(getClass(), "handleWithRequestAttribute", (Class<?>[]) null);
}

View File

@ -37,13 +37,11 @@ import org.springframework.core.codec.StringDecoder;
import org.springframework.http.codec.DecoderHttpMessageReader;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.method.ResolvableMethod;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -216,8 +214,7 @@ public class RequestBodyArgumentResolverTests {
@SuppressWarnings("unchecked")
private <T> T resolveValue(MethodParameter param, String body) {
MockServerHttpRequest request = MockServerHttpRequest.post("/path").body(body);
ServerWebExchange exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
ServerWebExchange exchange = MockServerHttpRequest.post("/path").body(body).toExchange();
Mono<Object> result = this.resolver.readBody(param, true, new BindingContext(), exchange);
Object value = result.block(Duration.ofSeconds(5));
@ -231,8 +228,7 @@ public class RequestBodyArgumentResolverTests {
@SuppressWarnings("unchecked")
private <T> T resolveValueWithEmptyBody(MethodParameter param) {
MockServerHttpRequest request = MockServerHttpRequest.post("/path").build();
ServerWebExchange exchange = new DefaultServerWebExchange(request, new MockServerHttpResponse());
ServerWebExchange exchange = MockServerHttpRequest.post("/path").build().toExchange();
Mono<Object> result = this.resolver.resolveArgument(param, new BindingContext(), exchange);
Object value = result.block(Duration.ofSeconds(5));

View File

@ -28,16 +28,17 @@ import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.ServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link RequestHeaderMapMethodArgumentResolver}.
@ -48,8 +49,6 @@ public class RequestHeaderMapMethodArgumentResolverTests {
private RequestHeaderMapMethodArgumentResolver resolver;
private ServerHttpRequest request;
private MethodParameter paramMap;
private MethodParameter paramMultiValueMap;
private MethodParameter paramHttpHeaders;
@ -60,7 +59,6 @@ public class RequestHeaderMapMethodArgumentResolverTests {
@Before
public void setup() throws Exception {
resolver = new RequestHeaderMapMethodArgumentResolver(new ReactiveAdapterRegistry());
request = MockServerHttpRequest.get("/").build();
Method method = ReflectionUtils.findMethod(getClass(), "params", (Class<?>[]) null);
paramMap = new SynthesizingMethodParameter(method, 0);
@ -94,9 +92,9 @@ public class RequestHeaderMapMethodArgumentResolverTests {
String name = "foo";
String value = "bar";
Map<String, String> expected = Collections.singletonMap(name, value);
request = MockServerHttpRequest.get("/").header(name, value).build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").header(name, value).toExchange();
Mono<Object> mono = resolver.resolveArgument(paramMap, null, createExchange());
Mono<Object> mono = resolver.resolveArgument(paramMap, null, exchange);
Object result = mono.block();
assertTrue(result instanceof Map);
@ -108,13 +106,13 @@ public class RequestHeaderMapMethodArgumentResolverTests {
String name = "foo";
String value1 = "bar";
String value2 = "baz";
request = MockServerHttpRequest.get("/").header(name, value1, value2).build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").header(name, value1, value2).toExchange();
MultiValueMap<String, String> expected = new LinkedMultiValueMap<>(1);
expected.add(name, value1);
expected.add(name, value2);
Mono<Object> mono = resolver.resolveArgument(paramMultiValueMap, null, createExchange());
Mono<Object> mono = resolver.resolveArgument(paramMultiValueMap, null, exchange);
Object result = mono.block();
assertTrue(result instanceof MultiValueMap);
@ -126,13 +124,13 @@ public class RequestHeaderMapMethodArgumentResolverTests {
String name = "foo";
String value1 = "bar";
String value2 = "baz";
request = MockServerHttpRequest.get("/").header(name, value1, value2).build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").header(name, value1, value2).toExchange();
HttpHeaders expected = new HttpHeaders();
expected.add(name, value1);
expected.add(name, value2);
Mono<Object> mono = resolver.resolveArgument(paramHttpHeaders, null, createExchange());
Mono<Object> mono = resolver.resolveArgument(paramHttpHeaders, null, exchange);
Object result = mono.block();
assertTrue(result instanceof HttpHeaders);
@ -140,11 +138,6 @@ public class RequestHeaderMapMethodArgumentResolverTests {
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
@SuppressWarnings("unused")
public void params(
@RequestHeader Map<?, ?> param1,

View File

@ -35,10 +35,12 @@ import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
@ -53,8 +55,6 @@ public class RequestHeaderMethodArgumentResolverTests {
private RequestHeaderMethodArgumentResolver resolver;
private ServerHttpRequest request;
private BindingContext bindingContext;
private MethodParameter paramNamedDefaultValueStringHeader;
@ -75,8 +75,6 @@ public class RequestHeaderMethodArgumentResolverTests {
ReactiveAdapterRegistry adapterRegistry = new ReactiveAdapterRegistry();
this.resolver = new RequestHeaderMethodArgumentResolver(context.getBeanFactory(), adapterRegistry);
this.request = MockServerHttpRequest.get("/").build();
ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
initializer.setConversionService(new DefaultFormattingConversionService());
this.bindingContext = new BindingContext(initializer);
@ -113,10 +111,10 @@ public class RequestHeaderMethodArgumentResolverTests {
@Test
public void resolveStringArgument() throws Exception {
String expected = "foo";
this.request = MockServerHttpRequest.get("/").header("name", expected).build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("name", expected).toExchange();
Mono<Object> mono = this.resolver.resolveArgument(
this.paramNamedDefaultValueStringHeader, this.bindingContext, createExchange());
this.paramNamedDefaultValueStringHeader, this.bindingContext, exchange);
Object result = mono.block();
assertTrue(result instanceof String);
@ -125,10 +123,10 @@ public class RequestHeaderMethodArgumentResolverTests {
@Test
public void resolveStringArrayArgument() throws Exception {
this.request = MockServerHttpRequest.get("/").header("name", "foo", "bar").build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("name", "foo", "bar").toExchange();
Mono<Object> mono = this.resolver.resolveArgument(
this.paramNamedValueStringArray, this.bindingContext, createExchange());
this.paramNamedValueStringArray, this.bindingContext, exchange);
Object result = mono.block();
assertTrue(result instanceof String[]);
@ -137,8 +135,9 @@ public class RequestHeaderMethodArgumentResolverTests {
@Test
public void resolveDefaultValue() throws Exception {
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
Mono<Object> mono = this.resolver.resolveArgument(
this.paramNamedDefaultValueStringHeader, this.bindingContext, createExchange());
this.paramNamedDefaultValueStringHeader, this.bindingContext, exchange);
Object result = mono.block();
assertTrue(result instanceof String);
@ -150,7 +149,8 @@ public class RequestHeaderMethodArgumentResolverTests {
System.setProperty("systemProperty", "bar");
try {
Mono<Object> mono = this.resolver.resolveArgument(
this.paramSystemProperty, this.bindingContext, createExchange());
this.paramSystemProperty, this.bindingContext,
MockServerHttpRequest.get("/").toExchange());
Object result = mono.block();
assertTrue(result instanceof String);
@ -164,12 +164,12 @@ public class RequestHeaderMethodArgumentResolverTests {
@Test
public void resolveNameFromSystemPropertyThroughExpression() throws Exception {
String expected = "foo";
this.request = MockServerHttpRequest.get("/").header("bar", expected).build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("bar", expected).toExchange();
System.setProperty("systemProperty", "bar");
try {
Mono<Object> mono = this.resolver.resolveArgument(
this.paramResolvedNameWithExpression, this.bindingContext, createExchange());
this.paramResolvedNameWithExpression, this.bindingContext, exchange);
Object result = mono.block();
assertTrue(result instanceof String);
@ -183,12 +183,12 @@ public class RequestHeaderMethodArgumentResolverTests {
@Test
public void resolveNameFromSystemPropertyThroughPlaceholder() throws Exception {
String expected = "foo";
this.request = MockServerHttpRequest.get("/").header("bar", expected).build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("bar", expected).toExchange();
System.setProperty("systemProperty", "bar");
try {
Mono<Object> mono = this.resolver.resolveArgument(
this.paramResolvedNameWithPlaceholder, this.bindingContext, createExchange());
this.paramResolvedNameWithPlaceholder, this.bindingContext, exchange);
Object result = mono.block();
assertTrue(result instanceof String);
@ -202,7 +202,8 @@ public class RequestHeaderMethodArgumentResolverTests {
@Test
public void notFound() throws Exception {
Mono<Object> mono = resolver.resolveArgument(
this.paramNamedValueStringArray, this.bindingContext, createExchange());
this.paramNamedValueStringArray, this.bindingContext,
MockServerHttpRequest.get("/").toExchange());
StepVerifier.create(mono)
.expectNextCount(0)
@ -214,9 +215,9 @@ public class RequestHeaderMethodArgumentResolverTests {
@SuppressWarnings("deprecation")
public void dateConversion() throws Exception {
String rfc1123val = "Thu, 21 Apr 2016 17:11:08 +0100";
this.request = MockServerHttpRequest.get("/").header("name", rfc1123val).build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("name", rfc1123val).toExchange();
Mono<Object> mono = this.resolver.resolveArgument(this.paramDate, this.bindingContext, createExchange());
Mono<Object> mono = this.resolver.resolveArgument(this.paramDate, this.bindingContext, exchange);
Object result = mono.block();
assertTrue(result instanceof Date);
@ -226,9 +227,9 @@ public class RequestHeaderMethodArgumentResolverTests {
@Test
public void instantConversion() throws Exception {
String rfc1123val = "Thu, 21 Apr 2016 17:11:08 +0100";
this.request = MockServerHttpRequest.get("/").header("name", rfc1123val).build();
ServerWebExchange exchange = MockServerHttpRequest.get("/").header("name", rfc1123val).toExchange();
Mono<Object> mono = this.resolver.resolveArgument(this.paramInstant, this.bindingContext, createExchange());
Mono<Object> mono = this.resolver.resolveArgument(this.paramInstant, this.bindingContext, exchange);
Object result = mono.block();
assertTrue(result instanceof Instant);
@ -236,11 +237,6 @@ public class RequestHeaderMethodArgumentResolverTests {
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
@SuppressWarnings("unused")
public void params(
@RequestHeader(name = "name", defaultValue = "bar") String param1,

View File

@ -29,17 +29,17 @@ import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.method.ResolvableMethod;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED;
import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.post;
import static org.springframework.web.method.MvcAnnotationPredicates.requestParam;
/**
@ -88,7 +88,7 @@ public class RequestParamMapMethodArgumentResolverTests {
@Test
public void resolveMapArgumentWithQueryString() throws Exception {
MethodParameter param = this.testMethod.annot(requestParam().name("")).arg(Map.class);
Object result= resolve(param, exchangeWithQuery("foo=bar"));
Object result= resolve(param, MockServerHttpRequest.get("/path?foo=bar").toExchange());
assertTrue(result instanceof Map);
assertEquals(Collections.singletonMap("foo", "bar"), result);
}
@ -96,7 +96,8 @@ public class RequestParamMapMethodArgumentResolverTests {
@Test
public void resolveMapArgumentWithFormData() throws Exception {
MethodParameter param = this.testMethod.annot(requestParam().name("")).arg(Map.class);
Object result= resolve(param, exchangeWithFormData("foo=bar"));
ServerWebExchange exchange = post("/").contentType(APPLICATION_FORM_URLENCODED).body("foo=bar").toExchange();
Object result= resolve(param, exchange);
assertTrue(result instanceof Map);
assertEquals(Collections.singletonMap("foo", "bar"), result);
}
@ -104,7 +105,7 @@ public class RequestParamMapMethodArgumentResolverTests {
@Test
public void resolveMultiValueMapArgument() throws Exception {
MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(MultiValueMap.class);
ServerWebExchange exchange = exchangeWithQuery("foo=bar&foo=baz");
ServerWebExchange exchange = MockServerHttpRequest.get("/path?foo=bar&foo=baz").toExchange();
Object result= resolve(param, exchange);
assertTrue(result instanceof MultiValueMap);
@ -112,18 +113,6 @@ public class RequestParamMapMethodArgumentResolverTests {
}
private ServerWebExchange exchangeWithQuery(String query) throws URISyntaxException {
MockServerHttpRequest request = MockServerHttpRequest.get("/path?" + query).build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
private ServerWebExchange exchangeWithFormData(String formData) throws URISyntaxException {
MockServerHttpRequest request = MockServerHttpRequest.post("/")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(formData);
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
private Object resolve(MethodParameter parameter, ServerWebExchange exchange) {
return this.resolver.resolveArgument(parameter, null, exchange).blockMillis(0);
}

View File

@ -16,7 +16,6 @@
package org.springframework.web.reactive.result.method.annotation;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
@ -31,15 +30,13 @@ import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.method.MvcAnnotationPredicates;
import org.springframework.web.method.ResolvableMethod;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
@ -139,19 +136,25 @@ public class RequestParamMethodArgumentResolverTests {
@Test
public void resolveWithQueryString() throws Exception {
MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class);
assertEquals("foo", resolve(param, exchangeWithQuery("name=foo")));
assertEquals("foo", resolve(param, MockServerHttpRequest.get("/path?name=foo").toExchange()));
}
@Test
public void resolveWithFormData() throws Exception {
ServerWebExchange exchange = MockServerHttpRequest.post("/path")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body("name=foo")
.toExchange();
MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class);
assertEquals("foo", resolve(param, exchangeWithFormData("name=foo")));
assertEquals("foo", resolve(param, exchange));
}
@Test
public void resolveStringArray() throws Exception {
MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(String[].class);
Object result = resolve(param, exchangeWithQuery("name=foo&name=bar"));
Object result = resolve(param, MockServerHttpRequest.get("/path?name=foo&name=bar").toExchange());
assertTrue(result instanceof String[]);
assertArrayEquals(new String[] {"foo", "bar"}, (String[]) result);
}
@ -159,14 +162,15 @@ public class RequestParamMethodArgumentResolverTests {
@Test
public void resolveDefaultValue() throws Exception {
MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class);
assertEquals("bar", resolve(param, exchange()));
assertEquals("bar", resolve(param, MockServerHttpRequest.get("/").toExchange()));
}
@Test
public void missingRequestParam() throws Exception {
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(String[].class);
Mono<Object> mono = this.resolver.resolveArgument(param, this.bindContext, exchange());
Mono<Object> mono = this.resolver.resolveArgument(param, this.bindContext, exchange);
StepVerifier.create(mono)
.expectNextCount(0)
@ -176,7 +180,7 @@ public class RequestParamMethodArgumentResolverTests {
@Test
public void resolveSimpleTypeParam() throws Exception {
ServerWebExchange exchange = exchangeWithQuery("stringNotAnnot=plainValue");
ServerWebExchange exchange = MockServerHttpRequest.get("/path?stringNotAnnot=plainValue").toExchange();
MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class);
Object result = resolve(param, exchange);
assertEquals("plainValue", result);
@ -185,12 +189,12 @@ public class RequestParamMethodArgumentResolverTests {
@Test // SPR-8561
public void resolveSimpleTypeParamToNull() throws Exception {
MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class);
assertNull(resolve(param, exchange()));
assertNull(resolve(param, MockServerHttpRequest.get("/").toExchange()));
}
@Test // SPR-10180
public void resolveEmptyValueToDefault() throws Exception {
ServerWebExchange exchange = exchangeWithQuery("name=");
ServerWebExchange exchange = MockServerHttpRequest.get("/path?name=").toExchange();
MethodParameter param = this.testMethod.annot(requestParam().notRequired("bar")).arg(String.class);
Object result = resolve(param, exchange);
assertEquals("bar", result);
@ -199,23 +203,23 @@ public class RequestParamMethodArgumentResolverTests {
@Test
public void resolveEmptyValueWithoutDefault() throws Exception {
MethodParameter param = this.testMethod.annotNotPresent(RequestParam.class).arg(String.class);
assertEquals("", resolve(param, exchangeWithQuery("stringNotAnnot=")));
assertEquals("", resolve(param, MockServerHttpRequest.get("/path?stringNotAnnot=").toExchange()));
}
@Test
public void resolveEmptyValueRequiredWithoutDefault() throws Exception {
MethodParameter param = this.testMethod.annot(requestParam()).arg(String.class);
assertEquals("", resolve(param, exchangeWithQuery("name=")));
assertEquals("", resolve(param, MockServerHttpRequest.get("/path?name=").toExchange()));
}
@Test
public void resolveOptionalParamValue() throws Exception {
ServerWebExchange exchange = exchange();
ServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
MethodParameter param = this.testMethod.arg(forClassWithGenerics(Optional.class, Integer.class));
Object result = resolve(param, exchange);
assertEquals(Optional.empty(), result);
exchange = exchangeWithQuery("name=123");
exchange = MockServerHttpRequest.get("/path?name=123").toExchange();
result = resolve(param, exchange);
assertEquals(Optional.class, result.getClass());
@ -225,23 +229,6 @@ public class RequestParamMethodArgumentResolverTests {
}
private ServerWebExchange exchangeWithQuery(String query) throws URISyntaxException {
MockServerHttpRequest request = MockServerHttpRequest.get("/path?" + query).build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
private ServerWebExchange exchangeWithFormData(String formData) throws URISyntaxException {
MockServerHttpRequest request = MockServerHttpRequest.post("/path")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(formData);
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
private ServerWebExchange exchange() {
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
return new DefaultServerWebExchange(request, new MockServerHttpResponse());
}
private Object resolve(MethodParameter parameter, ServerWebExchange exchange) {
return this.resolver.resolveArgument(parameter, this.bindContext, exchange).block(Duration.ZERO);
}

View File

@ -41,30 +41,28 @@ import org.springframework.core.codec.CharSequenceEncoder;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.ResourceHttpMessageWriter;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.http.codec.xml.Jaxb2XmlEncoder;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.util.ObjectUtils;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.HandlerResult;
import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.springframework.core.ResolvableType.forClassWithGenerics;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.http.ResponseEntity.notFound;
import static org.springframework.http.ResponseEntity.ok;
import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get;
import static org.springframework.web.method.ResolvableMethod.on;
import static org.springframework.web.reactive.HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;
/**
* Unit tests for {@link ResponseEntityResultHandler}. When adding a test also
@ -79,23 +77,12 @@ public class ResponseEntityResultHandlerTests {
private ResponseEntityResultHandler resultHandler;
private MockServerHttpRequest request;
private MockServerHttpResponse response;
@Before
public void setup() throws Exception {
this.resultHandler = createHandler();
initExchange();
}
private void initExchange() {
this.request = MockServerHttpRequest.get("/path").build();
this.response = new MockServerHttpResponse();
}
private ResponseEntityResultHandler createHandler(HttpMessageWriter<?>... writers) {
List<HttpMessageWriter<?>> writerList;
if (ObjectUtils.isEmpty(writers)) {
@ -156,11 +143,12 @@ public class ResponseEntityResultHandlerTests {
ResponseEntity<Void> value = ResponseEntity.noContent().build();
MethodParameter returnType = on(TestController.class).resolveReturnType(entity(Void.class));
HandlerResult result = handlerResult(value, returnType);
this.resultHandler.handleResult(createExchange(), result).block(Duration.ofSeconds(5));
MockServerWebExchange exchange = get("/path").toExchange();
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertEquals(HttpStatus.NO_CONTENT, this.response.getStatusCode());
assertEquals(0, this.response.getHeaders().size());
assertResponseBodyIsEmpty();
assertEquals(HttpStatus.NO_CONTENT, exchange.getResponse().getStatusCode());
assertEquals(0, exchange.getResponse().getHeaders().size());
assertResponseBodyIsEmpty(exchange);
}
@Test
@ -169,12 +157,13 @@ public class ResponseEntityResultHandlerTests {
ResponseEntity<Void> value = ResponseEntity.created(location).build();
MethodParameter returnType = on(TestController.class).resolveReturnType(entity(Void.class));
HandlerResult result = handlerResult(value, returnType);
this.resultHandler.handleResult(createExchange(), result).block(Duration.ofSeconds(5));
MockServerWebExchange exchange = get("/path").toExchange();
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertEquals(HttpStatus.CREATED, this.response.getStatusCode());
assertEquals(1, this.response.getHeaders().size());
assertEquals(location, this.response.getHeaders().getLocation());
assertResponseBodyIsEmpty();
assertEquals(HttpStatus.CREATED, exchange.getResponse().getStatusCode());
assertEquals(1, exchange.getResponse().getHeaders().size());
assertEquals(location, exchange.getResponse().getHeaders().getLocation());
assertResponseBodyIsEmpty(exchange);
}
@Test
@ -182,10 +171,11 @@ public class ResponseEntityResultHandlerTests {
Object returnValue = Mono.just(notFound().build());
MethodParameter type = on(TestController.class).resolveReturnType(Mono.class, entity(String.class));
HandlerResult result = handlerResult(returnValue, type);
this.resultHandler.handleResult(createExchange(), result).block(Duration.ofSeconds(5));
MockServerWebExchange exchange = get("/path").toExchange();
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertEquals(HttpStatus.NOT_FOUND, this.response.getStatusCode());
assertResponseBodyIsEmpty();
assertEquals(HttpStatus.NOT_FOUND, exchange.getResponse().getStatusCode());
assertResponseBodyIsEmpty(exchange);
}
@Test
@ -211,40 +201,40 @@ public class ResponseEntityResultHandlerTests {
public void handleReturnValueLastModified() throws Exception {
Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
Instant oneMinAgo = currentTime.minusSeconds(60);
this.request = MockServerHttpRequest.get("/path").ifModifiedSince(currentTime.toEpochMilli()).build();
MockServerWebExchange exchange = get("/path").ifModifiedSince(currentTime.toEpochMilli()).toExchange();
ResponseEntity<String> entity = ok().lastModified(oneMinAgo.toEpochMilli()).body("body");
MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
HandlerResult result = handlerResult(entity, returnType);
this.resultHandler.handleResult(createExchange(), result).block(Duration.ofSeconds(5));
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertConditionalResponse(HttpStatus.NOT_MODIFIED, null, null, oneMinAgo);
assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, null, oneMinAgo);
}
@Test
public void handleReturnValueEtag() throws Exception {
String etagValue = "\"deadb33f8badf00d\"";
this.request = MockServerHttpRequest.get("/path").ifNoneMatch(etagValue).build();
MockServerWebExchange exchange = get("/path").ifNoneMatch(etagValue).toExchange();
ResponseEntity<String> entity = ok().eTag(etagValue).body("body");
MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
HandlerResult result = handlerResult(entity, returnType);
this.resultHandler.handleResult(createExchange(), result).block(Duration.ofSeconds(5));
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertConditionalResponse(HttpStatus.NOT_MODIFIED, null, etagValue, Instant.MIN);
assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, etagValue, Instant.MIN);
}
@Test // SPR-14559
public void handleReturnValueEtagInvalidIfNoneMatch() throws Exception {
this.request = MockServerHttpRequest.get("/path").ifNoneMatch("unquoted").build();
MockServerWebExchange exchange = get("/path").ifNoneMatch("unquoted").toExchange();
ResponseEntity<String> entity = ok().eTag("\"deadb33f8badf00d\"").body("body");
MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
HandlerResult result = handlerResult(entity, returnType);
this.resultHandler.handleResult(createExchange(), result).block(Duration.ofSeconds(5));
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
assertResponseBody("body");
assertEquals(HttpStatus.OK, exchange.getResponse().getStatusCode());
assertResponseBody(exchange, "body");
}
@Test
@ -254,17 +244,17 @@ public class ResponseEntityResultHandlerTests {
Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
Instant oneMinAgo = currentTime.minusSeconds(60);
this.request = MockServerHttpRequest.get("/path")
MockServerWebExchange exchange = get("/path")
.ifNoneMatch(eTag)
.ifModifiedSince(currentTime.toEpochMilli())
.build();
.toExchange();
ResponseEntity<String> entity = ok().eTag(eTag).lastModified(oneMinAgo.toEpochMilli()).body("body");
MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
HandlerResult result = handlerResult(entity, returnType);
this.resultHandler.handleResult(createExchange(), result).block(Duration.ofSeconds(5));
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertConditionalResponse(HttpStatus.NOT_MODIFIED, null, eTag, oneMinAgo);
assertConditionalResponse(exchange, HttpStatus.NOT_MODIFIED, null, eTag, oneMinAgo);
}
@Test
@ -275,65 +265,59 @@ public class ResponseEntityResultHandlerTests {
Instant currentTime = Instant.now().truncatedTo(ChronoUnit.SECONDS);
Instant oneMinAgo = currentTime.minusSeconds(60);
this.request = MockServerHttpRequest.get("/path")
MockServerWebExchange exchange = get("/path")
.ifNoneMatch(etag)
.ifModifiedSince(currentTime.toEpochMilli())
.build();
.toExchange();
ResponseEntity<String> entity = ok().eTag(newEtag).lastModified(oneMinAgo.toEpochMilli()).body("body");
MethodParameter returnType = on(TestController.class).resolveReturnType(entity(String.class));
HandlerResult result = handlerResult(entity, returnType);
this.resultHandler.handleResult(createExchange(), result).block(Duration.ofSeconds(5));
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertConditionalResponse(HttpStatus.OK, "body", newEtag, oneMinAgo);
assertConditionalResponse(exchange, HttpStatus.OK, "body", newEtag, oneMinAgo);
}
@Test // SPR-14877
public void handleMonoWithWildcardBodyType() throws Exception {
ServerWebExchange exchange = createExchange();
exchange.getAttributes().put(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE,
Collections.singleton(MediaType.APPLICATION_JSON));
MockServerWebExchange exchange = get("/path").toExchange();
exchange.getAttributes().put(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(APPLICATION_JSON));
MethodParameter type = on(TestController.class).resolveReturnType(Mono.class, ResponseEntity.class);
HandlerResult result = new HandlerResult(new TestController(), Mono.just(ok().body("body")), type);
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
assertResponseBody("\"body\"");
assertEquals(HttpStatus.OK, exchange.getResponse().getStatusCode());
assertResponseBody(exchange, "\"body\"");
}
@Test // SPR-14877
public void handleMonoWithWildcardBodyTypeAndNullBody() throws Exception {
ServerWebExchange exchange = createExchange();
exchange.getAttributes().put(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE,
Collections.singleton(MediaType.APPLICATION_JSON));
MockServerWebExchange exchange = get("/path").toExchange();
exchange.getAttributes().put(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(APPLICATION_JSON));
MethodParameter returnType = on(TestController.class).resolveReturnType(Mono.class, ResponseEntity.class);
HandlerResult result = new HandlerResult(new TestController(), Mono.just(notFound().build()), returnType);
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertEquals(HttpStatus.NOT_FOUND, this.response.getStatusCode());
assertResponseBodyIsEmpty();
assertEquals(HttpStatus.NOT_FOUND, exchange.getResponse().getStatusCode());
assertResponseBodyIsEmpty(exchange);
}
private void testHandle(Object returnValue, MethodParameter returnType) {
initExchange();
MockServerWebExchange exchange = get("/path").toExchange();
HandlerResult result = handlerResult(returnValue, returnType);
this.resultHandler.handleResult(createExchange(), result).block(Duration.ofSeconds(5));
this.resultHandler.handleResult(exchange, result).block(Duration.ofSeconds(5));
assertEquals(HttpStatus.OK, this.response.getStatusCode());
assertEquals("text/plain;charset=UTF-8", this.response.getHeaders().getFirst("Content-Type"));
assertResponseBody("abc");
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, this.response);
assertEquals(HttpStatus.OK, exchange.getResponse().getStatusCode());
assertEquals("text/plain;charset=UTF-8", exchange.getResponse().getHeaders().getFirst("Content-Type"));
assertResponseBody(exchange, "abc");
}
private ResolvableType entity(Class<?> bodyType) {
@ -344,35 +328,35 @@ public class ResponseEntityResultHandlerTests {
return new HandlerResult(new TestController(), returnValue, returnType);
}
private void assertResponseBody(String responseBody) {
StepVerifier.create(this.response.getBody())
private void assertResponseBody(MockServerWebExchange exchange, String responseBody) {
StepVerifier.create(exchange.getResponse().getBody())
.consumeNextWith(buf -> assertEquals(responseBody,
DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8)))
.expectComplete()
.verify();
}
private void assertResponseBodyIsEmpty() {
StepVerifier.create(this.response.getBody()).expectComplete().verify();
private void assertResponseBodyIsEmpty(MockServerWebExchange exchange) {
StepVerifier.create(exchange.getResponse().getBody()).expectComplete().verify();
}
private void assertConditionalResponse(HttpStatus status, String body, String etag, Instant lastModified)
throws Exception {
private void assertConditionalResponse(MockServerWebExchange exchange, HttpStatus status,
String body, String etag, Instant lastModified) throws Exception {
assertEquals(status, this.response.getStatusCode());
assertEquals(status, exchange.getResponse().getStatusCode());
if (body != null) {
assertResponseBody(body);
assertResponseBody(exchange, body);
}
else {
assertResponseBodyIsEmpty();
assertResponseBodyIsEmpty(exchange);
}
if (etag != null) {
assertEquals(1, this.response.getHeaders().get(HttpHeaders.ETAG).size());
assertEquals(etag, this.response.getHeaders().getETag());
assertEquals(1, exchange.getResponse().getHeaders().get(HttpHeaders.ETAG).size());
assertEquals(etag, exchange.getResponse().getHeaders().getETag());
}
if (lastModified.isAfter(Instant.EPOCH)) {
assertEquals(1, this.response.getHeaders().get(HttpHeaders.LAST_MODIFIED).size());
assertEquals(lastModified.toEpochMilli(), this.response.getHeaders().getLastModified());
assertEquals(1, exchange.getResponse().getHeaders().get(HttpHeaders.LAST_MODIFIED).size());
assertEquals(lastModified.toEpochMilli(), exchange.getResponse().getHeaders().getLastModified());
}
}

View File

@ -16,7 +16,6 @@
package org.springframework.web.reactive.result.method.annotation;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Mono;
@ -26,17 +25,16 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.reactive.BindingContext;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.method.ResolvableMethod;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager;
import org.springframework.web.server.session.WebSessionManager;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for {@link ServerWebExchangeArgumentResolver}.
@ -47,21 +45,11 @@ public class ServerWebExchangeArgumentResolverTests {
private final ServerWebExchangeArgumentResolver resolver =
new ServerWebExchangeArgumentResolver(new ReactiveAdapterRegistry());
private ServerWebExchange exchange;
private final MockServerWebExchange exchange = MockServerHttpRequest.get("/path").toExchange();
private ResolvableMethod testMethod = ResolvableMethod.on(getClass()).named("handle").build();
@Before
public void setup() throws Exception {
ServerHttpRequest request = MockServerHttpRequest.get("/path").build();
ServerHttpResponse response = new MockServerHttpResponse();
WebSessionManager sessionManager = new MockWebSessionManager(mock(WebSession.class));
this.exchange = new DefaultServerWebExchange(request, response, sessionManager);
}
@Test
public void supportsParameter() throws Exception {
assertTrue(this.resolver.supportsParameter(this.testMethod.arg(ServerWebExchange.class)));

View File

@ -17,6 +17,7 @@
package org.springframework.web.reactive.result.view;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@ -34,14 +35,10 @@ import org.springframework.http.MediaType;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.http.codec.xml.Jaxb2XmlEncoder;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.ModelMap;
import org.springframework.util.MimeType;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.DefaultWebSessionManager;
import org.springframework.web.server.session.WebSessionManager;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
@ -146,14 +143,11 @@ public class HttpMessageWriterViewTests {
this.model.addAttribute("pojoData", pojoData);
this.view.setModelKeys(Collections.singleton("pojoData"));
MockServerHttpRequest request = MockServerHttpRequest.get("/path").build();
MockServerHttpResponse response = new MockServerHttpResponse();
WebSessionManager manager = new DefaultWebSessionManager();
ServerWebExchange exchange = new DefaultServerWebExchange(request, response, manager);
MockServerWebExchange exchange = MockServerHttpRequest.get("/path").toExchange();
this.view.render(this.model, MediaType.APPLICATION_JSON, exchange).blockMillis(5000);
this.view.render(this.model, MediaType.APPLICATION_JSON, exchange).block(Duration.ofSeconds(5));
StepVerifier.create(response.getBody())
StepVerifier.create(exchange.getResponse().getBody())
.consumeNextWith( buf -> assertEquals("{\"foo\":\"f\",\"bar\":\"b\"}",
DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8))
)

View File

@ -27,9 +27,8 @@ import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -43,15 +42,12 @@ import static org.junit.Assert.assertTrue;
*/
public class RedirectViewTests {
private MockServerHttpRequest request;
private MockServerHttpResponse response;
private MockServerWebExchange exchange;
@Before
public void setup() {
this.request = MockServerHttpRequest.get("/").contextPath("/context").build();
this.response = new MockServerHttpResponse();
this.exchange = MockServerHttpRequest.get("/").contextPath("/context").toExchange();
}
@ -65,34 +61,34 @@ public class RedirectViewTests {
public void defaultStatusCode() {
String url = "http://url.somewhere.com";
RedirectView view = new RedirectView(url);
view.render(new HashMap<>(), MediaType.TEXT_HTML, createExchange());
assertEquals(HttpStatus.SEE_OTHER, this.response.getStatusCode());
assertEquals(URI.create(url), this.response.getHeaders().getLocation());
view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange);
assertEquals(HttpStatus.SEE_OTHER, this.exchange.getResponse().getStatusCode());
assertEquals(URI.create(url), this.exchange.getResponse().getHeaders().getLocation());
}
@Test
public void customStatusCode() {
String url = "http://url.somewhere.com";
RedirectView view = new RedirectView(url, HttpStatus.FOUND);
view.render(new HashMap<>(), MediaType.TEXT_HTML, createExchange());
assertEquals(HttpStatus.FOUND, this.response.getStatusCode());
assertEquals(URI.create(url), this.response.getHeaders().getLocation());
view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange);
assertEquals(HttpStatus.FOUND, this.exchange.getResponse().getStatusCode());
assertEquals(URI.create(url), this.exchange.getResponse().getHeaders().getLocation());
}
@Test
public void contextRelative() {
String url = "/test.html";
RedirectView view = new RedirectView(url);
view.render(new HashMap<>(), MediaType.TEXT_HTML, createExchange());
assertEquals(URI.create("/context/test.html"), this.response.getHeaders().getLocation());
view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange);
assertEquals(URI.create("/context/test.html"), this.exchange.getResponse().getHeaders().getLocation());
}
@Test
public void contextRelativeQueryParam() {
String url = "/test.html?id=1";
RedirectView view = new RedirectView(url);
view.render(new HashMap<>(), MediaType.TEXT_HTML, createExchange());
assertEquals(URI.create("/context/test.html?id=1"), this.response.getHeaders().getLocation());
view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange);
assertEquals(URI.create("/context/test.html?id=1"), this.exchange.getResponse().getHeaders().getLocation());
}
@Test
@ -115,35 +111,29 @@ public class RedirectViewTests {
String url = "http://url.somewhere.com?foo={foo}";
Map<String, String> model = Collections.singletonMap("foo", "bar");
RedirectView view = new RedirectView(url);
view.render(model, MediaType.TEXT_HTML, createExchange());
assertEquals(URI.create("http://url.somewhere.com?foo=bar"), this.response.getHeaders().getLocation());
view.render(model, MediaType.TEXT_HTML, this.exchange);
assertEquals(URI.create("http://url.somewhere.com?foo=bar"), this.exchange.getResponse().getHeaders().getLocation());
}
@Test
public void expandUriTemplateVariablesFromExchangeAttribute() {
String url = "http://url.somewhere.com?foo={foo}";
Map<String, String> attributes = Collections.singletonMap("foo", "bar");
DefaultServerWebExchange exchange = createExchange();
exchange.getAttributes().put(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, attributes);
this.exchange.getAttributes().put(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, attributes);
RedirectView view = new RedirectView(url);
view.render(new HashMap<>(), MediaType.TEXT_HTML, exchange);
assertEquals(URI.create("http://url.somewhere.com?foo=bar"), this.response.getHeaders().getLocation());
assertEquals(URI.create("http://url.somewhere.com?foo=bar"), this.exchange.getResponse().getHeaders().getLocation());
}
@Test
public void propagateQueryParams() throws Exception {
RedirectView view = new RedirectView("http://url.somewhere.com?foo=bar#bazz");
view.setPropagateQuery(true);
this.request = MockServerHttpRequest.get("http://url.somewhere.com?a=b&c=d").build();
view.render(new HashMap<>(), MediaType.TEXT_HTML, createExchange());
assertEquals(HttpStatus.SEE_OTHER, this.response.getStatusCode());
this.exchange = MockServerHttpRequest.get("http://url.somewhere.com?a=b&c=d").toExchange();
view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange);
assertEquals(HttpStatus.SEE_OTHER, this.exchange.getResponse().getStatusCode());
assertEquals(URI.create("http://url.somewhere.com?foo=bar&a=b&c=d#bazz"),
this.response.getHeaders().getLocation());
}
private DefaultServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, this.response);
this.exchange.getResponse().getHeaders().getLocation());
}
}

View File

@ -24,9 +24,7 @@ import org.junit.Test;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import static org.junit.Assert.assertEquals;
@ -36,7 +34,7 @@ import static org.junit.Assert.assertEquals;
*/
public class RequestContextTests {
private ServerWebExchange exchange;
private final MockServerWebExchange exchange = MockServerHttpRequest.get("/").contextPath("foo/").toExchange();
private GenericApplicationContext applicationContext;
@ -45,9 +43,6 @@ public class RequestContextTests {
@Before
public void init() {
MockServerHttpRequest request = MockServerHttpRequest.get("/").contextPath("foo/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
this.exchange = new DefaultServerWebExchange(request, response);
this.applicationContext = new GenericApplicationContext();
this.applicationContext.refresh();
}

View File

@ -27,7 +27,6 @@ import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@ -43,8 +42,7 @@ import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.core.io.buffer.support.DataBufferTestUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.ui.ConcurrentModel;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
@ -54,7 +52,6 @@ import org.springframework.web.reactive.accept.HeaderContentTypeResolver;
import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
import org.springframework.web.server.NotAcceptableStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
@ -62,6 +59,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.mock.http.server.reactive.test.MockServerHttpRequest.get;
import static org.springframework.web.method.ResolvableMethod.on;
/**
@ -72,17 +70,9 @@ import static org.springframework.web.method.ResolvableMethod.on;
*/
public class ViewResolutionResultHandlerTests {
private MockServerHttpRequest request;
private final BindingContext bindingContext = new BindingContext();
@Before
public void setup() throws Exception {
this.request = MockServerHttpRequest.get("/path").build();
}
@Test
public void supports() throws Exception {
@ -193,18 +183,15 @@ public class ViewResolutionResultHandlerTests {
HandlerResult result = new HandlerResult(new Object(), returnValue, returnType, this.bindingContext);
ViewResolutionResultHandler handler = resultHandler(new TestViewResolver("account"));
this.request = MockServerHttpRequest.get("/account").build();
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = get("/account").toExchange();
handler.handleResult(exchange, result).block(Duration.ofMillis(5000));
assertResponseBody(exchange, "account: {id=123}");
this.request = MockServerHttpRequest.get("/account/").build();
exchange = createExchange();
exchange = get("/account/").toExchange();
handler.handleResult(exchange, result).block(Duration.ofMillis(5000));
assertResponseBody(exchange, "account: {id=123}");
this.request = MockServerHttpRequest.get("/account.123").build();
exchange = createExchange();
exchange = get("/account.123").toExchange();
handler.handleResult(exchange, result).block(Duration.ofMillis(5000));
assertResponseBody(exchange, "account: {id=123}");
}
@ -215,8 +202,7 @@ public class ViewResolutionResultHandlerTests {
MethodParameter returnType = on(TestController.class).resolveReturnType(String.class);
HandlerResult result = new HandlerResult(new Object(), returnValue, returnType, this.bindingContext);
this.request = MockServerHttpRequest.get("/path").build();
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = get("/path").toExchange();
Mono<Void> mono = resultHandler().handleResult(exchange, result);
StepVerifier.create(mono)
@ -231,8 +217,7 @@ public class ViewResolutionResultHandlerTests {
MethodParameter returnType = on(TestController.class).resolveReturnType(TestBean.class);
HandlerResult handlerResult = new HandlerResult(new Object(), value, returnType, this.bindingContext);
this.request = MockServerHttpRequest.get("/account").accept(APPLICATION_JSON).build();
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = get("/account").accept(APPLICATION_JSON).toExchange();
TestView defaultView = new TestView("jsonView", APPLICATION_JSON);
@ -254,8 +239,7 @@ public class ViewResolutionResultHandlerTests {
MethodParameter returnType = on(TestController.class).resolveReturnType(TestBean.class);
HandlerResult handlerResult = new HandlerResult(new Object(), value, returnType, this.bindingContext);
this.request = MockServerHttpRequest.get("/account").accept(APPLICATION_JSON).build();
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = get("/account").accept(APPLICATION_JSON).toExchange();
ViewResolutionResultHandler resultHandler = resultHandler(new TestViewResolver("account"));
Mono<Void> mono = resultHandler.handleResult(exchange, handlerResult);
@ -278,8 +262,7 @@ public class ViewResolutionResultHandlerTests {
HandlerResult result = new HandlerResult(new Object(), null, returnType, this.bindingContext);
ViewResolutionResultHandler handler = resultHandler(new TestViewResolver("account"));
this.request = MockServerHttpRequest.get("/account").build();
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = get("/account").toExchange();
handler.handleResult(exchange, result).block(Duration.ofMillis(5000));
assertResponseBody(exchange, "account: {" +
@ -295,10 +278,6 @@ public class ViewResolutionResultHandlerTests {
}
private ServerWebExchange createExchange() {
return new DefaultServerWebExchange(this.request, new MockServerHttpResponse());
}
private ViewResolutionResultHandler resultHandler(ViewResolver... resolvers) {
return resultHandler(Collections.emptyList(), resolvers);
}
@ -318,16 +297,14 @@ public class ViewResolutionResultHandlerTests {
model.asMap().clear();
model.addAttribute("id", "123");
HandlerResult result = new HandlerResult(new Object(), returnValue, returnType, this.bindingContext);
this.request = MockServerHttpRequest.get(path).build();
ServerWebExchange exchange = createExchange();
MockServerWebExchange exchange = get(path).toExchange();
resultHandler(resolvers).handleResult(exchange, result).block(Duration.ofSeconds(5));
assertResponseBody(exchange, responseBody);
return exchange;
}
private void assertResponseBody(ServerWebExchange exchange, String responseBody) {
MockServerHttpResponse response = (MockServerHttpResponse) exchange.getResponse();
StepVerifier.create(response.getBody())
private void assertResponseBody(MockServerWebExchange exchange, String responseBody) {
StepVerifier.create(exchange.getResponse().getBody())
.consumeNextWith(buf -> assertEquals(responseBody, DataBufferTestUtils.dumpString(buf, UTF_8)))
.expectComplete()
.verify();

View File

@ -31,13 +31,12 @@ import org.springframework.context.ApplicationContextException;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.ModelMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Rossen Stoyanchev
@ -47,9 +46,7 @@ public class FreeMarkerViewTests {
private static final String TEMPLATE_PATH = "classpath*:org/springframework/web/reactive/view/freemarker/";
private ServerWebExchange exchange;
private MockServerHttpResponse response;
private final MockServerWebExchange exchange = MockServerHttpRequest.get("/path").toExchange();
private GenericApplicationContext context;
@ -69,10 +66,6 @@ public class FreeMarkerViewTests {
configurer.setTemplateLoaderPath(TEMPLATE_PATH);
configurer.setResourceLoader(this.context);
this.freeMarkerConfig = configurer.createConfiguration();
MockServerHttpRequest request = MockServerHttpRequest.get("/path").build();
this.response = new MockServerHttpResponse();
this.exchange = new DefaultServerWebExchange(request, this.response);
}
@ -115,7 +108,7 @@ public class FreeMarkerViewTests {
model.addAttribute("hello", "hi FreeMarker");
view.render(model, null, this.exchange).blockMillis(5000);
StepVerifier.create(this.response.getBody())
StepVerifier.create(this.exchange.getResponse().getBody())
.consumeNextWith(buf -> assertEquals("<html><body>hi FreeMarker</body></html>", asString(buf)))
.expectComplete()
.verify();

View File

@ -30,10 +30,7 @@ import org.springframework.context.support.StaticApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.DefaultWebSessionManager;
import org.springframework.web.server.session.WebSessionManager;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import static org.junit.Assert.assertEquals;
@ -64,12 +61,9 @@ public class JRubyScriptTemplateTests {
private MockServerHttpResponse renderViewWithModel(String viewUrl, Map<String, Object> model) throws Exception {
ScriptTemplateView view = createViewWithUrl(viewUrl);
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
WebSessionManager manager = new DefaultWebSessionManager();
ServerWebExchange exchange = new DefaultServerWebExchange(request, response, manager);
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
view.renderInternal(model, MediaType.TEXT_HTML, exchange).block();
return response;
return exchange.getResponse();
}
private ScriptTemplateView createViewWithUrl(String viewUrl) throws Exception {

View File

@ -19,7 +19,6 @@ package org.springframework.web.reactive.result.view.script;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
@ -30,10 +29,9 @@ import org.springframework.context.support.StaticApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.DefaultWebSessionManager;
import org.springframework.web.server.session.WebSessionManager;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for String templates running on Jython.
@ -62,12 +60,9 @@ public class JythonScriptTemplateTests {
private MockServerHttpResponse renderViewWithModel(String viewUrl, Map<String, Object> model) throws Exception {
ScriptTemplateView view = createViewWithUrl(viewUrl);
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
WebSessionManager manager = new DefaultWebSessionManager();
ServerWebExchange exchange = new DefaultServerWebExchange(request, response, manager);
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
view.renderInternal(model, MediaType.TEXT_HTML, exchange).block();
return response;
return exchange.getResponse();
}
private ScriptTemplateView createViewWithUrl(String viewUrl) throws Exception {

View File

@ -20,7 +20,6 @@ import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
@ -32,10 +31,9 @@ import org.springframework.context.support.StaticApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.DefaultWebSessionManager;
import org.springframework.web.server.session.WebSessionManager;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for Kotlin script templates running on Kotlin JSR 223 support
@ -74,12 +72,9 @@ public class KotlinScriptTemplateTests {
private MockServerHttpResponse renderViewWithModel(String viewUrl, Map<String, Object> model, Locale locale, Class<?> configuration) throws Exception {
ScriptTemplateView view = createViewWithUrl(viewUrl, configuration);
view.setLocale(locale);
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
WebSessionManager manager = new DefaultWebSessionManager();
ServerWebExchange exchange = new DefaultServerWebExchange(request, response, manager);
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
view.renderInternal(model, MediaType.TEXT_HTML, exchange).block();
return response;
return exchange.getResponse();
}
private ScriptTemplateView createViewWithUrl(String viewUrl, Class<?> configuration) throws Exception {

View File

@ -19,7 +19,6 @@ package org.springframework.web.reactive.result.view.script;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
@ -30,10 +29,9 @@ import org.springframework.context.support.StaticApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.DefaultWebSessionManager;
import org.springframework.web.server.session.WebSessionManager;
import org.springframework.mock.http.server.reactive.test.MockServerWebExchange;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for pure Javascript templates running on Nashorn engine.
@ -70,12 +68,9 @@ public class NashornScriptTemplateTests {
private MockServerHttpResponse renderViewWithModel(String viewUrl, Map<String, Object> model, Class<?> configuration) throws Exception {
ScriptTemplateView view = createViewWithUrl(viewUrl, configuration);
MockServerHttpRequest request = MockServerHttpRequest.get("/").build();
MockServerHttpResponse response = new MockServerHttpResponse();
WebSessionManager manager = new DefaultWebSessionManager();
ServerWebExchange exchange = new DefaultServerWebExchange(request, response, manager);
MockServerWebExchange exchange = MockServerHttpRequest.get("/").toExchange();
view.renderInternal(model, MediaType.TEXT_HTML, exchange).block();
return response;
return exchange.getResponse();
}
private ScriptTemplateView createViewWithUrl(String viewUrl, Class<?> configuration) throws Exception {

View File

@ -7,13 +7,11 @@ import org.springframework.core.ReactiveAdapterRegistry
import org.springframework.core.annotation.SynthesizingMethodParameter
import org.springframework.format.support.DefaultFormattingConversionService
import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest
import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse
import org.springframework.util.ReflectionUtils
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer
import org.springframework.web.reactive.BindingContext
import org.springframework.web.server.ServerWebInputException
import org.springframework.web.server.adapter.DefaultServerWebExchange
import reactor.test.StepVerifier
/**
@ -24,7 +22,6 @@ import reactor.test.StepVerifier
class RequestParamMethodArgumentResolverKotlinTests {
lateinit var resolver: RequestParamMethodArgumentResolver
lateinit var request: MockServerHttpRequest
lateinit var bindingContext: BindingContext
lateinit var nullableParamRequired: MethodParameter
@ -36,7 +33,6 @@ class RequestParamMethodArgumentResolverKotlinTests {
@Before
fun setup() {
this.resolver = RequestParamMethodArgumentResolver(null, ReactiveAdapterRegistry(), true)
this.request = MockServerHttpRequest.get("/").build()
val initializer = ConfigurableWebBindingInitializer()
initializer.conversionService = DefaultFormattingConversionService()
bindingContext = BindingContext(initializer)
@ -52,58 +48,60 @@ class RequestParamMethodArgumentResolverKotlinTests {
@Test
fun resolveNullableRequiredWithParameter() {
this.request = MockServerHttpRequest.get("/path?name=123").build()
var result = resolver.resolveArgument(nullableParamRequired, bindingContext, createExchange())
var exchange = MockServerHttpRequest.get("/path?name=123").toExchange()
var result = resolver.resolveArgument(nullableParamRequired, bindingContext, exchange)
StepVerifier.create(result).expectNext("123").expectComplete().verify()
}
@Test
fun resolveNullableRequiredWithoutParameter() {
var result = resolver.resolveArgument(nullableParamRequired, bindingContext, createExchange())
var exchange = MockServerHttpRequest.get("/").toExchange()
var result = resolver.resolveArgument(nullableParamRequired, bindingContext, exchange)
StepVerifier.create(result).expectComplete().verify()
}
@Test
fun resolveNullableNotRequiredWithParameter() {
this.request = MockServerHttpRequest.get("/path?name=123").build()
var result = resolver.resolveArgument(nullableParamNotRequired, bindingContext, createExchange())
var exchange = MockServerHttpRequest.get("/path?name=123").toExchange()
var result = resolver.resolveArgument(nullableParamNotRequired, bindingContext, exchange)
StepVerifier.create(result).expectNext("123").expectComplete().verify()
}
@Test
fun resolveNullableNotRequiredWithoutParameter() {
var result = resolver.resolveArgument(nullableParamNotRequired, bindingContext, createExchange())
var exchange = MockServerHttpRequest.get("/").toExchange()
var result = resolver.resolveArgument(nullableParamNotRequired, bindingContext, exchange)
StepVerifier.create(result).expectComplete().verify()
}
@Test
fun resolveNonNullableRequiredWithParameter() {
this.request = MockServerHttpRequest.get("/path?name=123").build()
var result = resolver.resolveArgument(nonNullableParamRequired, bindingContext, createExchange())
var exchange = MockServerHttpRequest.get("/path?name=123").toExchange()
var result = resolver.resolveArgument(nonNullableParamRequired, bindingContext, exchange)
StepVerifier.create(result).expectNext("123").expectComplete().verify()
}
@Test
fun resolveNonNullableRequiredWithoutParameter() {
var result = resolver.resolveArgument(nonNullableParamRequired, bindingContext, createExchange())
var exchange = MockServerHttpRequest.get("/").toExchange()
var result = resolver.resolveArgument(nonNullableParamRequired, bindingContext, exchange)
StepVerifier.create(result).expectError(ServerWebInputException::class.java).verify()
}
@Test
fun resolveNonNullableNotRequiredWithParameter() {
this.request = MockServerHttpRequest.get("/path?name=123").build()
var result = resolver.resolveArgument(nonNullableParamNotRequired, bindingContext, createExchange())
var exchange = MockServerHttpRequest.get("/path?name=123").toExchange()
var result = resolver.resolveArgument(nonNullableParamNotRequired, bindingContext, exchange)
StepVerifier.create(result).expectNext("123").expectComplete().verify()
}
@Test
fun resolveNonNullableNotRequiredWithoutParameter() {
var result = resolver.resolveArgument(nonNullableParamNotRequired, bindingContext, createExchange())
var exchange = MockServerHttpRequest.get("/").toExchange()
var result = resolver.resolveArgument(nonNullableParamNotRequired, bindingContext, exchange)
StepVerifier.create(result).expectComplete().verify()
}
private fun createExchange() = DefaultServerWebExchange(this.request, MockServerHttpResponse())
@Suppress("unused_parameter")
fun handle(