Skip to content

Commit bf9c584

Browse files
committed
Minor refactoring in HTTP handler tests
Change WebFlux handler to actually decode from JSON rather than take an already decoded SerializableGraphQlRequest. See gh-948
1 parent 8eb3cfd commit bf9c584

File tree

2 files changed

+98
-85
lines changed

2 files changed

+98
-85
lines changed

spring-graphql/src/test/java/org/springframework/graphql/server/webflux/GraphQlHttpHandlerTests.java

+48-41
Original file line numberDiff line numberDiff line change
@@ -23,22 +23,24 @@
2323
import com.jayway.jsonpath.DocumentContext;
2424
import com.jayway.jsonpath.JsonPath;
2525
import org.junit.jupiter.api.Test;
26-
import reactor.core.publisher.Mono;
26+
import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper;
27+
import reactor.test.StepVerifier;
2728

28-
import org.springframework.graphql.GraphQlRequest;
2929
import org.springframework.graphql.GraphQlSetup;
3030
import org.springframework.graphql.server.support.SerializableGraphQlRequest;
3131
import org.springframework.http.MediaType;
32+
import org.springframework.http.codec.DecoderHttpMessageReader;
3233
import org.springframework.http.codec.EncoderHttpMessageWriter;
34+
import org.springframework.http.codec.HttpMessageReader;
3335
import org.springframework.http.codec.HttpMessageWriter;
36+
import org.springframework.http.codec.json.Jackson2JsonDecoder;
3437
import org.springframework.http.codec.json.Jackson2JsonEncoder;
3538
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
3639
import org.springframework.mock.http.server.reactive.MockServerHttpResponse;
37-
import org.springframework.mock.web.reactive.function.server.MockServerRequest;
3840
import org.springframework.mock.web.server.MockServerWebExchange;
41+
import org.springframework.web.reactive.function.server.ServerRequest;
3942
import org.springframework.web.reactive.function.server.ServerResponse;
4043
import org.springframework.web.reactive.result.view.ViewResolver;
41-
import org.springframework.web.server.ServerWebExchange;
4244

4345
import static org.assertj.core.api.Assertions.assertThat;
4446

@@ -48,95 +50,100 @@
4850
*/
4951
public class GraphQlHttpHandlerTests {
5052

51-
private final GraphQlHttpHandler greetingHandler = GraphQlSetup.schemaContent("type Query { greeting: String }")
52-
.queryFetcher("greeting", (env) -> "Hello").toHttpHandlerWebFlux();
53+
private static final List<HttpMessageReader<?>> MESSAGE_READERS =
54+
List.of(new DecoderHttpMessageReader<>(new Jackson2JsonDecoder()));
55+
56+
private final GraphQlHttpHandler greetingHandler =
57+
GraphQlSetup.schemaContent("type Query { greeting: String }")
58+
.queryFetcher("greeting", (env) -> "Hello")
59+
.toHttpHandlerWebFlux();
5360

5461

5562
@Test
56-
void shouldProduceApplicationJsonByDefault() {
63+
void shouldProduceApplicationJsonByDefault() throws Exception {
64+
String document = "{greeting}";
5765
MockServerHttpRequest httpRequest = MockServerHttpRequest.post("/")
58-
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.ALL).build();
66+
.contentType(MediaType.APPLICATION_JSON)
67+
.accept(MediaType.ALL)
68+
.body(initRequestBody(document));
5969

60-
String document = "{greeting}";
61-
MockServerHttpResponse httpResponse = handleRequest(
62-
httpRequest, this.greetingHandler, initRequest(document));
70+
MockServerHttpResponse response = handleRequest(httpRequest, this.greetingHandler);
6371

64-
assertThat(httpResponse.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
72+
assertThat(response.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
73+
StepVerifier.create(response.getBodyAsString())
74+
.expectNext("{\"data\":{\"greeting\":\"Hello\"}}")
75+
.verifyComplete();
6576
}
6677

6778
@Test
68-
void shouldProduceApplicationGraphQl() {
79+
void shouldProduceApplicationGraphQl() throws Exception {
6980
MockServerHttpRequest httpRequest = MockServerHttpRequest.post("/")
70-
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_GRAPHQL_RESPONSE).build();
81+
.contentType(MediaType.APPLICATION_JSON)
82+
.accept(MediaType.APPLICATION_GRAPHQL_RESPONSE)
83+
.body(initRequestBody("{greeting}"));
7184

72-
MockServerHttpResponse httpResponse = handleRequest(
73-
httpRequest, this.greetingHandler, initRequest("{greeting}"));
85+
MockServerHttpResponse httpResponse = handleRequest(httpRequest, this.greetingHandler);
7486

7587
assertThat(httpResponse.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_GRAPHQL_RESPONSE);
7688
}
7789

7890
@Test
79-
void shouldProduceApplicationJson() {
91+
void shouldProduceApplicationJson() throws Exception {
8092
MockServerHttpRequest httpRequest = MockServerHttpRequest.post("/")
81-
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).build();
93+
.contentType(MediaType.APPLICATION_JSON)
94+
.accept(MediaType.APPLICATION_JSON)
95+
.body(initRequestBody("{greeting}"));
8296

83-
MockServerHttpResponse httpResponse = handleRequest(
84-
httpRequest, this.greetingHandler, initRequest("{greeting}"));
97+
MockServerHttpResponse httpResponse = handleRequest(httpRequest, this.greetingHandler);
8598

8699
assertThat(httpResponse.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_JSON);
87100
}
88101

89102
@Test
90-
void locale() {
103+
void locale() throws Exception {
91104
GraphQlHttpHandler handler = GraphQlSetup.schemaContent("type Query { greeting: String }")
92105
.queryFetcher("greeting", (env) -> "Hello in " + env.getLocale())
93106
.toHttpHandlerWebFlux();
94107

95108
MockServerHttpRequest httpRequest = MockServerHttpRequest.post("/")
96-
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_GRAPHQL_RESPONSE)
97-
.acceptLanguageAsLocales(Locale.FRENCH).build();
109+
.contentType(MediaType.APPLICATION_JSON)
110+
.accept(MediaType.APPLICATION_GRAPHQL_RESPONSE)
111+
.acceptLanguageAsLocales(Locale.FRENCH)
112+
.body(initRequestBody("{greeting}"));
98113

99-
MockServerHttpResponse httpResponse = handleRequest(
100-
httpRequest, handler, initRequest("{greeting}"));
114+
MockServerHttpResponse httpResponse = handleRequest(httpRequest, handler);
101115

102116
assertThat(httpResponse.getBodyAsString().block())
103117
.isEqualTo("{\"data\":{\"greeting\":\"Hello in fr\"}}");
104118
}
105119

106120
@Test
107-
void shouldSetExecutionId() {
121+
void shouldSetExecutionId() throws Exception {
108122
GraphQlHttpHandler handler = GraphQlSetup.schemaContent("type Query { showId: String }")
109123
.queryFetcher("showId", (env) -> env.getExecutionId().toString())
110124
.toHttpHandlerWebFlux();
111125

112126
MockServerHttpRequest httpRequest = MockServerHttpRequest.post("/")
113-
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_GRAPHQL_RESPONSE).build();
127+
.contentType(MediaType.APPLICATION_JSON)
128+
.accept(MediaType.APPLICATION_GRAPHQL_RESPONSE)
129+
.body(initRequestBody("{showId}"));
114130

115-
MockServerHttpResponse httpResponse = handleRequest(
116-
httpRequest, handler, initRequest("{showId}"));
131+
MockServerHttpResponse httpResponse = handleRequest(httpRequest, handler);
117132

118133
DocumentContext document = JsonPath.parse(httpResponse.getBodyAsString().block());
119134
String id = document.read("data.showId", String.class);
120135
assertThat(id).isEqualTo(httpRequest.getId());
121136
}
122137

123-
private static SerializableGraphQlRequest initRequest(String document) {
138+
private static String initRequestBody(String document) throws Exception {
124139
SerializableGraphQlRequest request = new SerializableGraphQlRequest();
125140
request.setQuery(document);
126-
return request;
141+
return new ObjectMapper().writeValueAsString(request);
127142
}
128143

129-
private MockServerHttpResponse handleRequest(
130-
MockServerHttpRequest httpRequest, GraphQlHttpHandler handler, GraphQlRequest body) {
131-
144+
private MockServerHttpResponse handleRequest(MockServerHttpRequest httpRequest, GraphQlHttpHandler handler) {
132145
MockServerWebExchange exchange = MockServerWebExchange.from(httpRequest);
133-
134-
MockServerRequest serverRequest = MockServerRequest.builder()
135-
.exchange(exchange)
136-
.uri(((ServerWebExchange) exchange).getRequest().getURI())
137-
.method(((ServerWebExchange) exchange).getRequest().getMethod())
138-
.headers(((ServerWebExchange) exchange).getRequest().getHeaders())
139-
.body(Mono.just(body));
146+
ServerRequest serverRequest = ServerRequest.create(exchange, MESSAGE_READERS);
140147

141148
handler.handleRequest(serverRequest)
142149
.flatMap(response -> response.writeTo(exchange, new DefaultContext()))

spring-graphql/src/test/java/org/springframework/graphql/server/webmvc/GraphQlHttpHandlerTests.java

+50-44
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import java.util.Collections;
2222
import java.util.List;
2323
import java.util.Locale;
24+
import java.util.Map;
2425
import java.util.UUID;
2526

2627
import com.jayway.jsonpath.DocumentContext;
@@ -29,9 +30,11 @@
2930
import graphql.execution.preparsed.persisted.InMemoryPersistedQueryCache;
3031
import jakarta.servlet.ServletException;
3132
import org.junit.jupiter.api.Test;
33+
import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper;
3234

3335
import org.springframework.context.i18n.LocaleContextHolder;
3436
import org.springframework.graphql.GraphQlSetup;
37+
import org.springframework.graphql.server.support.SerializableGraphQlRequest;
3538
import org.springframework.http.MediaType;
3639
import org.springframework.http.converter.HttpMessageConverter;
3740
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
@@ -57,23 +60,24 @@ public class GraphQlHttpHandlerTests {
5760
private final GraphQlHttpHandler greetingHandler = GraphQlSetup.schemaContent("type Query { greeting: String }")
5861
.queryFetcher("greeting", (env) -> "Hello").toHttpHandler();
5962

63+
6064
@Test
6165
void shouldProduceApplicationJsonByDefault() throws Exception {
62-
MockHttpServletRequest servletRequest = createServletRequest("{\"query\":\"{ greeting }\"}", "*/*");
63-
MockHttpServletResponse servletResponse = handleRequest(servletRequest, this.greetingHandler);
64-
assertThat(servletResponse.getContentType()).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
66+
MockHttpServletRequest request = createServletRequest("{ greeting }", "*/*");
67+
MockHttpServletResponse response = handleRequest(request, this.greetingHandler);
68+
assertThat(response.getContentType()).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
6569
}
6670

6771
@Test
6872
void shouldProduceApplicationGraphQl() throws Exception {
69-
MockHttpServletRequest servletRequest = createServletRequest("{\"query\":\"{ greeting }\"}", MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE);
70-
MockHttpServletResponse servletResponse = handleRequest(servletRequest, this.greetingHandler);
71-
assertThat(servletResponse.getContentType()).isEqualTo(MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE);
73+
MockHttpServletRequest request = createServletRequest("{ greeting }", MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE);
74+
MockHttpServletResponse response = handleRequest(request, this.greetingHandler);
75+
assertThat(response.getContentType()).isEqualTo(MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE);
7276
}
7377

7478
@Test
7579
void shouldProduceApplicationJson() throws Exception {
76-
MockHttpServletRequest servletRequest = createServletRequest("{\"query\":\"{ greeting }\"}", "application/json");
80+
MockHttpServletRequest servletRequest = createServletRequest("{ greeting }", "application/json");
7781
MockHttpServletResponse servletResponse = handleRequest(servletRequest, this.greetingHandler);
7882
assertThat(servletResponse.getContentType()).isEqualTo("application/json");
7983
}
@@ -83,14 +87,15 @@ void locale() throws Exception {
8387
GraphQlHttpHandler handler = GraphQlSetup.schemaContent("type Query { greeting: String }")
8488
.queryFetcher("greeting", (env) -> "Hello in " + env.getLocale())
8589
.toHttpHandler();
86-
MockHttpServletRequest servletRequest = createServletRequest("{\"query\":\"{ greeting }\"}", MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE);
90+
91+
MockHttpServletRequest request = createServletRequest(
92+
"{ greeting }", MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE);
93+
8794
LocaleContextHolder.setLocale(Locale.FRENCH);
8895

8996
try {
90-
MockHttpServletResponse servletResponse = handleRequest(servletRequest, handler);
91-
92-
assertThat(servletResponse.getContentAsString())
93-
.isEqualTo("{\"data\":{\"greeting\":\"Hello in fr\"}}");
97+
MockHttpServletResponse response = handleRequest(request, handler);
98+
assertThat(response.getContentAsString()).isEqualTo("{\"data\":{\"greeting\":\"Hello in fr\"}}");
9499
}
95100
finally {
96101
LocaleContextHolder.resetLocaleContext();
@@ -103,10 +108,12 @@ void shouldSetExecutionId() throws Exception {
103108
.queryFetcher("showId", (env) -> env.getExecutionId().toString())
104109
.toHttpHandler();
105110

106-
MockHttpServletRequest servletRequest = createServletRequest("{\"query\":\"{ showId }\"}", MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE);
111+
MockHttpServletRequest request = createServletRequest(
112+
"{ showId }", MediaType.APPLICATION_GRAPHQL_RESPONSE_VALUE);
113+
114+
MockHttpServletResponse response = handleRequest(request, handler);
107115

108-
MockHttpServletResponse servletResponse = handleRequest(servletRequest, handler);
109-
DocumentContext document = JsonPath.parse(servletResponse.getContentAsString());
116+
DocumentContext document = JsonPath.parse(response.getContentAsString());
110117
String id = document.read("data.showId", String.class);
111118
assertThatNoException().isThrownBy(() -> UUID.fromString(id));
112119
}
@@ -121,44 +128,44 @@ void persistedQuery() throws Exception {
121128
.configureGraphQl(builder -> builder.preparsedDocumentProvider(documentProvider))
122129
.toHttpHandler();
123130

124-
String document = """
125-
{
126-
"query" : "{__typename}",
127-
"extensions": {
128-
"persistedQuery": {
129-
"version":1,
130-
"sha256Hash":"ecf4edb46db40b5132295c0291d62fb65d6759a9eedfa4d5d612dd5ec54a6b38"
131-
}
132-
}
133-
}""";
134-
135-
MockHttpServletResponse servletResponse = handleRequest(createServletRequest(document, "*/*"), handler);
136-
assertThat(servletResponse.getContentAsString()).isEqualTo("{\"data\":{\"__typename\":\"Query\"}}");
137-
138-
document = """
139-
{
140-
"extensions":{
141-
"persistedQuery":{
142-
"version":1,
143-
"sha256Hash":"ecf4edb46db40b5132295c0291d62fb65d6759a9eedfa4d5d612dd5ec54a6b38"
144-
}
145-
}
146-
}""";
147-
148-
servletResponse = handleRequest(createServletRequest(document, "*/*"), handler);
149-
assertThat(servletResponse.getContentAsString()).isEqualTo("{\"data\":{\"__typename\":\"Query\"}}");
131+
SerializableGraphQlRequest request = new SerializableGraphQlRequest();
132+
request.setQuery("{__typename}");
133+
request.setExtensions(Map.of("persistedQuery", Map.of(
134+
"version", "1",
135+
"sha256Hash", "ecf4edb46db40b5132295c0291d62fb65d6759a9eedfa4d5d612dd5ec54a6b38")));
136+
137+
MockHttpServletResponse response = handleRequest(createServletRequest(request, "*/*"), handler);
138+
assertThat(response.getContentAsString()).isEqualTo("{\"data\":{\"__typename\":\"Query\"}}");
139+
140+
request = new SerializableGraphQlRequest();
141+
request.setQuery("{__typename}");
142+
request.setExtensions(Map.of("persistedQuery", Map.of(
143+
"version", "1",
144+
"sha256Hash", "ecf4edb46db40b5132295c0291d62fb65d6759a9eedfa4d5d612dd5ec54a6b38")));
145+
146+
response = handleRequest(createServletRequest(request, "*/*"), handler);
147+
assertThat(response.getContentAsString()).isEqualTo("{\"data\":{\"__typename\":\"Query\"}}");
150148
}
151149

150+
private MockHttpServletRequest createServletRequest(String document, String accept) throws Exception {
151+
SerializableGraphQlRequest request = new SerializableGraphQlRequest();
152+
request.setQuery(document);
153+
return createServletRequest(request, accept);
154+
}
152155

153-
private MockHttpServletRequest createServletRequest(String query, String accept) {
156+
private MockHttpServletRequest createServletRequest(SerializableGraphQlRequest request, String accept) throws Exception {
154157
MockHttpServletRequest servletRequest = new MockHttpServletRequest("POST", "/");
155158
servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);
156-
servletRequest.setContent(query.getBytes(StandardCharsets.UTF_8));
159+
servletRequest.setContent(initRequestBody(request));
157160
servletRequest.addHeader("Accept", accept);
158161
servletRequest.setAsyncSupported(true);
159162
return servletRequest;
160163
}
161164

165+
private static byte[] initRequestBody(SerializableGraphQlRequest request) throws Exception {
166+
return new ObjectMapper().writeValueAsString(request).getBytes(StandardCharsets.UTF_8);
167+
}
168+
162169
private MockHttpServletResponse handleRequest(
163170
MockHttpServletRequest servletRequest, GraphQlHttpHandler handler) throws ServletException, IOException {
164171

@@ -180,7 +187,6 @@ private static class DefaultContext implements ServerResponse.Context {
180187
public List<HttpMessageConverter<?>> messageConverters() {
181188
return MESSAGE_READERS;
182189
}
183-
184190
}
185191

186192
}

0 commit comments

Comments
 (0)