Simplify creation of RequestInput in tests

Introduce a TestRequestInput subclass to make the creation of
RequestInput in tests convenient.

See gh-310
This commit is contained in:
rstoyanchev
2022-03-01 14:13:51 +00:00
parent b49c63f376
commit 087202d9cb
22 changed files with 97 additions and 62 deletions

View File

@@ -70,7 +70,7 @@ class GraphQlTesterRequestSpecSupport {
}
protected RequestInput createRequestInput() {
return new RequestInput(this.query, this.operationName, this.variables, this.locale, idGenerator.generateId().toString());
return new RequestInput(this.query, this.operationName, this.variables, idGenerator.generateId().toString(), this.locale);
}
}

View File

@@ -44,33 +44,33 @@ import org.springframework.util.Assert;
*/
public class RequestInput extends GraphQlRequest {
@Nullable
private final Locale locale;
private final String id;
private final List<BiFunction<ExecutionInput, ExecutionInput.Builder, ExecutionInput>> executionInputConfigurers = new ArrayList<>();
@Nullable
private ExecutionId executionId;
@Nullable
private final Locale locale;
private final List<BiFunction<ExecutionInput, ExecutionInput.Builder, ExecutionInput>> executionInputConfigurers = new ArrayList<>();
/**
* Create an instance.
* @param document textual representation of the operation(s)
* @param operationName optionally, the name of the operation to execute
* @param variables variables by which the query is parameterized
* @param locale the locale associated with the request
* @param id the request id, to be used as the {@link ExecutionId}
* @param locale the locale associated with the request
*/
public RequestInput(
String document, @Nullable String operationName, @Nullable Map<String, Object> variables,
@Nullable Locale locale, String id) {
String id, @Nullable Locale locale) {
super(document, operationName, variables);
Assert.notNull(id, "'id' is required");
this.locale = locale;
this.id = id;
this.locale = locale;
}

View File

@@ -49,13 +49,12 @@ public class WebInput extends RequestInput {
* @param uri the URL for the HTTP request or WebSocket handshake
* @param headers the HTTP request headers
* @param body the deserialized content of the GraphQL request
* @param locale the locale from the HTTP request, if any
* @param id an identifier for the GraphQL request, e.g. a subscription id for
* correlating request and response messages, or it could be an id associated with the
* underlying request/connection id, if available
* correlating request and response messages, or it could be an id associated with the
* @param locale the locale from the HTTP request, if any
*/
public WebInput(URI uri, HttpHeaders headers, Map<String, Object> body, @Nullable Locale locale, String id) {
super(getKey("query", body), getKey("operationName", body), getKey("variables", body), locale, id);
public WebInput(URI uri, HttpHeaders headers, Map<String, Object> body, String id, @Nullable Locale locale) {
super(getKey("query", body), getKey("operationName", body), getKey("variables", body), id, locale);
Assert.notNull(uri, "URI is required'");
Assert.notNull(headers, "HttpHeaders is required'");
this.uri = UriComponentsBuilder.fromUri(uri).build(true);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2020-2021 the original author or authors.
* Copyright 2020-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -65,8 +65,8 @@ public class GraphQlHttpHandler {
.flatMap((body) -> {
WebInput input = new WebInput(
request.uri(), request.headers().asHttpHeaders(), body,
request.exchange().getLocaleContext().getLocale(),
request.exchange().getRequest().getId());
request.exchange().getRequest().getId(),
request.exchange().getLocaleContext().getLocale());
if (logger.isDebugEnabled()) {
logger.debug("Executing: " + input);
}

View File

@@ -25,8 +25,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import graphql.ExecutionResult;
import graphql.GraphQLError;
import graphql.GraphqlErrorBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.reactivestreams.Publisher;
@@ -125,7 +123,7 @@ public class GraphQlWebSocketHandler implements WebSocketHandler {
return GraphQlStatus.close(session, GraphQlStatus.INVALID_MESSAGE_STATUS);
}
WebInput input = new WebInput(
handshakeInfo.getUri(), handshakeInfo.getHeaders(), payload, null, id);
handshakeInfo.getUri(), handshakeInfo.getHeaders(), payload, id, null);
if (logger.isDebugEnabled()) {
logger.debug("Executing: " + input);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2020-2021 the original author or authors.
* Copyright 2020-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -76,7 +76,7 @@ public class GraphQlHttpHandler {
WebInput input = new WebInput(
request.uri(), request.headers().asHttpHeaders(), readBody(request),
LocaleContextHolder.getLocale(), this.idGenerator.generateId().toString());
this.idGenerator.generateId().toString(), LocaleContextHolder.getLocale());
if (logger.isDebugEnabled()) {
logger.debug("Executing: " + input);

View File

@@ -150,7 +150,7 @@ public class GraphQlWebSocketHandler extends TextWebSocketHandler implements Sub
URI uri = session.getUri();
Assert.notNull(uri, "Expected handshake url");
HttpHeaders headers = session.getHandshakeHeaders();
WebInput input = new WebInput(uri, headers, payload, null, id);
WebInput input = new WebInput(uri, headers, payload, id, null);
if (logger.isDebugEnabled()) {
logger.debug("Executing: " + input);
}

View File

@@ -28,7 +28,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
class RequestInputTests {
private final RequestInput requestInput = new RequestInput("greeting", "Greeting", null, null, "id");
private final RequestInput requestInput = new RequestInput("greeting", "Greeting", null, "id", null);
@Test

View File

@@ -34,7 +34,6 @@ import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.graphql.GraphQlRequest;
import org.springframework.graphql.RequestInput;
import org.springframework.graphql.web.webflux.GraphQlWebSocketMessage;
import org.springframework.http.HttpHeaders;
import org.springframework.web.reactive.socket.CloseStatus;

View File

@@ -29,8 +29,8 @@ import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.graphql.GraphQlResponse;
import org.springframework.graphql.RequestInput;
import org.springframework.graphql.RequestOutput;
import org.springframework.graphql.TestRequestInput;
import org.springframework.graphql.data.method.annotation.BatchMapping;
import org.springframework.stereotype.Controller;
@@ -71,7 +71,7 @@ public class BatchMappingInvocationTests extends BatchMappingTestSupport {
"}";
Mono<RequestOutput> resultMono = createGraphQlService(controller)
.execute(new RequestInput(query, null, null, null, "1"));
.execute(new TestRequestInput(query));
List<Course> actualCourses = GraphQlResponse.from(resultMono).toList("courses", Course.class);
List<Course> courses = Course.allCourses();
@@ -104,7 +104,7 @@ public class BatchMappingInvocationTests extends BatchMappingTestSupport {
"}";
Mono<RequestOutput> resultMono = createGraphQlService(controller)
.execute(new RequestInput(query, null, null, null, "1"));
.execute(new TestRequestInput(query));
List<Course> actualCourses = GraphQlResponse.from(resultMono).toList("courses", Course.class);
List<Course> courses = Course.allCourses();

View File

@@ -31,8 +31,8 @@ import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import org.springframework.graphql.GraphQlResponse;
import org.springframework.graphql.RequestInput;
import org.springframework.graphql.RequestOutput;
import org.springframework.graphql.TestRequestInput;
import org.springframework.graphql.data.method.annotation.BatchMapping;
import org.springframework.graphql.execution.ReactorContextManager;
import org.springframework.graphql.execution.SecurityContextThreadLocalAccessor;
@@ -95,7 +95,7 @@ public class BatchMappingPrincipalMethodArgumentResolverTests extends BatchMappi
Mono<RequestOutput> resultMono = Mono.delay(Duration.ofMillis(10))
.flatMap(aLong -> {
String query = "{ courses { id instructor { id } } }";
return createGraphQlService(controller).execute(new RequestInput(query, null, null, null, "1"));
return createGraphQlService(controller).execute(new TestRequestInput(query));
})
.contextWrite(contextWriter);

View File

@@ -38,6 +38,7 @@ import org.springframework.graphql.GraphQlService;
import org.springframework.graphql.GraphQlSetup;
import org.springframework.graphql.RequestInput;
import org.springframework.graphql.RequestOutput;
import org.springframework.graphql.TestRequestInput;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.MutationMapping;
import org.springframework.graphql.data.method.annotation.QueryMapping;
@@ -59,7 +60,7 @@ public class SchemaMappingInvocationTests {
@Test
void queryWithScalarArgument() {
String query = "{ " +
String document = "{ " +
" bookById(id:\"1\") { " +
" id" +
" name" +
@@ -70,7 +71,7 @@ public class SchemaMappingInvocationTests {
" }" +
"}";
Mono<RequestOutput> resultMono = graphQlService().execute(new RequestInput(query, null, null, null, "1"));
Mono<RequestOutput> resultMono = graphQlService().execute(new TestRequestInput(document));
Book book = GraphQlResponse.from(resultMono).toEntity("bookById", Book.class);
assertThat(book.getId()).isEqualTo(1);
@@ -83,14 +84,14 @@ public class SchemaMappingInvocationTests {
@Test
void queryWithObjectArgument() {
String query = "{ " +
String document = "{ " +
" booksByCriteria(criteria: {author:\"Orwell\"}) { " +
" id" +
" name" +
" }" +
"}";
Mono<RequestOutput> resultMono = graphQlService().execute(new RequestInput(query, null, null, null, "1"));
Mono<RequestOutput> resultMono = graphQlService().execute(new TestRequestInput(document));
List<Book> bookList = GraphQlResponse.from(resultMono).toList("booksByCriteria", Book.class);
assertThat(bookList).hasSize(2);
@@ -100,14 +101,14 @@ public class SchemaMappingInvocationTests {
@Test
void queryWithProjectionOnArgumentsMap() {
String query = "{ " +
String document = "{ " +
" booksByProjectedArguments(author:\"Orwell\") { " +
" id" +
" name" +
" }" +
"}";
Mono<RequestOutput> resultMono = graphQlService().execute(new RequestInput(query, null, null, null, "1"));
Mono<RequestOutput> resultMono = graphQlService().execute(new TestRequestInput(document));
List<Book> bookList = GraphQlResponse.from(resultMono).toList("booksByProjectedArguments", Book.class);
assertThat(bookList).hasSize(2);
@@ -117,14 +118,14 @@ public class SchemaMappingInvocationTests {
@Test
void queryWithProjectionOnNamedArgument() {
String query = "{ " +
String document = "{ " +
" booksByProjectedCriteria(criteria: {author:\"Orwell\"}) { " +
" id" +
" name" +
" }" +
"}";
Mono<RequestOutput> resultMono = graphQlService().execute(new RequestInput(query, null, null, null, "1"));
Mono<RequestOutput> resultMono = graphQlService().execute(new TestRequestInput(document));
List<Book> bookList = GraphQlResponse.from(resultMono).toList("booksByProjectedCriteria", Book.class);
assertThat(bookList).hasSize(2);
@@ -134,7 +135,7 @@ public class SchemaMappingInvocationTests {
@Test
void queryWithArgumentViaDataFetchingEnvironment() {
String query = "{ " +
String document = "{ " +
" authorById(id:\"101\") { " +
" id" +
" firstName" +
@@ -143,7 +144,7 @@ public class SchemaMappingInvocationTests {
"}";
AtomicReference<GraphQLContext> contextRef = new AtomicReference<>();
RequestInput requestInput = new RequestInput(query, null, null, null, "1");
RequestInput requestInput = new TestRequestInput(document);
requestInput.configureExecutionInput((executionInput, builder) -> {
contextRef.set(executionInput.getGraphQLContext());
return executionInput;
@@ -161,7 +162,7 @@ public class SchemaMappingInvocationTests {
@Test
void mutation() {
String operation = "mutation { " +
String document = "mutation { " +
" addAuthor(firstName:\"James\", lastName:\"Joyce\") { " +
" id" +
" firstName" +
@@ -169,8 +170,7 @@ public class SchemaMappingInvocationTests {
" }" +
"}";
Mono<RequestOutput> resultMono = graphQlService()
.execute(new RequestInput(operation, null, null, null, "1"));
Mono<RequestOutput> resultMono = graphQlService().execute(new TestRequestInput(document));
Author author = GraphQlResponse.from(resultMono).toEntity("addAuthor", Author.class);
assertThat(author.getId()).isEqualTo(99);
@@ -180,15 +180,14 @@ public class SchemaMappingInvocationTests {
@Test
void subscription() {
String operation = "subscription { " +
String document = "subscription { " +
" bookSearch(author:\"Orwell\") { " +
" id" +
" name" +
" }" +
"}";
Mono<RequestOutput> resultMono = graphQlService()
.execute(new RequestInput(operation, null, null, null, "1"));
Mono<RequestOutput> resultMono = graphQlService().execute(new TestRequestInput(document));
Flux<Book> bookFlux = GraphQlResponse.forSubscription(resultMono)
.map(response -> response.toEntity("bookSearch", Book.class));

View File

@@ -33,8 +33,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.core.MethodParameter;
import org.springframework.graphql.GraphQlResponse;
import org.springframework.graphql.GraphQlSetup;
import org.springframework.graphql.RequestInput;
import org.springframework.graphql.RequestOutput;
import org.springframework.graphql.TestRequestInput;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SubscriptionMapping;
import org.springframework.graphql.execution.ExecutionGraphQlService;
@@ -162,7 +162,7 @@ public class SchemaMappingPrincipalMethodArgumentResolverTests {
.toGraphQlService();
return Mono.delay(Duration.ofMillis(10))
.flatMap(aLong -> graphQlService.execute(new RequestInput(op, null, null, null, "1")))
.flatMap(aLong -> graphQlService.execute(new TestRequestInput(op)))
.contextWrite(contextWriter);
}

View File

@@ -288,7 +288,7 @@ class QuerydslDataFetcherTests {
}
private WebInput input(String query) {
return new WebInput(URI.create("/"), new HttpHeaders(), Collections.singletonMap("query", query), null, "1");
return new WebInput(URI.create("/"), new HttpHeaders(), Collections.singletonMap("query", query), "1", null);
}

View File

@@ -187,7 +187,7 @@ class QueryByExampleDataFetcherJpaTests {
}
private WebInput input(String query) {
return new WebInput(URI.create("/"), new HttpHeaders(), Collections.singletonMap("query", query), null, "1");
return new WebInput(URI.create("/"), new HttpHeaders(), Collections.singletonMap("query", query), "1", null);
}

View File

@@ -185,7 +185,7 @@ class QueryByExampleDataFetcherMongoDbTests {
}
private WebInput input(String query) {
return new WebInput(URI.create("/"), new HttpHeaders(), Collections.singletonMap("query", query), null, "1");
return new WebInput(URI.create("/"), new HttpHeaders(), Collections.singletonMap("query", query), "1", null);
}

View File

@@ -157,7 +157,7 @@ class QueryByExampleDataFetcherReactiveMongoDbTests {
}
private WebInput input(String query) {
return new WebInput(URI.create("/"), new HttpHeaders(), Collections.singletonMap("query", query), null, "1");
return new WebInput(URI.create("/"), new HttpHeaders(), Collections.singletonMap("query", query), "1", null);
}

View File

@@ -30,8 +30,8 @@ import org.springframework.graphql.BookSource;
import org.springframework.graphql.GraphQlResponse;
import org.springframework.graphql.GraphQlService;
import org.springframework.graphql.GraphQlSetup;
import org.springframework.graphql.RequestInput;
import org.springframework.graphql.RequestOutput;
import org.springframework.graphql.TestRequestInput;
import static org.assertj.core.api.Assertions.assertThat;
@@ -76,7 +76,7 @@ public class BatchLoadingTests {
.dataLoaders(this.registry)
.toGraphQlService();
Mono<RequestOutput> resultMono = service.execute(new RequestInput(query, null, null, null, "1"));
Mono<RequestOutput> resultMono = service.execute(new TestRequestInput(query));
List<Book> books = GraphQlResponse.from(resultMono).toList("booksByCriteria", Book.class);
assertThat(books).hasSize(2);

View File

@@ -24,8 +24,8 @@ import reactor.core.publisher.Mono;
import org.springframework.graphql.GraphQlResponse;
import org.springframework.graphql.GraphQlSetup;
import org.springframework.graphql.RequestInput;
import org.springframework.graphql.RequestOutput;
import org.springframework.graphql.TestRequestInput;
import static org.assertj.core.api.Assertions.assertThat;
@@ -85,7 +85,7 @@ public class ClassNameTypeResolverTests {
Mono<RequestOutput> resultMono = graphQlSetup.queryFetcher("animals", env -> animalList)
.toGraphQlService()
.execute(new RequestInput(query, null, null, null, "1"));
.execute(new TestRequestInput(query));
GraphQlResponse response = GraphQlResponse.from(resultMono);
for (int i = 0; i < animalList.size(); i++) {
@@ -128,7 +128,7 @@ public class ClassNameTypeResolverTests {
Mono<RequestOutput> result = graphQlSetup.queryFetcher("sightings", env -> animalAndPlantList)
.typeResolver(typeResolver)
.toGraphQlService()
.execute(new RequestInput(query, null, null, null, "1"));
.execute(new TestRequestInput(query));
GraphQlResponse response = GraphQlResponse.from(result);
for (int i = 0; i < animalAndPlantList.size(); i++) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,7 +41,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class WebGraphQlHandlerTests {
private static final WebInput webInput = new WebInput(
URI.create("https://abc.org"), new HttpHeaders(), Collections.singletonMap("query", "{ greeting }"), null, "1");
URI.create("https://abc.org"), new HttpHeaders(), Collections.singletonMap("query", "{ greeting }"), "1", null);
private final GraphQlSetup graphQlSetup = GraphQlSetup.schemaContent("type Query { greeting: String }");

View File

@@ -20,7 +20,6 @@ import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import graphql.ExecutionInput;
import graphql.ExecutionResultImpl;
@@ -40,8 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class WebInterceptorTests {
private static final WebInput webInput = new WebInput(
URI.create("http://abc.org"), new HttpHeaders(), Collections.singletonMap("query", "{ notUsed }"),
null, "1");
URI.create("http://abc.org"), new HttpHeaders(), Collections.singletonMap("query", "{ notUsed }"), "1", null);
@Test
void interceptorOrder() {

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.graphql;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/**
* {@link RequestInput} for use in tests with a convenient single-arg constructor
* and simple incrementing id generation.
*
* @author Rossen Stoyanchev
*/
public class TestRequestInput extends RequestInput {
private static final AtomicLong idIndex = new AtomicLong();
public TestRequestInput(String document) {
super(document, null, null, String.valueOf(idIndex.incrementAndGet()), null);
}
public TestRequestInput(String doc, String operationName, Map<String, Object> vars, Locale locale, String id) {
super(doc, operationName, vars, id, locale);
}
}