Upgrade samples to match the GraphQlTest updates

See gh-310
This commit is contained in:
rstoyanchev
2022-03-09 12:47:08 +00:00
parent 19793a6e74
commit 4818ee6c81
14 changed files with 125 additions and 175 deletions

View File

@@ -20,6 +20,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation project(':spring-graphql')
testImplementation project(':spring-graphql-test')
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'

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.
@@ -15,27 +15,41 @@
*/
package io.spring.sample.graphql;
import java.net.URI;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureWebGraphQlTester;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.graphql.execution.ErrorType;
import org.springframework.graphql.test.tester.WebGraphQlTester;
import org.springframework.graphql.test.tester.WebSocketGraphQlTester;
import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@SpringBootTest
@AutoConfigureWebGraphQlTester
class SampleApplicationTests {
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class WebFluxSecuritySampleTests {
@LocalServerPort
private int port;
@Autowired
private WebGraphQlTester graphQlTester;
@BeforeEach
public void setUp() {
URI url = URI.create("http://localhost:" + this.port + "/graphql");
this.graphQlTester = WebSocketGraphQlTester.create(url, new ReactorNettyWebSocketClient());
}
@Test
void printError() {
this.graphQlTester.queryName("employeesNamesAndSalaries")
this.graphQlTester.documentName("employeesNamesAndSalaries")
.execute()
.errors()
.satisfy(System.out::println);
@@ -43,7 +57,7 @@ class SampleApplicationTests {
@Test
void anonymousThenUnauthorized() {
this.graphQlTester.queryName("employeesNamesAndSalaries")
this.graphQlTester.documentName("employeesNamesAndSalaries")
.execute()
.errors()
.satisfy(errors -> {
@@ -54,8 +68,12 @@ class SampleApplicationTests {
@Test
void userRoleThenForbidden() {
this.graphQlTester.queryName("employeesNamesAndSalaries")
.httpHeaders(headers -> headers.setBasicAuth("rob", "rob"))
WebGraphQlTester authTester = this.graphQlTester.mutate()
.headers(headers -> headers.setBasicAuth("rob", "rob"))
.build();
authTester.documentName("employeesNamesAndSalaries")
.execute()
.errors()
.satisfy(errors -> {
@@ -66,14 +84,14 @@ class SampleApplicationTests {
@Test
void canQueryName() {
this.graphQlTester.queryName("employeesNames")
this.graphQlTester.documentName("employeesNames")
.execute()
.path("employees[0].name").entity(String.class).isEqualTo("Andi");
}
@Test
void canNotQuerySalary() {
this.graphQlTester.queryName("employeesNamesAndSalaries")
this.graphQlTester.documentName("employeesNamesAndSalaries")
.execute()
.errors()
.satisfy(errors -> {
@@ -84,8 +102,12 @@ class SampleApplicationTests {
@Test
void canQuerySalaryAsAdmin() {
this.graphQlTester.queryName("employeesNamesAndSalaries")
.httpHeaders(headers -> headers.setBasicAuth("admin", "admin"))
WebGraphQlTester authTester = this.graphQlTester.mutate()
.headers(headers -> headers.setBasicAuth("admin", "admin"))
.build();
authTester.documentName("employeesNamesAndSalaries")
.execute()
.path("employees[0].name").entity(String.class).isEqualTo("Andi")
.path("employees[0].salary").entity(int.class).isEqualTo(42);
@@ -94,10 +116,12 @@ class SampleApplicationTests {
@Test
void invalidCredentials() {
assertThatThrownBy(() ->
this.graphQlTester.queryName("employeesNamesAndSalaries")
.httpHeaders(headers -> headers.setBasicAuth("admin", "INVALID"))
this.graphQlTester.mutate()
.headers(headers -> headers.setBasicAuth("admin", "INVALID"))
.build()
.documentName("employeesNamesAndSalaries")
.executeAndVerify())
.hasMessage("Status expected:<200 OK> but was:<401 UNAUTHORIZED>");
.hasMessage("Invalid handshake response getStatus: 401 Unauthorized");
}
}

View File

@@ -19,6 +19,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webflux'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation project(':spring-graphql')
testImplementation project(':spring-graphql-test')
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'

View File

@@ -1,35 +0,0 @@
/*
* Copyright 2002-2021 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 io.spring.sample.graphql;
import reactor.core.publisher.Mono;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
/**
* WebFilter that inserts a key-value pair into the Reactor context which is transferred
* to and accessible in Reactor data fetchers.
*/
public class ContextWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return chain.filter(exchange).contextWrite(context -> context.put("name", "007"));
}
}

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.
@@ -33,24 +33,17 @@ public class DataRepository {
}
public Mono<String> getGreeting() {
return Mono.deferContextual(context -> {
Object name = context.get("name");
return Mono.delay(Duration.ofMillis(50)).map(aLong -> "Hello " + name);
});
return Mono.delay(Duration.ofMillis(50)).map(aLong -> "Hello!");
}
public Flux<String> getGreetings() {
return Mono.delay(Duration.ofMillis(50)).flatMapMany(aLong -> Flux.deferContextual(context -> {
String name = context.get("name");
return Flux.just("Hi", "Bonjour", "Hola", "Ciao", "Zdravo").map(s -> s + " " + name);
}));
return Mono.delay(Duration.ofMillis(50))
.flatMapMany(aLong -> Flux.just("Hi!", "Bonjour!", "Hola!", "Ciao!", "Zdravo!"));
}
public Flux<String> getGreetingsStream() {
return Mono.delay(Duration.ofMillis(50)).flatMapMany(aLong -> Flux.deferContextual(context -> {
String name = context.get("name");
return Flux.just("Hi", "Bonjour", "Hola", "Ciao", "Zdravo").map(s -> s + " " + name);
}));
return Mono.delay(Duration.ofMillis(50))
.flatMapMany(aLong -> Flux.just("Hi!", "Bonjour!", "Hola!", "Ciao!", "Zdravo!"));
}
}

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.
@@ -18,7 +18,6 @@ package io.spring.sample.graphql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SampleApplication {
@@ -27,9 +26,4 @@ public class SampleApplication {
SpringApplication.run(SampleApplication.class, args);
}
@Bean
ContextWebFilter reactorContextWebFilter() {
return new ContextWebFilter();
}
}

View File

@@ -1,37 +0,0 @@
/*
* Copyright 2002-2021 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 io.spring.sample.graphql;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Collaborator and additional components for {@link SampleController} slice tests.
*/
@Configuration
class TestConfig {
@Bean
public ContextWebFilter contextWebFilter() {
return new ContextWebFilter();
}
@Bean
public DataRepository dataRepository() {
return new DataRepository();
}
}

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.
@@ -15,8 +15,6 @@
*/
package io.spring.sample.graphql;
import graphql.GraphQL;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
@@ -24,49 +22,44 @@ import reactor.test.StepVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.graphql.GraphQlTest;
import org.springframework.context.annotation.Import;
import org.springframework.graphql.GraphQlService;
import org.springframework.graphql.test.tester.GraphQlTester;
/**
* GraphQL subscription tests directly via {@link GraphQL}.
* GraphQL over WebSocket subscription tests.
*/
@GraphQlTest(SampleController.class)
@Import(TestConfig.class)
public class SubscriptionTests {
@Import(DataRepository.class)
public class WebFluxWebSocketSampleSubscriptionTests {
@Autowired
private GraphQlTester graphQlTester;
@BeforeEach
public void setUp(@Autowired GraphQlService service) {
this.graphQlTester = GraphQlTester.create(requestInput ->
service.execute(requestInput).contextWrite(context -> context.put("name", "James")));
}
@Test
void subscriptionWithEntityPath() {
Flux<String> result = this.graphQlTester.query("subscription { greetings }")
Flux<String> result = this.graphQlTester.document("subscription { greetings }")
.executeSubscription()
.toFlux("greetings", String.class);
StepVerifier.create(result)
.expectNext("Hi James")
.expectNext("Bonjour James")
.expectNext("Hola James")
.expectNext("Ciao James")
.expectNext("Zdravo James")
.expectNext("Hi!")
.expectNext("Bonjour!")
.expectNext("Hola!")
.expectNext("Ciao!")
.expectNext("Zdravo!")
.verifyComplete();
}
@Test
void subscriptionWithResponseSpec() {
Flux<GraphQlTester.ResponseSpec> result = this.graphQlTester.query("subscription { greetings }")
void subscriptionWithResponse() {
Flux<GraphQlTester.Response> result = this.graphQlTester.document("subscription { greetings }")
.executeSubscription()
.toFlux();
StepVerifier.create(result)
.consumeNextWith(spec -> spec.path("greetings").valueExists())
.consumeNextWith(spec -> spec.path("greetings").matchesJson("\"Bonjour James\""))
.consumeNextWith(spec -> spec.path("greetings").matchesJson("\"Hola James\""))
.consumeNextWith(response -> response.path("greetings").valueExists())
.consumeNextWith(response -> response.path("greetings").matchesJson("\"Bonjour!\""))
.consumeNextWith(response -> response.path("greetings").matchesJson("\"Hola!\""))
.expectNextCount(2)
.verifyComplete();
}

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.
@@ -15,47 +15,40 @@
*/
package io.spring.sample.graphql;
import graphql.GraphQL;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.graphql.GraphQlTest;
import org.springframework.context.annotation.Import;
import org.springframework.graphql.GraphQlService;
import org.springframework.graphql.test.tester.GraphQlTester;
/**
* GraphQL query tests directly via {@link GraphQL}.
* GraphQL over WebSocket single response tests.
*/
@GraphQlTest(SampleController.class)
@Import(TestConfig.class)
public class QueryTests {
@Import(DataRepository.class)
public class WebFluxWebSocketSampleTests {
@Autowired
private GraphQlTester graphQlTester;
@BeforeEach
public void setUp(@Autowired GraphQlService service) {
this.graphQlTester = GraphQlTester.create(requestInput ->
service.execute(requestInput).contextWrite(context -> context.put("name", "James")));
}
@Test
void greetingMono() {
this.graphQlTester.query("{greetingMono}")
this.graphQlTester.document("{greetingMono}")
.execute()
.path("greetingMono")
.entity(String.class)
.isEqualTo("Hello James");
.isEqualTo("Hello!");
}
@Test
void greetingsFlux() {
this.graphQlTester.query("{greetingsFlux}")
this.graphQlTester.document("{greetingsFlux}")
.execute()
.path("greetingsFlux")
.entityList(String.class)
.containsExactly("Hi James", "Bonjour James", "Hola James", "Ciao James", "Zdravo James");
.containsExactly("Hi!", "Bonjour!", "Hola!", "Ciao!", "Zdravo!");
}
}

View File

@@ -20,6 +20,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation project(':spring-graphql')
testImplementation project(':spring-graphql-test')
testImplementation 'org.springframework:spring-webflux'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

View File

@@ -3,7 +3,7 @@ package io.spring.sample.graphql;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureWebGraphQlTester;
import org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureHttpGraphQlTester;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.graphql.execution.ErrorType;
import org.springframework.graphql.test.tester.WebGraphQlTester;
@@ -12,8 +12,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@SpringBootTest
@AutoConfigureWebGraphQlTester
class SampleApplicationTests {
@AutoConfigureHttpGraphQlTester
class WebMvcHttpSecuritySampleTests {
@Autowired
private WebGraphQlTester graphQlTester;
@@ -21,7 +21,7 @@ class SampleApplicationTests {
@Test
void printError() {
this.graphQlTester.queryName("employeesNamesAndSalaries")
this.graphQlTester.documentName("employeesNamesAndSalaries")
.execute()
.errors()
.satisfy(System.out::println);
@@ -29,7 +29,7 @@ class SampleApplicationTests {
@Test
void anonymousThenUnauthorized() {
this.graphQlTester.queryName("employeesNamesAndSalaries")
this.graphQlTester.documentName("employeesNamesAndSalaries")
.execute()
.errors()
.satisfy(errors -> {
@@ -40,8 +40,12 @@ class SampleApplicationTests {
@Test
void userRoleThenForbidden() {
this.graphQlTester.queryName("employeesNamesAndSalaries")
.httpHeaders(headers -> headers.setBasicAuth("rob", "rob"))
WebGraphQlTester tester = this.graphQlTester.mutate()
.headers(headers -> headers.setBasicAuth("rob", "rob"))
.build();
tester.documentName("employeesNamesAndSalaries")
.execute()
.errors()
.satisfy(errors -> {
@@ -51,15 +55,15 @@ class SampleApplicationTests {
}
@Test
void canQueryName() {
this.graphQlTester.queryName("employeesNames")
void candocumentName() {
this.graphQlTester.documentName("employeesNames")
.execute()
.path("employees[0].name").entity(String.class).isEqualTo("Andi");
}
@Test
void canNotQuerySalary() {
this.graphQlTester.queryName("employeesNamesAndSalaries")
this.graphQlTester.documentName("employeesNamesAndSalaries")
.execute()
.errors()
.satisfy(errors -> {
@@ -70,8 +74,12 @@ class SampleApplicationTests {
@Test
void canQuerySalaryAsAdmin() {
this.graphQlTester.queryName("employeesNamesAndSalaries")
.httpHeaders(headers -> headers.setBasicAuth("admin", "admin"))
WebGraphQlTester tester = this.graphQlTester.mutate()
.headers(headers -> headers.setBasicAuth("admin", "admin"))
.build();
tester.documentName("employeesNamesAndSalaries")
.execute()
.path("employees[0].name").entity(String.class).isEqualTo("Andi")
.path("employees[0].salary").entity(int.class).isEqualTo(42);
@@ -80,9 +88,12 @@ class SampleApplicationTests {
@Test
void invalidCredentials() {
assertThatThrownBy(() ->
this.graphQlTester.queryName("employeesNamesAndSalaries")
.httpHeaders(headers -> headers.setBasicAuth("admin", "INVALID"))
this.graphQlTester.mutate()
.headers(headers -> headers.setBasicAuth("admin", "INVALID"))
.build()
.documentName("employeesNamesAndSalaries")
.executeAndVerify())
.hasMessage("Status expected:<200 OK> but was:<401 UNAUTHORIZED>");
}
}
}

View File

@@ -24,6 +24,7 @@ dependencies {
implementation 'com.querydsl:querydsl-jpa'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.h2database:h2'
testImplementation project(':spring-graphql')
testImplementation project(':spring-graphql-test')
testImplementation 'org.springframework:spring-webflux'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

View File

@@ -54,9 +54,14 @@ public class ProjectControllerTests {
@Test
void jsonPath() {
given(this.projectsClient.fetchProject(eq("spring-framework"))).willReturn(this.springFramework);
given(this.projectsClient.fetchProjectReleases(eq("spring-framework"))).willReturn(Collections.singletonList(this.latestRelease));
this.graphQlTester.queryName("projectReleases")
given(this.projectsClient.fetchProject(eq("spring-framework")))
.willReturn(this.springFramework);
given(this.projectsClient.fetchProjectReleases(eq("spring-framework")))
.willReturn(Collections.singletonList(this.latestRelease));
this.graphQlTester.documentName("projectReleases")
.variable("slug", "spring-framework")
.execute()
.path("project.releases[*].version")
@@ -68,7 +73,7 @@ public class ProjectControllerTests {
@Test
void jsonContent() {
given(this.projectsClient.fetchProject(eq("spring-framework"))).willReturn(this.springFramework);
this.graphQlTester.queryName("projectRepositoryUrl")
this.graphQlTester.documentName("projectRepositoryUrl")
.variable("slug", "spring-framework")
.execute()
.path("project")
@@ -77,9 +82,14 @@ public class ProjectControllerTests {
@Test
void decodedResponse() {
given(this.projectsClient.fetchProject(eq("spring-framework"))).willReturn(this.springFramework);
given(this.projectsClient.fetchProjectReleases(eq("spring-framework"))).willReturn(Collections.singletonList(this.latestRelease));
this.graphQlTester.queryName("projectReleases")
given(this.projectsClient.fetchProject(eq("spring-framework")))
.willReturn(this.springFramework);
given(this.projectsClient.fetchProjectReleases(eq("spring-framework")))
.willReturn(Collections.singletonList(this.latestRelease));
this.graphQlTester.documentName("projectReleases")
.variable("slug", "spring-framework")
.execute()
.path("project")

View File

@@ -19,20 +19,20 @@ package io.spring.sample.graphql.repository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureWebGraphQlTester;
import org.springframework.boot.test.autoconfigure.graphql.tester.AutoConfigureGraphQlTester;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.graphql.test.tester.WebGraphQlTester;
import org.springframework.graphql.test.tester.GraphQlTester;
@SpringBootTest
@AutoConfigureWebGraphQlTester
@AutoConfigureGraphQlTester
class ArtifactRepositoriesTests {
@Autowired
private WebGraphQlTester graphQlTester;
private GraphQlTester graphQlTester;
@Test
void querydslRepositorySingle() {
this.graphQlTester.queryName("artifactRepository")
this.graphQlTester.documentName("artifactRepository")
.variable("id", "spring-releases")
.execute()
.path("artifactRepository.name")
@@ -41,7 +41,7 @@ class ArtifactRepositoriesTests {
@Test
void querydslRepositoryMany() {
this.graphQlTester.queryName("artifactRepositories")
this.graphQlTester.documentName("artifactRepositories")
.execute()
.path("artifactRepositories[*].id")
.entityList(String.class).containsExactly("spring-releases", "spring-milestones");