From bd5b6ae53a58233485010e8b20d9d935bb98ac59 Mon Sep 17 00:00:00 2001 From: Michiel Oliemans Date: Sun, 20 Dec 2020 13:53:30 +0100 Subject: [PATCH] Fix code style formatting according to spec --- .github/ISSUE_TEMPLATE/bug_report.md | 15 +- .github/ISSUE_TEMPLATE/feature_request.md | 7 +- .github/workflows/pull-request.yml | 6 +- .github/workflows/release.yml | 2 +- LICENSE.md | 15 +- README.md | 310 +++++---- altair-spring-boot-starter/LICENSE.md | 15 +- build.gradle | 2 +- .../boot/SubscriptionSampleApplication.java | 6 +- .../StockTickerReactorPublisher.java | 55 +- .../publishers/StockTickerRxPublisher.java | 56 +- .../spring/web/boot/resolvers/Query.java | 6 +- .../web/boot/resolvers/StockPriceUpdate.java | 55 +- .../web/boot/resolvers/Subscription.java | 17 +- .../src/main/resources/public/index.html | 275 ++++---- example-graphql-tools/LICENSE.md | 15 +- .../java/com/graphql/sample/boot/Comment.java | 4 +- .../boot/GraphQLToolsSampleApplication.java | 6 +- .../com/graphql/sample/boot/Mutation.java | 3 +- .../java/com/graphql/sample/boot/Post.java | 28 +- .../com/graphql/sample/boot/PostResolver.java | 9 +- .../java/com/graphql/sample/boot/Query.java | 6 +- .../graphql/sample/boot/GraphQLServletTest.kt | 18 +- .../GraphQLToolsSampleApplicationTest.java | 80 +-- ...ringBootTestWithoutWebEnvironmentTest.java | 6 +- example-spring-common/LICENSE.md | 15 +- example-spring-common/build.gradle | 2 +- .../sample/ApplicationBootConfiguration.java | 6 +- .../web/boot/sample/SimpleListConnection.java | 170 ++--- .../boot/sample/TodoSimpleListConnection.java | 25 +- .../web/boot/sample/schema/TodoSchema.java | 30 +- .../schema/objecttype/BaseObjectType.java | 18 +- .../schema/objecttype/RootObjectType.java | 32 +- .../schema/objecttype/TodoObjectType.java | 44 +- .../schema/objecttype/UserObjectType.java | 38 +- .../src/main/resources/application.yml | 22 +- example-webflux/LICENSE.md | 15 +- .../ApplicationWebfluxConfiguration.java | 32 +- example/LICENSE.md | 15 +- example/build.gradle | 2 +- .../sample/ApplicationBootConfiguration.java | 32 +- gradle.properties | 45 +- gradlew | 207 +++--- graphql-spring-boot-starter/LICENSE.md | 15 +- .../spring/boot/test/GraphQLResponse.java | 254 ++++---- .../boot/test/GraphQLTestSubscription.java | 8 +- .../spring/boot/test/GraphQLTestTemplate.java | 611 +++++++++--------- .../test/JacksonFriendlySourceLocation.java | 16 +- .../spring/boot/test/RequestFactory.java | 28 +- .../spring/boot/test/SubscriptionState.java | 21 +- .../graphql/spring/boot/test/TestUtils.java | 18 +- .../assertions/GraphQLBigDecimalAssert.java | 21 +- .../assertions/GraphQLBigIntegerAssert.java | 21 +- .../test/assertions/GraphQLBooleanAssert.java | 18 +- .../test/assertions/GraphQLByteAssert.java | 18 +- .../assertions/GraphQLErrorListAssertion.java | 86 +-- .../test/assertions/GraphQLFieldAssert.java | 433 +++++++------ .../GraphQLGenericObjectAssert.java | 18 +- .../test/assertions/GraphQLIntegerAssert.java | 19 +- .../test/assertions/GraphQLListAssert.java | 23 +- .../test/assertions/GraphQLLongAssert.java | 18 +- .../assertions/GraphQLResponseAssertion.java | 14 +- .../test/assertions/GraphQLShortAssert.java | 20 +- .../test/assertions/GraphQLStringAssert.java | 18 +- .../assertions/NumberOfErrorsAssertion.java | 55 +- .../helper/GraphQLTestConstantsHelper.java | 10 +- .../boot/test/GraphQLAssertIsNotNullTest.java | 79 +-- .../GraphQLAssertIsNotPresentOrNullTest.java | 75 +-- .../GraphQLFieldAssertAsBigDecimalTest.java | 122 ++-- .../GraphQLFieldAssertAsBigIntegerTest.java | 122 ++-- .../test/GraphQLFieldAssertAsBooleanTest.java | 119 ++-- .../test/GraphQLFieldAssertAsByteTest.java | 121 ++-- .../test/GraphQLFieldAssertAsIntegerTest.java | 119 ++-- .../GraphQLFieldAssertAsJavaListTypeTest.java | 128 ++-- .../GraphQLFieldAssertAsJavaTypeTest.java | 123 ++-- .../test/GraphQLFieldAssertAsListTest.java | 125 ++-- .../test/GraphQLFieldAssertAsLongTest.java | 121 ++-- .../test/GraphQLFieldAssertAsShortTest.java | 119 ++-- .../test/GraphQLFieldAssertAsStringTest.java | 119 ++-- .../boot/test/GraphQLFieldAssertAsTest.java | 121 ++-- .../GraphQLFieldAssertIsNotPresentTest.java | 65 +- .../test/GraphQLFieldAssertIsNullTest.java | 79 +-- .../boot/test/GraphQLFieldAssertTestBase.java | 19 +- .../spring/boot/test/GraphQLResponseTest.java | 480 +++++++------- ...phQLSubscriptionTestAwaitNoAnswerTest.java | 88 +-- ...stSubscriptionAwaitAndGetResponseTest.java | 225 +++---- .../GraphQLTestSubscriptionErrorTest.java | 22 +- ...SubscriptionGetRemainingResponsesTest.java | 50 +- .../GraphQLTestSubscriptionResetTest.java | 138 ++-- .../test/GraphQLTestSubscriptionTestBase.java | 87 +-- ...estSubscriptionUsageErrorHandlingTest.java | 98 +-- .../GraphQLTestTemplateIntegrationTest.java | 332 +++++----- .../boot/test/GraphQLTestTemplateTest.java | 347 +++++----- .../spring/boot/test/TestApplication.java | 6 +- .../spring/boot/test/beans/DummyQuery.java | 55 +- .../spring/boot/test/beans/FooBar.java | 5 +- .../boot/test/beans/SubscriptionListener.java | 26 +- .../boot/test/beans/TestSubscriptions.java | 37 +- .../resources/response-with-nested-list.json | 27 +- voyager-spring-boot-starter/LICENSE.md | 15 +- 100 files changed, 3810 insertions(+), 3534 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index d1ba2bc0..9d023782 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,9 +1,6 @@ --- -name: Bug report -about: Create a report to help us improve -title: '' -labels: bug -assignees: '' +name: Bug report about: Create a report to help us improve title: '' +labels: bug assignees: '' --- @@ -12,6 +9,7 @@ A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: + 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' @@ -24,9 +22,10 @@ A clear and concise description of what you expected to happen. If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - - OS: [e.g. iOS] - - Browser [e.g. chrome, safari] - - Version [e.g. 22] + +- OS: [e.g. iOS] +- Browser [e.g. chrome, safari] +- Version [e.g. 22] **Additional context** Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 11fc491e..bbefe247 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,9 +1,6 @@ --- -name: Feature request -about: Suggest an idea for this project -title: '' -labels: enhancement -assignees: '' +name: Feature request about: Suggest an idea for this project title: '' +labels: enhancement assignees: '' --- diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 787e598e..47d25d97 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -4,7 +4,7 @@ on: branches-ignore: - master pull_request: - types: [opened, synchronize, reopened] + types: [ opened, synchronize, reopened ] jobs: validation: @@ -18,8 +18,8 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, macos-latest, windows-latest] - java: [8, 11, 15] + os: [ ubuntu-latest, macos-latest, windows-latest ] + java: [ 8, 11, 15 ] needs: validation runs-on: ${{ matrix.os }} steps: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ab5d1086..b6901775 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,5 +1,5 @@ name: "Publish release" -on: [workflow_dispatch] +on: [ workflow_dispatch ] jobs: validation: diff --git a/LICENSE.md b/LICENSE.md index 9deca2c8..8ab1ef6c 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -2,8 +2,17 @@ The MIT License (MIT) Copyright (c) 2016 Oembedler Inc. and Contributors -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES +OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index c2d6d65e..db53afb3 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,11 @@ # GraphQL and Graph*i*QL Spring Framework Boot Starters + [![GitHub CI Workflow](https://github.com/graphql-java-kickstart/graphql-spring-boot/workflows/ci/badge.svg)](https://github.com/graphql-java-kickstart/graphql-spring-boot/actions?query=workflow%3ACI+branch%3Amaster) [![Maven Central](https://img.shields.io/maven-central/v/com.graphql-java-kickstart/graphql-spring-boot-starter.svg)](https://maven-badges.herokuapp.com/maven-central/com.graphql-java-kickstart/graphql-spring-boot-starter) [![Chat on Spectrum](https://img.shields.io/badge/spectrum-join%20the%20community-%23800080)](https://spectrum.chat/graphql-java-kick) #### We are looking for contributors! + Are you interested in improving our documentation, working on the codebase, reviewing PRs? [Reach out to us on Spectrum](https://spectrum.chat/graphql-java-kick) and join the team! @@ -13,7 +15,7 @@ Are you interested in improving our documentation, working on the codebase, revi **Table of Contents** - - [WARNING: NoClassDefFoundError when using GraphQL Java Tools > 5.4.x](#warning-noclassdeffounderror-when-using-graphql-java-tools--54x) +- [WARNING: NoClassDefFoundError when using GraphQL Java Tools > 5.4.x](#warning-noclassdeffounderror-when-using-graphql-java-tools--54x) - [Using Gradle](#using-gradle) - [Using Maven](#using-maven) - [Documentation](#documentation) @@ -23,21 +25,21 @@ Are you interested in improving our documentation, working on the codebase, revi - [Enable Graph*i*QL](#enable-graphiql) - [Enable Altair](#enable-altair) - [Enable GraphQL Playground](#enable-graphql-playground) - - [Basic settings](#basic-settings) - - [CDN](#cdn) - - [Custom static resources](#custom-static-resources) - - [Customizing GraphQL Playground](#customizing-graphql-playground) - - [Tabs](#tabs) + - [Basic settings](#basic-settings) + - [CDN](#cdn) + - [Custom static resources](#custom-static-resources) + - [Customizing GraphQL Playground](#customizing-graphql-playground) + - [Tabs](#tabs) - [Supported GraphQL-Java Libraries](#supported-graphql-java-libraries) - - [GraphQL Java Tools](#graphql-java-tools) - - [GraphQL Annotations](#graphql-annotations) - - [Configuration](#configuration) - - [Root resolvers, directives, type extensions](#root-resolvers-directives-type-extensions) - - [Interfaces](#interfaces) - - [Custom scalars and type functions](#custom-scalars-and-type-functions) - - [Custom Relay and GraphQL Annotation Processor](#custom-relay-and-graphql-annotation-processor) + - [GraphQL Java Tools](#graphql-java-tools) + - [GraphQL Annotations](#graphql-annotations) + - [Configuration](#configuration) + - [Root resolvers, directives, type extensions](#root-resolvers-directives-type-extensions) + - [Interfaces](#interfaces) + - [Custom scalars and type functions](#custom-scalars-and-type-functions) + - [Custom Relay and GraphQL Annotation Processor](#custom-relay-and-graphql-annotation-processor) - [Tracing and Metrics](#tracing-and-metrics) - - [Usage](#usage) + - [Usage](#usage) - [Contributions](#contributions) - [Licenses](#licenses) @@ -45,22 +47,27 @@ Are you interested in improving our documentation, working on the codebase, revi ## WARNING: NoClassDefFoundError when using GraphQL Java Tools > 5.4.x -If you're using `graphql-java-tools` in combination with Spring Boot 2.1.x or below then you need to set the -`kotlin.version` in your Spring Boot project explicitly to version 1.3.70, because Spring Boot Starter parent currently -overrides it with a 1.2.* version of Kotlin. -`graphql-java-tools` requires 1.3.* however because of its coroutine support. If you don't override this version -you will run into a `NoClassDefFoundError`. +If you're using `graphql-java-tools` in combination with Spring Boot 2.1.x or below then you need to +set the +`kotlin.version` in your Spring Boot project explicitly to version 1.3.70, because Spring Boot +Starter parent currently overrides it with a 1.2.* version of Kotlin. +`graphql-java-tools` requires 1.3.* however because of its coroutine support. If you don't override +this version you will run into a `NoClassDefFoundError`. Spring Boot team has indicated the Kotlin version will be upgraded to 1.3 in Spring Boot 2.2. ### Using Gradle + Set the Kotlin version in your `gradle.properties` + ``` kotlin.version=1.3.70 ``` ### Using Maven + Set the Kotlin version in your `` section + ```xml 1.3.70 @@ -73,17 +80,23 @@ See our new [Documentation](https://www.graphql-java-kickstart.com/spring-boot/) Repository contains: -* `graphql-spring-boot-starter` to turn your boot application into GraphQL server (see [graphql-java-servlet](https://github.com/graphql-java-kickstart/graphql-java-servlet)) -* `altair-spring-boot-starter`to embed `Altair` tool for schema introspection and query debugging (see [altair](https://github.com/imolorhe/altair)) -* `graphiql-spring-boot-starter`to embed `GraphiQL` tool for schema introspection and query debugging (see [graphiql](https://github.com/graphql/graphiql)) -* `playground-spring-boot-starter`to embed `GraphQL Playground` tool for schema introspection and query debugging (see [GraphQL Playground](https://github.com/prisma/graphql-playground)) -* `voyager-spring-boot-starter`to embed `Voyager` tool for visually explore GraphQL APIs as an interactive graph (see [voyger](https://github.com/APIs-guru/graphql-voyager)) +* `graphql-spring-boot-starter` to turn your boot application into GraphQL server ( + see [graphql-java-servlet](https://github.com/graphql-java-kickstart/graphql-java-servlet)) +* `altair-spring-boot-starter`to embed `Altair` tool for schema introspection and query debugging ( + see [altair](https://github.com/imolorhe/altair)) +* `graphiql-spring-boot-starter`to embed `GraphiQL` tool for schema introspection and query + debugging (see [graphiql](https://github.com/graphql/graphiql)) +* `playground-spring-boot-starter`to embed `GraphQL Playground` tool for schema introspection and + query debugging (see [GraphQL Playground](https://github.com/prisma/graphql-playground)) +* `voyager-spring-boot-starter`to embed `Voyager` tool for visually explore GraphQL APIs as an + interactive graph (see [voyger](https://github.com/APIs-guru/graphql-voyager)) # Requirements and Downloads Requirements: - * Java 1.8 - * Spring Framework Boot > 2.x.x (web) + +* Java 1.8 +* Spring Framework Boot > 2.x.x (web) Gradle: @@ -111,6 +124,7 @@ dependencies { ``` Maven: + ```xml com.graphql-java-kickstart @@ -152,7 +166,9 @@ Maven: ``` -New releases will be available faster in the JCenter repository than in Maven Central. Add the following to use for Maven +New releases will be available faster in the JCenter repository than in Maven Central. Add the +following to use for Maven + ```xml @@ -161,7 +177,9 @@ New releases will be available faster in the JCenter repository than in Maven Ce ``` + For Gradle: + ```groovy repositories { jcenter() @@ -169,6 +187,7 @@ repositories { ``` ### Snapshots + ```xml @@ -178,7 +197,9 @@ repositories { ``` + For gradle: + ```groovy repositories { maven { url "https://oss.jfrog.org/artifactory/oss-snapshot-local" } @@ -187,13 +208,21 @@ repositories { # Enable GraphQL Servlet -The servlet becomes accessible at `/graphql` if `graphql-spring-boot-starter` added as a dependency to a boot application and a `GraphQLSchema` bean is present in the application. Check out the [simple example](https://github.com/graphql-java-kickstart/graphql-spring-boot/tree/master/example) for the bare minimum required. +The servlet becomes accessible at `/graphql` if `graphql-spring-boot-starter` added as a dependency +to a boot application and a `GraphQLSchema` bean is present in the application. Check out +the [simple example](https://github.com/graphql-java-kickstart/graphql-spring-boot/tree/master/example) +for the bare minimum required. -A GraphQL schema can also be automatically created when a [supported graphql-java schema library](https://github.com/graphql-java-kickstart/graphql-spring-boot/blob/master/README.md#supported-graphql-java-libraries) is found on the classpath. +A GraphQL schema can also be automatically created when +a [supported graphql-java schema library](https://github.com/graphql-java-kickstart/graphql-spring-boot/blob/master/README.md#supported-graphql-java-libraries) +is found on the classpath. -See the [graphql-java-servlet usage docs](https://github.com/graphql-java-kickstart/graphql-java-servlet#usage) for the avaiable endpoints exposed. +See +the [graphql-java-servlet usage docs](https://github.com/graphql-java-kickstart/graphql-java-servlet#usage) +for the avaiable endpoints exposed. -Available Spring Boot configuration parameters (either `application.yml` or `application.properties`): +Available Spring Boot configuration parameters (either `application.yml` +or `application.properties`): ```yaml graphql: @@ -208,16 +237,19 @@ graphql: contextSetting: PER_REQUEST_WITH_INSTRUMENTATION ``` -By default a global CORS filter is enabled for `/graphql/**` context. -The `corsEnabled` can be set to `false` to disable it. +By default a global CORS filter is enabled for `/graphql/**` context. The `corsEnabled` can be set +to `false` to disable it. # Enable Graph*i*QL -Graph*i*QL becomes accessible at the root `/graphiql` if `graphiql-spring-boot-starter` is added as a dependency to a boot application. +Graph*i*QL becomes accessible at the root `/graphiql` if `graphiql-spring-boot-starter` is added as +a dependency to a boot application. Note that GraphQL server must be available at `/graphql/*` context to be discovered by Graph*i*QL. -Available Spring Boot configuration parameters (either `application.yml` or `application.properties`): +Available Spring Boot configuration parameters (either `application.yml` +or `application.properties`): + ```yaml graphiql: mapping: /graphiql @@ -244,23 +276,28 @@ graphiql: headers: Authorization: "Bearer " ``` -By default GraphiQL is served from within the package. This can be configured to be served from CDN instead, -by setting the property `graphiql.cdn.enabled` to `true`. -You are able to set the GraphiQL props as well. The `graphiql.props.variables` group can contain any of the props -as defined at [GraphiQL Usage](https://github.com/graphql/graphiql#usage). Since setting (large) queries in the -properties like this isn't very readable, you can use the properties in the `graphiql.props.resources` group -to set the classpath resources that should be loaded. +By default GraphiQL is served from within the package. This can be configured to be served from CDN +instead, by setting the property `graphiql.cdn.enabled` to `true`. -Headers that are used when sending the GraphiQL queries can be set by defining them in the `graphiql.headers` group. +You are able to set the GraphiQL props as well. The `graphiql.props.variables` group can contain any +of the props as defined at [GraphiQL Usage](https://github.com/graphql/graphiql#usage). Since +setting (large) queries in the properties like this isn't very readable, you can use the properties +in the `graphiql.props.resources` group to set the classpath resources that should be loaded. + +Headers that are used when sending the GraphiQL queries can be set by defining them in +the `graphiql.headers` group. # Enable Altair -Altair becomes accessible at the root `/altair` if `altair-spring-boot-starter` is added as a dependency to a boot application. +Altair becomes accessible at the root `/altair` if `altair-spring-boot-starter` is added as a +dependency to a boot application. Note that GraphQL server must be available at `/graphql/*` context to be discovered by Altair. -Available Spring Boot configuration parameters (either `application.yml` or `application.properties`): +Available Spring Boot configuration parameters (either `application.yml` +or `application.properties`): + ```yaml altair: mapping: /altair @@ -284,24 +321,29 @@ altair: headers: Authorization: "Bearer " ``` -By default Altair is served from within the package. This can be configured to be served from CDN instead, -by setting the property `altair.cdn.enabled` to `true`. -You are able to set the Altair props as well. The `altair.props.variables` group. Since setting (large) queries in the -properties like this isn't very readable, you can use the properties in the `altair.props.resources` group -to set the classpath resources that should be loaded. +By default Altair is served from within the package. This can be configured to be served from CDN +instead, by setting the property `altair.cdn.enabled` to `true`. -Headers that are used when sending the Altair queries can be set by defining them in the `altair.headers` group. +You are able to set the Altair props as well. The `altair.props.variables` group. Since setting ( +large) queries in the properties like this isn't very readable, you can use the properties in +the `altair.props.resources` group to set the classpath resources that should be loaded. + +Headers that are used when sending the Altair queries can be set by defining them in +the `altair.headers` group. # Enable GraphQL Playground -GraphQL Playground becomes accessible at root `/playground` (or as configured in `graphql.playground.mapping`) -if `playground-spring-boot-starter` is added as a dependency to a boot application. +GraphQL Playground becomes accessible at root `/playground` (or as configured +in `graphql.playground.mapping`) +if `playground-spring-boot-starter` is added as a dependency to a boot application. -It uses an embedded `GraphQL Playground React`, in accordance to the [official guide](https://github.com/prisma/graphql-playground#as-html-page), -using the 'minimum HTML' approach. +It uses an embedded `GraphQL Playground React`, in accordance to +the [official guide](https://github.com/prisma/graphql-playground#as-html-page), using the 'minimum +HTML' approach. -Available Spring Boot configuration parameters (either `application.yml` or `application.properties`): +Available Spring Boot configuration parameters (either `application.yml` +or `application.properties`): ```yaml graphql.playground: @@ -342,63 +384,77 @@ graphql.playground: - classpath:exampleResponse1.json - classpath:exampleResponse2.json ``` + ## Basic settings -`mapping`, `endpoint` and `subscriptionEndpoint` will default to `/playground`, `/graphql` and `/subscriptions`, -respectively. Note that these values may not be empty. +`mapping`, `endpoint` and `subscriptionEndpoint` will default to `/playground`, `/graphql` +and `/subscriptions`, respectively. Note that these values may not be empty. -`enabled` defaults to `true`, and therefor Playground will be available by default if the dependency is added to a - Spring Boot Web Application project. +`enabled` defaults to `true`, and therefor Playground will be available by default if the dependency +is added to a Spring Boot Web Application project. `pageTitle` defaults to `Playground`. -`headers` allows you to specify headers for the default tab. Note that if your are using Spring Security and CSRF is -enabled CSRF, the CSRF token will be automatically added to the headers. These headers will also be added to all the tabs -configured under the [Tabs](#tabs) section. If a header is defined both in this 'global' header list and the header list -of the individual tabs, the 'local' version will be used for that tab. +`headers` allows you to specify headers for the default tab. Note that if your are using Spring +Security and CSRF is enabled CSRF, the CSRF token will be automatically added to the headers. These +headers will also be added to all the tabs configured under the [Tabs](#tabs) section. If a header +is defined both in this 'global' header list and the header list of the individual tabs, the 'local' +version will be used for that tab. ## CDN -The currently bundled version is `1.7.20`, which is - as of writing this - the latest release of `GraphQL Playground React`. -The CDN option uses `jsDelivr` CDN, if enabled. By default, it will load the latest available release. -Available CDN versions can be found on the project's -[jsDelivr page](https://www.jsdelivr.com/package/npm/graphql-playground-react). The CDN option is disabled by default. +The currently bundled version is `1.7.20`, which is - as of writing this - the latest release +of `GraphQL Playground React`. The CDN option uses `jsDelivr` CDN, if enabled. By default, it will +load the latest available release. Available CDN versions can be found on the project's +[jsDelivr page](https://www.jsdelivr.com/package/npm/graphql-playground-react). The CDN option is +disabled by default. ## Custom static resources -You can also specify a custom local version of Playground by setting the base path for `Playground` resources in -the `staticPath.base` property. Under this directory, you have to provide the following files: - +You can also specify a custom local version of Playground by setting the base path for `Playground` +resources in the `staticPath.base` property. Under this directory, you have to provide the following +files: + * `static/css/index.css` * `static/js/middleware.js` * `favicon.png` * `logo.png` -This is identical to the directory structure of the CDN under the `build` subfolder (where these files can be found). +This is identical to the directory structure of the CDN under the `build` subfolder (where these +files can be found). ## Customizing GraphQL Playground -Further GraphQL Playground settings can be specified under the `settings` group, which are documented in the official -[GraphQL Playground readme](https://github.com/prisma/graphql-playground#settings). Note that enum-like values are -validated against the available options, and your application will not start if wrong settings are provided. Similarly -there is some basic validation for integer values (they must be valid positive integers). +Further GraphQL Playground settings can be specified under the `settings` group, which are +documented in the official +[GraphQL Playground readme](https://github.com/prisma/graphql-playground#settings). Note that +enum-like values are validated against the available options, and your application will not start if +wrong settings are provided. Similarly there is some basic validation for integer values (they must +be valid positive integers). ## Tabs -Optionally, you can specify tabs that will be present when the user first opens GraphQL Playground. You can configure the -query, variables, headers and even supply sample responses. Note that `query`, `variables` and `responses` are expected -to be resources of the appropriate format (GraphQL for `query`, JSON for `variables` and `responses`). +Optionally, you can specify tabs that will be present when the user first opens GraphQL Playground. +You can configure the query, variables, headers and even supply sample responses. Note that `query` +, `variables` and `responses` are expected to be resources of the appropriate format (GraphQL +for `query`, JSON for `variables` and `responses`). # Supported GraphQL-Java Libraries The following libraries have auto-configuration classes for creating a `GraphQLSchema`. ## GraphQL Java Tools + **https://github.com/graphql-java-kickstart/graphql-java-tools** -All `GraphQLResolver` and `GraphQLScalar` beans, along with a bean of type `SchemaParserDictionary` (to provide all other classes), will be used to create a GraphQLSchema. Any files on the classpath named `*.graphqls` will be used to provide the schema definition. See the [Readme](https://github.com/graphql-java-kickstart/graphql-java-tools#usage) for more info. +All `GraphQLResolver` and `GraphQLScalar` beans, along with a bean of +type `SchemaParserDictionary` (to provide all other classes), will be used to create a +GraphQLSchema. Any files on the classpath named `*.graphqls` will be used to provide the schema +definition. See the [Readme](https://github.com/graphql-java-kickstart/graphql-java-tools#usage) for +more info. -Available Spring Boot configuration parameters (either `application.yml` or `application.properties`): +Available Spring Boot configuration parameters (either `application.yml` +or `application.properties`): ```yaml graphql: @@ -408,17 +464,19 @@ graphql: # specification and expectations of most clients, so use this option with caution introspection-enabled: true ``` -By default GraphQL tools uses the location pattern `**/*.graphqls` to scan for GraphQL schemas on the classpath. -Use the `schemaLocationPattern` property to customize this pattern. + +By default GraphQL tools uses the location pattern `**/*.graphqls` to scan for GraphQL schemas on +the classpath. Use the `schemaLocationPattern` property to customize this pattern. ## GraphQL Annotations https://github.com/Enigmatis/graphql-java-annotations -The schema will be built using the GraphQL Annotations library in a code-first approach - instead of writing it -manually, the schema will be constructed based on the Java code. Please see the documentation of the GraphQL Annotations -library for a detailed documentation of the available annotations. This readme focuses on how GraphQL Annotations - -GraphQL Spring Boot Starter integration works. +The schema will be built using the GraphQL Annotations library in a code-first approach - instead of +writing it manually, the schema will be constructed based on the Java code. Please see the +documentation of the GraphQL Annotations library for a detailed documentation of the available +annotations. This readme focuses on how GraphQL Annotations - GraphQL Spring Boot Starter +integration works. ### Configuration @@ -429,59 +487,72 @@ graphql: always-prettify: true #true is the default value, no need to specify it ``` -The most important parameter is the base package. The starter will look for schema-relevant classes in the specified -package and its subpackages. `always-prettify` will "prettify" getter/setter methods - the get/set/is prefix will be -removed from GraphQL fields automatically. +The most important parameter is the base package. The starter will look for schema-relevant classes +in the specified package and its subpackages. `always-prettify` will "prettify" getter/setter +methods - the get/set/is prefix will be removed from GraphQL fields automatically. -### Root resolvers, directives, type extensions +### Root resolvers, directives, type extensions -The root resolvers must be marked with the `GraphQLQueryResolver`, `GraphQLMutationResolver` and `GraphQLSubscription` - annotations (not to be confused with the marker interfaces from the GraphQL Java Tools library). +The root resolvers must be marked with the `GraphQLQueryResolver`, `GraphQLMutationResolver` +and `GraphQLSubscription` +annotations (not to be confused with the marker interfaces from the GraphQL Java Tools library). **Important:** -Unlike GraphQL Java Tools, GraphQL Annotations only supports *one* of them each. Furthermore, GraphQL Annotations -only accepts a *class* as input, *not an instance*. It will either create a new instance of the class itself, or use -static methods. This means that Spring dependency injection will not work in the usual way. The companion example -project (which can be found in the [samples](https://github.com/graphql-java-kickstart/samples) repository) +Unlike GraphQL Java Tools, GraphQL Annotations only supports *one* of them each. Furthermore, +GraphQL Annotations only accepts a *class* as input, *not an instance*. It will either create a new +instance of the class itself, or use static methods. This means that Spring dependency injection +will not work in the usual way. The companion example project (which can be found in +the [samples](https://github.com/graphql-java-kickstart/samples) repository) demonstrates possible workarounds for this issue. -`GraphQLDirectiveDefinition` and `GraphQLTypeExtension`-annotated classes are subject to the same limitation regarding -dependency injection - but there can be any number of them. +`GraphQLDirectiveDefinition` and `GraphQLTypeExtension`-annotated classes are subject to the same +limitation regarding dependency injection - but there can be any number of them. ### Interfaces -Interfaces in the configured package having at least one of their methods marked as `@GraphQLField` are considered a -GraphQL interface, and their implementations are automatically added to the schema. Furthermore, you have to add the -following annotation to GraphQL interfaces: `@GraphQLTypeResolver(GraphQLInterfaceTypeResolver.class)` +Interfaces in the configured package having at least one of their methods marked as `@GraphQLField` +are considered a GraphQL interface, and their implementations are automatically added to the schema. +Furthermore, you have to add the following annotation to GraphQL +interfaces: `@GraphQLTypeResolver(GraphQLInterfaceTypeResolver.class)` ### Custom scalars and type functions -Custom scalars can be defined in the same way as in the case of using GraphQL Java Tools - just define the +Custom scalars can be defined in the same way as in the case of using GraphQL Java Tools - just +define the `GraphQLScalarType` beans. -The starter will also pick up `TypeFunction` beans and pass them to the schema builder. +The starter will also pick up `TypeFunction` beans and pass them to the schema builder. -In these cases the actual beans will be used, not just the classes. Spring dependency injection works as usual. +In these cases the actual beans will be used, not just the classes. Spring dependency injection +works as usual. ### Custom Relay and GraphQL Annotation Processor -It is possible to define a bean implementing `Relay` and/or `GraphQLAnnotations`. If present, these will be passed to -the schema builder. Spring dependency injection works as usual. Note that GraphQL Annotations provides default -implementation for these which should be sufficient is most cases. +It is possible to define a bean implementing `Relay` and/or `GraphQLAnnotations`. If present, these +will be passed to the schema builder. Spring dependency injection works as usual. Note that GraphQL +Annotations provides default implementation for these which should be sufficient is most cases. # Tracing and Metrics -[Apollo style tracing](https://github.com/apollographql/apollo-tracing) along with two levels of metrics based on them are currently configurable. -Full tracing is based on the GraphQL java implementation, and can be enabled in the application.yml or application.properties file: +[Apollo style tracing](https://github.com/apollographql/apollo-tracing) along with two levels of +metrics based on them are currently configurable. Full tracing is based on the GraphQL java +implementation, and can be enabled in the application.yml or application.properties file: + ```yaml graphql: servlet: tracing-enabled: true ``` -the default value is false, with "metrics-only" being available. Metrics-only does not add the tracing extension to the response. -Metrics utilize one of two forms of tracing to feed information to Micrometer. If tracing is enabled, or set to "metrics-only", full tracing metrics will be collected, otherwise a tracing implementation that does not collect field data will be injected. Metrics can be configured in the application.yml or application.properties to either true or false, with a default of false: +the default value is false, with "metrics-only" being available. Metrics-only does not add the +tracing extension to the response. + +Metrics utilize one of two forms of tracing to feed information to Micrometer. If tracing is +enabled, or set to "metrics-only", full tracing metrics will be collected, otherwise a tracing +implementation that does not collect field data will be injected. Metrics can be configured in the +application.yml or application.properties to either true or false, with a default of false: + ```yaml graphql: servlet: @@ -489,23 +560,26 @@ graphql: ``` ## Usage -See [Baeldung Spring Boot Actuators](https://www.baeldung.com/spring-boot-actuators) for the basics of using Actuator. -Add `spring-boot-starter-actuator` to your project as dependency. + +See [Baeldung Spring Boot Actuators](https://www.baeldung.com/spring-boot-actuators) for the basics +of using Actuator. Add `spring-boot-starter-actuator` to your project as dependency. The following metrics are available for exposure: + * `graphql.timer.query` * `graphql.websocket.sessions` - number of active websocket sessions for subscriptions -* `graphql.websocket.subscriptions` - number of active subscriptions - +* `graphql.websocket.subscriptions` - number of active subscriptions # Contributions -Contributions are welcome. Please respect the [Code of Conduct](http://contributor-covenant.org/version/1/3/0/). - +Contributions are welcome. Please respect +the [Code of Conduct](http://contributor-covenant.org/version/1/3/0/). # Licenses -`graphql-spring-boot-starter`, `altair-spring-boot-starter`, `graphiql-spring-boot-starter`and `voyager-spring-boot-starter` are licensed under the MIT License. See [LICENSE](LICENSE.md) for details. +`graphql-spring-boot-starter`, `altair-spring-boot-starter`, `graphiql-spring-boot-starter` +and `voyager-spring-boot-starter` are licensed under the MIT License. See [LICENSE](LICENSE.md) for +details. [graphql-java License](https://github.com/andimarek/graphql-java/blob/master/LICENSE.md) diff --git a/altair-spring-boot-starter/LICENSE.md b/altair-spring-boot-starter/LICENSE.md index 9deca2c8..8ab1ef6c 100644 --- a/altair-spring-boot-starter/LICENSE.md +++ b/altair-spring-boot-starter/LICENSE.md @@ -2,8 +2,17 @@ The MIT License (MIT) Copyright (c) 2016 Oembedler Inc. and Contributors -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES +OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/build.gradle b/build.gradle index d95ee519..54fc8a51 100644 --- a/build.gradle +++ b/build.gradle @@ -48,7 +48,7 @@ subprojects { apply plugin: "io.spring.dependency-management" apply plugin: 'com.jfrog.artifactory' - group "$PROJECT_GROUP" + group "$PROJECT_GROUP" repositories { mavenLocal() diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/SubscriptionSampleApplication.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/SubscriptionSampleApplication.java index ec287deb..e397803c 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/SubscriptionSampleApplication.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/SubscriptionSampleApplication.java @@ -6,8 +6,8 @@ @SpringBootApplication public class SubscriptionSampleApplication { - public static void main(String[] args) { - SpringApplication.run(SubscriptionSampleApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(SubscriptionSampleApplication.class, args); + } } diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerReactorPublisher.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerReactorPublisher.java index 983faccc..c37636c4 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerReactorPublisher.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerReactorPublisher.java @@ -23,6 +23,17 @@ @Component public class StockTickerReactorPublisher { + private static final Map CURRENT_STOCK_PRICES = new ConcurrentHashMap<>(); + private static final Random rand = new SecureRandom(); + + static { + CURRENT_STOCK_PRICES.put("TEAM", dollars(39, 64)); + CURRENT_STOCK_PRICES.put("IBM", dollars(147, 10)); + CURRENT_STOCK_PRICES.put("AMZN", dollars(1002, 94)); + CURRENT_STOCK_PRICES.put("MSFT", dollars(77, 49)); + CURRENT_STOCK_PRICES.put("GOOGL", dollars(1007, 87)); + } + private final Flux publisher; public StockTickerReactorPublisher() { @@ -36,6 +47,22 @@ public StockTickerReactorPublisher() { publisher = Flux.from(connectableFlux); } + private static BigDecimal dollars(int dollars, int cents) { + return truncate("" + dollars + "." + cents); + } + + private static BigDecimal truncate(final String text) { + BigDecimal bigDecimal = new BigDecimal(text); + if (bigDecimal.scale() > 2) { + bigDecimal = new BigDecimal(text).setScale(2, RoundingMode.HALF_UP); + } + return bigDecimal.stripTrailingZeros(); + } + + private static int rollDice(int min, int max) { + return rand.nextInt((max - min) + 1) + min; + } + private Runnable newStockTick(FluxSink emitter) { return () -> { List stockPriceUpdates = getUpdates(rollDice(0, 5)); @@ -76,16 +103,6 @@ private List getUpdates(int number) { return updates; } - private static final Map CURRENT_STOCK_PRICES = new ConcurrentHashMap<>(); - - static { - CURRENT_STOCK_PRICES.put("TEAM", dollars(39, 64)); - CURRENT_STOCK_PRICES.put("IBM", dollars(147, 10)); - CURRENT_STOCK_PRICES.put("AMZN", dollars(1002, 94)); - CURRENT_STOCK_PRICES.put("MSFT", dollars(77, 49)); - CURRENT_STOCK_PRICES.put("GOOGL", dollars(1007, 87)); - } - private StockPriceUpdate rollUpdate() { ArrayList stockQuotes = new ArrayList<>(CURRENT_STOCK_PRICES.keySet()); @@ -103,22 +120,4 @@ private StockPriceUpdate rollUpdate() { return new StockPriceUpdate(stockCode, LocalDateTime.now(), newPrice, incrementDollars); } - private static BigDecimal dollars(int dollars, int cents) { - return truncate("" + dollars + "." + cents); - } - - private static BigDecimal truncate(final String text) { - BigDecimal bigDecimal = new BigDecimal(text); - if (bigDecimal.scale() > 2) { - bigDecimal = new BigDecimal(text).setScale(2, RoundingMode.HALF_UP); - } - return bigDecimal.stripTrailingZeros(); - } - - private static final Random rand = new SecureRandom(); - - private static int rollDice(int min, int max) { - return rand.nextInt((max - min) + 1) + min; - } - } diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerRxPublisher.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerRxPublisher.java index 5ca9afeb..11d4b906 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerRxPublisher.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerRxPublisher.java @@ -25,6 +25,17 @@ @Component public class StockTickerRxPublisher { + private static final Map CURRENT_STOCK_PRICES = new ConcurrentHashMap<>(); + private static final Random rand = new SecureRandom(); + + static { + CURRENT_STOCK_PRICES.put("TEAM", dollars(39, 64)); + CURRENT_STOCK_PRICES.put("IBM", dollars(147, 10)); + CURRENT_STOCK_PRICES.put("AMZN", dollars(1002, 94)); + CURRENT_STOCK_PRICES.put("MSFT", dollars(77, 49)); + CURRENT_STOCK_PRICES.put("GOOGL", dollars(1007, 87)); + } + private final Flowable publisher; public StockTickerRxPublisher() { @@ -42,6 +53,22 @@ public StockTickerRxPublisher() { publisher = connectableObservable.toFlowable(BackpressureStrategy.BUFFER); } + private static BigDecimal dollars(int dollars, int cents) { + return truncate("" + dollars + "." + cents); + } + + private static BigDecimal truncate(final String text) { + BigDecimal bigDecimal = new BigDecimal(text); + if (bigDecimal.scale() > 2) { + bigDecimal = new BigDecimal(text).setScale(2, RoundingMode.HALF_UP); + } + return bigDecimal.stripTrailingZeros(); + } + + private static int rollDice(int min, int max) { + return rand.nextInt((max - min) + 1) + min; + } + private Runnable newStockTick(ObservableEmitter emitter) { return () -> { List stockPriceUpdates = getUpdates(rollDice(0, 5)); @@ -80,17 +107,6 @@ private List getUpdates(int number) { return updates; } - - private static final Map CURRENT_STOCK_PRICES = new ConcurrentHashMap<>(); - - static { - CURRENT_STOCK_PRICES.put("TEAM", dollars(39, 64)); - CURRENT_STOCK_PRICES.put("IBM", dollars(147, 10)); - CURRENT_STOCK_PRICES.put("AMZN", dollars(1002, 94)); - CURRENT_STOCK_PRICES.put("MSFT", dollars(77, 49)); - CURRENT_STOCK_PRICES.put("GOOGL", dollars(1007, 87)); - } - private StockPriceUpdate rollUpdate() { ArrayList stockCodes = new ArrayList<>(CURRENT_STOCK_PRICES.keySet()); @@ -108,22 +124,4 @@ private StockPriceUpdate rollUpdate() { return new StockPriceUpdate(stockCode, LocalDateTime.now(), newPrice, incrementDollars); } - private static BigDecimal dollars(int dollars, int cents) { - return truncate("" + dollars + "." + cents); - } - - private static BigDecimal truncate(final String text) { - BigDecimal bigDecimal = new BigDecimal(text); - if (bigDecimal.scale() > 2) { - bigDecimal = new BigDecimal(text).setScale(2, RoundingMode.HALF_UP); - } - return bigDecimal.stripTrailingZeros(); - } - - private static final Random rand = new SecureRandom(); - - private static int rollDice(int min, int max) { - return rand.nextInt((max - min) + 1) + min; - } - } diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Query.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Query.java index a35b4bf3..4a5a55cb 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Query.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Query.java @@ -6,8 +6,8 @@ @Component class Query implements GraphQLQueryResolver { - public String hello() { - return "Hello world!"; - } + public String hello() { + return "Hello world!"; + } } diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/StockPriceUpdate.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/StockPriceUpdate.java index 7af8accf..e1345965 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/StockPriceUpdate.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/StockPriceUpdate.java @@ -6,31 +6,32 @@ public class StockPriceUpdate { - private final String stockCode; - private final String dateTime; - private final BigDecimal stockPrice; - private final BigDecimal stockPriceChange; - - public StockPriceUpdate(String stockCode, LocalDateTime dateTime, BigDecimal stockPrice, BigDecimal stockPriceChange) { - this.stockCode = stockCode; - this.dateTime = dateTime.format(DateTimeFormatter.ISO_DATE_TIME); - this.stockPrice = stockPrice; - this.stockPriceChange = stockPriceChange; - } - - public String getStockCode() { - return stockCode; - } - - public String getDateTime() { - return dateTime; - } - - public BigDecimal getStockPrice() { - return stockPrice; - } - - public BigDecimal getStockPriceChange() { - return null; //stockPriceChange; - } + private final String stockCode; + private final String dateTime; + private final BigDecimal stockPrice; + private final BigDecimal stockPriceChange; + + public StockPriceUpdate(String stockCode, LocalDateTime dateTime, BigDecimal stockPrice, + BigDecimal stockPriceChange) { + this.stockCode = stockCode; + this.dateTime = dateTime.format(DateTimeFormatter.ISO_DATE_TIME); + this.stockPrice = stockPrice; + this.stockPriceChange = stockPriceChange; + } + + public String getStockCode() { + return stockCode; + } + + public String getDateTime() { + return dateTime; + } + + public BigDecimal getStockPrice() { + return stockPrice; + } + + public BigDecimal getStockPriceChange() { + return null; //stockPriceChange; + } } diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Subscription.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Subscription.java index fbb6687d..122ae7df 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Subscription.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Subscription.java @@ -2,22 +2,21 @@ import graphql.kickstart.spring.web.boot.publishers.StockTickerRxPublisher; import graphql.kickstart.tools.GraphQLSubscriptionResolver; +import java.util.List; import org.reactivestreams.Publisher; import org.springframework.stereotype.Component; -import java.util.List; - @Component class Subscription implements GraphQLSubscriptionResolver { - private StockTickerRxPublisher stockTickerPublisher; + private StockTickerRxPublisher stockTickerPublisher; - Subscription(StockTickerRxPublisher stockTickerPublisher) { - this.stockTickerPublisher = stockTickerPublisher; - } + Subscription(StockTickerRxPublisher stockTickerPublisher) { + this.stockTickerPublisher = stockTickerPublisher; + } - Publisher stockQuotes(List stockCodes) { - return stockTickerPublisher.getPublisher(stockCodes); - } + Publisher stockQuotes(List stockCodes) { + return stockTickerPublisher.getPublisher(stockCodes); + } } diff --git a/example-graphql-subscription/src/main/resources/public/index.html b/example-graphql-subscription/src/main/resources/public/index.html index 48942138..d50b8e77 100644 --- a/example-graphql-subscription/src/main/resources/public/index.html +++ b/example-graphql-subscription/src/main/resources/public/index.html @@ -1,154 +1,157 @@ - - Subscriptions over Web Sockets - - + .stockWrapper { + display: block; + padding: 20px; + font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; + font-weight: 300; + } - - - + .stockSymbol { + font-weight: 600; + } - + + + + + var htmlStr = '' + Object.keys(STOCK_CODES_UPDATES).forEach(function(stockCode) { + var stockList = STOCK_CODES_UPDATES[stockCode] + htmlStr += '
' + htmlStr += ' ' + stockCode + ' ' + stockList.forEach(function(stock) { + var stockPrice = stock['stockPrice'] + + if (stock.stockPriceChange > 0) { + htmlStr += '$' + stockPrice + '' + } else { + htmlStr += '$' + stockPrice + '' + } + htmlStr += ', ' + }) + htmlStr += '
' + }) + $('.stockTicker').html(htmlStr) + } + } + + window.addEventListener("load", subscribeToStocks) +
-

graphql-java Subscriptions

-

An example of graphql-java subscriptions sending continuous updates over websockets

+

graphql-java Subscriptions

+

An example of graphql-java subscriptions sending continuous updates over websockets

-
-
- graphql-java -
-
-

Explanation

-

This demonstrates the use of graphql subscriptions and web sockets to send a stream of imagined stock price - updates to this page.

-

The updates are continuously sent from a server side publish and subscribe system (RxJava in this case) and - pushed - down to the browser client while applying graphql shapes to the subscription data

-

The graphql query used in this example is :

-
+  
+
+ graphql-java +
+
+

Explanation

+

This demonstrates the use of graphql subscriptions and web sockets to send a stream of + imagined stock price + updates to this page.

+

The updates are continuously sent from a server side publish and subscribe system (RxJava + in this case) and + pushed + down to the browser client while applying graphql shapes to the subscription data

+

The graphql query used in this example is :

+
 subscription StockCodeSubscription {
     stockQuotes {
         dateTime
@@ -158,13 +161,13 @@ 

Explanation

} }
-
-
-

Stock Price Updates

-
Pending subscription...
-
📡
-
+
+

Stock Price Updates

+
Pending subscription...
+
📡
+
+
diff --git a/example-graphql-tools/LICENSE.md b/example-graphql-tools/LICENSE.md index 9deca2c8..8ab1ef6c 100644 --- a/example-graphql-tools/LICENSE.md +++ b/example-graphql-tools/LICENSE.md @@ -2,8 +2,17 @@ The MIT License (MIT) Copyright (c) 2016 Oembedler Inc. and Contributors -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES +OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Comment.java b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Comment.java index 1e32139b..4fd82b75 100644 --- a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Comment.java +++ b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Comment.java @@ -2,7 +2,7 @@ class Comment { - private Long id; - private String description; + private Long id; + private String description; } diff --git a/example-graphql-tools/src/main/java/com/graphql/sample/boot/GraphQLToolsSampleApplication.java b/example-graphql-tools/src/main/java/com/graphql/sample/boot/GraphQLToolsSampleApplication.java index 7f3e4a68..97e55f58 100644 --- a/example-graphql-tools/src/main/java/com/graphql/sample/boot/GraphQLToolsSampleApplication.java +++ b/example-graphql-tools/src/main/java/com/graphql/sample/boot/GraphQLToolsSampleApplication.java @@ -6,8 +6,8 @@ @SpringBootApplication public class GraphQLToolsSampleApplication { - public static void main(String[] args) { - SpringApplication.run(GraphQLToolsSampleApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(GraphQLToolsSampleApplication.class, args); + } } diff --git a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Mutation.java b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Mutation.java index f00c63ae..cad837a2 100644 --- a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Mutation.java +++ b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Mutation.java @@ -2,13 +2,12 @@ import graphql.kickstart.tools.GraphQLMutationResolver; import java.security.SecureRandom; -import java.util.Random; import org.springframework.stereotype.Component; @Component public class Mutation implements GraphQLMutationResolver { - public Post createPost(String text){ + public Post createPost(String text) { Post post = new Post(new SecureRandom().nextLong()); post.setText(text); return post; diff --git a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Post.java b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Post.java index 7a56de8d..433979f2 100644 --- a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Post.java +++ b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Post.java @@ -2,22 +2,22 @@ public class Post { - private Long id; - private String text; + private Long id; + private String text; - Post(Long id) { - this.id = id; - } + Post(Long id) { + this.id = id; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public String getText() { - return text; - } + public String getText() { + return text; + } - public void setText(String text) { - this.text = text; - } + public void setText(String text) { + this.text = text; + } } diff --git a/example-graphql-tools/src/main/java/com/graphql/sample/boot/PostResolver.java b/example-graphql-tools/src/main/java/com/graphql/sample/boot/PostResolver.java index 1c7126e8..6f4b1ba2 100644 --- a/example-graphql-tools/src/main/java/com/graphql/sample/boot/PostResolver.java +++ b/example-graphql-tools/src/main/java/com/graphql/sample/boot/PostResolver.java @@ -1,16 +1,15 @@ package com.graphql.sample.boot; import graphql.kickstart.tools.GraphQLResolver; -import org.springframework.stereotype.Component; - import java.util.Collections; import java.util.List; +import org.springframework.stereotype.Component; @Component class PostResolver implements GraphQLResolver { - public List getComments(Post post) { - return Collections.emptyList(); - } + public List getComments(Post post) { + return Collections.emptyList(); + } } diff --git a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Query.java b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Query.java index 3aeb7dfc..7a3af309 100644 --- a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Query.java +++ b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Query.java @@ -6,8 +6,8 @@ @Component class Query implements GraphQLQueryResolver { - Post getPost(Long id) { - return new Post(id); - } + Post getPost(Long id) { + return new Post(id); + } } diff --git a/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLServletTest.kt b/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLServletTest.kt index ab0043fc..e27976eb 100644 --- a/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLServletTest.kt +++ b/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLServletTest.kt @@ -1,8 +1,8 @@ package com.graphql.sample.boot -import com.graphql.spring.boot.test.GraphQLTestTemplate import com.graphql.spring.boot.test.GraphQLTest +import com.graphql.spring.boot.test.GraphQLTestTemplate import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @@ -14,14 +14,14 @@ import org.springframework.test.context.junit.jupiter.SpringExtension @GraphQLTest class GraphQLServletTest { - @Autowired - private lateinit var graphQLTestTemplate: GraphQLTestTemplate + @Autowired + private lateinit var graphQLTestTemplate: GraphQLTestTemplate - @Test - fun `query over HTTP POST multipart with variables returns data requires multipartconfig`() { - val response = graphQLTestTemplate.postMultipart("query echo(\$string: String!)", """{"string":"echo"}""") - assertThat(response).isNotNull - assertThat(response.statusCode).isEqualTo(HttpStatus.OK) - } + @Test + fun `query over HTTP POST multipart with variables returns data requires multipartconfig`() { + val response = graphQLTestTemplate.postMultipart("query echo(\$string: String!)", """{"string":"echo"}""") + assertThat(response).isNotNull + assertThat(response.statusCode).isEqualTo(HttpStatus.OK) + } } diff --git a/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLToolsSampleApplicationTest.java b/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLToolsSampleApplicationTest.java index ec9e3645..1dbcb80b 100644 --- a/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLToolsSampleApplicationTest.java +++ b/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLToolsSampleApplicationTest.java @@ -1,58 +1,58 @@ package com.graphql.sample.boot; +import static graphql.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; + import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.graphql.spring.boot.test.GraphQLResponse; -import com.graphql.spring.boot.test.GraphQLTestTemplate; import com.graphql.spring.boot.test.GraphQLTest; +import com.graphql.spring.boot.test.GraphQLTestTemplate; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.io.IOException; - -import static graphql.Assert.assertNotNull; -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.ArrayList; -import java.util.List; - @ExtendWith(SpringExtension.class) @GraphQLTest public class GraphQLToolsSampleApplicationTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; - - @Test - @Disabled - public void get_comments() throws IOException { - GraphQLResponse response = graphQLTestTemplate.postForResource("graphql/post-get-comments.graphql"); - assertNotNull(response); - assertThat(response.isOk()).isTrue(); - assertThat(response.get("$.data.post.id")).isEqualTo("1"); - } - - @Test - public void get_comments_withFragments() throws IOException { - List fragments = new ArrayList<>(); - fragments.add("graphql/all-comment-fields-fragment.graphql"); - GraphQLResponse response = graphQLTestTemplate.postForResource("graphql/post-get-comments-with-fragment.graphql", fragments); - assertNotNull(response); - assertThat((response.isOk())).isTrue(); - assertThat(response.get("$.data.post.id")).isEqualTo("1"); - } - - @Test - public void create_post() throws IOException { - ObjectNode variables = new ObjectMapper().createObjectNode(); - variables.put("text", "lorem ipsum dolor sit amet"); - GraphQLResponse response = graphQLTestTemplate.perform("graphql/create-post.graphql", variables); - assertThat(response).isNotNull(); - assertThat(response.get("$.data.createPost.id")).isNotNull(); - } + @Autowired + private GraphQLTestTemplate graphQLTestTemplate; + + @Test + @Disabled + public void get_comments() throws IOException { + GraphQLResponse response = graphQLTestTemplate + .postForResource("graphql/post-get-comments.graphql"); + assertNotNull(response); + assertThat(response.isOk()).isTrue(); + assertThat(response.get("$.data.post.id")).isEqualTo("1"); + } + + @Test + public void get_comments_withFragments() throws IOException { + List fragments = new ArrayList<>(); + fragments.add("graphql/all-comment-fields-fragment.graphql"); + GraphQLResponse response = graphQLTestTemplate + .postForResource("graphql/post-get-comments-with-fragment.graphql", fragments); + assertNotNull(response); + assertThat((response.isOk())).isTrue(); + assertThat(response.get("$.data.post.id")).isEqualTo("1"); + } + + @Test + public void create_post() throws IOException { + ObjectNode variables = new ObjectMapper().createObjectNode(); + variables.put("text", "lorem ipsum dolor sit amet"); + GraphQLResponse response = graphQLTestTemplate + .perform("graphql/create-post.graphql", variables); + assertThat(response).isNotNull(); + assertThat(response.get("$.data.createPost.id")).isNotNull(); + } } diff --git a/example-graphql-tools/src/test/java/com/graphql/sample/boot/SpringBootTestWithoutWebEnvironmentTest.java b/example-graphql-tools/src/test/java/com/graphql/sample/boot/SpringBootTestWithoutWebEnvironmentTest.java index d0a3ebce..877e06e1 100644 --- a/example-graphql-tools/src/test/java/com/graphql/sample/boot/SpringBootTestWithoutWebEnvironmentTest.java +++ b/example-graphql-tools/src/test/java/com/graphql/sample/boot/SpringBootTestWithoutWebEnvironmentTest.java @@ -11,9 +11,9 @@ @Disabled public class SpringBootTestWithoutWebEnvironmentTest { - @Test - public void loads_without_complaining_about_missing_ServerContainer() { + @Test + public void loads_without_complaining_about_missing_ServerContainer() { - } + } } diff --git a/example-spring-common/LICENSE.md b/example-spring-common/LICENSE.md index 9deca2c8..8ab1ef6c 100644 --- a/example-spring-common/LICENSE.md +++ b/example-spring-common/LICENSE.md @@ -2,8 +2,17 @@ The MIT License (MIT) Copyright (c) 2016 Oembedler Inc. and Contributors -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES +OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/example-spring-common/build.gradle b/example-spring-common/build.gradle index 0269806d..ddb74e64 100644 --- a/example-spring-common/build.gradle +++ b/example-spring-common/build.gradle @@ -19,7 +19,7 @@ apply plugin: 'org.springframework.boot' -dependencies{ +dependencies { implementation(project(":graphql-spring-boot-starter")) implementation(project(":graphiql-spring-boot-starter")) diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java index 1edd47e0..a66df6b4 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java @@ -28,7 +28,7 @@ @SpringBootApplication public class ApplicationBootConfiguration { - public static void main(String[] args) throws Exception { - SpringApplication.run(ApplicationBootConfiguration.class, args); - } + public static void main(String[] args) throws Exception { + SpringApplication.run(ApplicationBootConfiguration.class, args); + } } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/SimpleListConnection.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/SimpleListConnection.java index 1fbe4468..85b7cf72 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/SimpleListConnection.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/SimpleListConnection.java @@ -7,7 +7,6 @@ import graphql.relay.DefaultConnectionCursor; import graphql.schema.DataFetchingEnvironment; import java.nio.charset.StandardCharsets; - import java.util.ArrayList; import java.util.List; @@ -16,102 +15,105 @@ */ public class SimpleListConnection { - private static final String DUMMY_CURSOR_PREFIX = "simple-cursor"; - private List data = new ArrayList(); - - public SimpleListConnection(List data) { - this.data = data; + private static final String DUMMY_CURSOR_PREFIX = "simple-cursor"; + private List data = new ArrayList(); + + public SimpleListConnection(List data) { + this.data = data; + } + + public T createEdgeObject() { + return (T) new EdgeObjectType(); + } + + public T createConnectionObject() { + return (T) new ConnectionObjectType(); + } + + private List buildEdges() { + List edges = new ArrayList<>(); + int ix = 0; + for (Object object : data) { + EdgeObjectType edge = createEdgeObject(); + edge.setNode(object); + edge.setCursor(createCursor(ix++)); + edges.add(edge); } + return edges; + } - public T createEdgeObject() { - return (T) new EdgeObjectType(); - } - - public T createConnectionObject() { - return (T) new ConnectionObjectType(); - } - - private List buildEdges() { - List edges = new ArrayList<>(); - int ix = 0; - for (Object object : data) { - EdgeObjectType edge = createEdgeObject(); - edge.setNode(object); - edge.setCursor(createCursor(ix++)); - edges.add(edge); - } - return edges; - } - - public T get(DataFetchingEnvironment environment) { - - List edges = buildEdges(); + public T get(DataFetchingEnvironment environment) { - int afterOffset = getOffsetFromCursor(environment.getArgument("after"), -1); - int begin = Math.max(afterOffset, -1) + 1; - int beforeOffset = getOffsetFromCursor(environment.getArgument("before"), edges.size()); - int end = Math.min(beforeOffset, edges.size()); + List edges = buildEdges(); - edges = edges.subList(begin, end); - if (edges.size() == 0) { - return emptyConnection(); - } + int afterOffset = getOffsetFromCursor(environment.getArgument("after"), -1); + int begin = Math.max(afterOffset, -1) + 1; + int beforeOffset = getOffsetFromCursor(environment.getArgument("before"), edges.size()); + int end = Math.min(beforeOffset, edges.size()); - Integer first = environment.getArgument("first"); - Integer last = environment.getArgument("last"); - - String firstPresliceCursor = edges.get(0).getCursor(); - String lastPresliceCursor = edges.get(edges.size() - 1).getCursor(); - - if (first != null) { - edges = edges.subList(0, first <= edges.size() ? first : edges.size()); - } - if (last != null) { - edges = edges.subList(edges.size() - last, edges.size()); - } - - if (edges.size() == 0) { - return emptyConnection(); - } - - EdgeObjectType firstEdge = edges.get(0); - EdgeObjectType lastEdge = edges.get(edges.size() - 1); - - PageInfoObjectType pageInfo = new PageInfoObjectType(); - pageInfo.setStartCursor(firstEdge.getCursor()); - pageInfo.setEndCursor(lastEdge.getCursor()); - pageInfo.setHasPreviousPage(!firstEdge.getCursor().equals(firstPresliceCursor)); - pageInfo.setHasNextPage(!lastEdge.getCursor().equals(lastPresliceCursor)); + edges = edges.subList(begin, end); + if (edges.size() == 0) { + return emptyConnection(); + } - ConnectionObjectType connection = createConnectionObject(); - connection.setEdges(edges); - connection.setPageInfo(pageInfo); + Integer first = environment.getArgument("first"); + Integer last = environment.getArgument("last"); - return (T) connection; - } + String firstPresliceCursor = edges.get(0).getCursor(); + String lastPresliceCursor = edges.get(edges.size() - 1).getCursor(); - private T emptyConnection() { - ConnectionObjectType connection = createConnectionObject(); - connection.setPageInfo(new PageInfoObjectType()); - return (T) connection; + if (first != null) { + edges = edges.subList(0, first <= edges.size() ? first : edges.size()); } - - public ConnectionCursor cursorForObjectInConnection(Object object) { - int index = data.indexOf(object); - String cursor = createCursor(index); - return new DefaultConnectionCursor(cursor); + if (last != null) { + edges = edges.subList(edges.size() - last, edges.size()); } - private int getOffsetFromCursor(String cursor, int defaultValue) { - if (cursor == null) return defaultValue; - String string = new String(java.util.Base64.getDecoder().decode(cursor), StandardCharsets.UTF_8); - return Integer.parseInt(string.substring(DUMMY_CURSOR_PREFIX.length())); + if (edges.size() == 0) { + return emptyConnection(); } - private String createCursor(int offset) { - byte[] lala = (DUMMY_CURSOR_PREFIX + Integer.toString(offset)).getBytes(StandardCharsets.UTF_8); - String string = java.util.Base64.getEncoder().encodeToString(lala); - return string; + EdgeObjectType firstEdge = edges.get(0); + EdgeObjectType lastEdge = edges.get(edges.size() - 1); + + PageInfoObjectType pageInfo = new PageInfoObjectType(); + pageInfo.setStartCursor(firstEdge.getCursor()); + pageInfo.setEndCursor(lastEdge.getCursor()); + pageInfo.setHasPreviousPage(!firstEdge.getCursor().equals(firstPresliceCursor)); + pageInfo.setHasNextPage(!lastEdge.getCursor().equals(lastPresliceCursor)); + + ConnectionObjectType connection = createConnectionObject(); + connection.setEdges(edges); + connection.setPageInfo(pageInfo); + + return (T) connection; + } + + private T emptyConnection() { + ConnectionObjectType connection = createConnectionObject(); + connection.setPageInfo(new PageInfoObjectType()); + return (T) connection; + } + + public ConnectionCursor cursorForObjectInConnection(Object object) { + int index = data.indexOf(object); + String cursor = createCursor(index); + return new DefaultConnectionCursor(cursor); + } + + private int getOffsetFromCursor(String cursor, int defaultValue) { + if (cursor == null) { + return defaultValue; } + String string = new String(java.util.Base64.getDecoder().decode(cursor), + StandardCharsets.UTF_8); + return Integer.parseInt(string.substring(DUMMY_CURSOR_PREFIX.length())); + } + + private String createCursor(int offset) { + byte[] lala = (DUMMY_CURSOR_PREFIX + Integer.toString(offset)).getBytes(StandardCharsets.UTF_8); + String string = java.util.Base64.getEncoder().encodeToString(lala); + return string; + } } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/TodoSimpleListConnection.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/TodoSimpleListConnection.java index 39317897..1afc1e34 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/TodoSimpleListConnection.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/TodoSimpleListConnection.java @@ -1,9 +1,8 @@ package graphql.kickstart.spring.web.boot.sample; -import graphql.kickstart.spring.web.boot.sample.schema.objecttype.TodoObjectType; import com.oembedler.moon.graphql.engine.relay.ConnectionObjectType; import com.oembedler.moon.graphql.engine.relay.EdgeObjectType; - +import graphql.kickstart.spring.web.boot.sample.schema.objecttype.TodoObjectType; import java.util.ArrayList; import java.util.List; @@ -12,19 +11,19 @@ */ public class TodoSimpleListConnection extends SimpleListConnection { - private static final String DUMMY_CURSOR_PREFIX = "simple-cursor"; - private List data = new ArrayList(); + private static final String DUMMY_CURSOR_PREFIX = "simple-cursor"; + private List data = new ArrayList(); - public TodoSimpleListConnection(List data) { - super(data); - } + public TodoSimpleListConnection(List data) { + super(data); + } - public T createEdgeObject() { - return (T) new TodoObjectType.TodoEdgeObjectType(); - } + public T createEdgeObject() { + return (T) new TodoObjectType.TodoEdgeObjectType(); + } - public T createConnectionObject() { - return (T) new TodoObjectType.TodoConnectionObjectType(); - } + public T createConnectionObject() { + return (T) new TodoObjectType.TodoConnectionObjectType(); + } } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/TodoSchema.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/TodoSchema.java index 208d5b28..88f6a582 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/TodoSchema.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/TodoSchema.java @@ -123,21 +123,6 @@ public TodoSimpleListConnection getSimpleConnectionTodo() { return simpleConnectionTodo; } - public static class AddTodoIn { - - private String text; - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } - } - - // --- mutations - @GraphQLMutation @GraphQLDescription("Mutation to add new todo item") public @@ -155,6 +140,8 @@ TodoObjectType.TodoEdgeObjectType addTodoMutation( return todoEdgeObjectType; } + // --- mutations + @GraphQLMutation public @GraphQLOut("filename") @@ -168,4 +155,17 @@ public String updateTodoMutation(@GraphQLIn("updateTodoInput") String newText) { return "Simple output string"; } + public static class AddTodoIn { + + private String text; + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + } + } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/BaseObjectType.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/BaseObjectType.java index f00665bd..98376f80 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/BaseObjectType.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/BaseObjectType.java @@ -28,15 +28,15 @@ */ public class BaseObjectType implements RelayNode { - @GraphQLIgnore - private String id; + @GraphQLIgnore + private String id; - public String getId(RelayNode relayNode) { - BaseObjectType baseObjectType = (BaseObjectType) relayNode; - return new Relay().toGlobalId(relayNode.getClass().getSimpleName(), baseObjectType.id); - } + public String getId(RelayNode relayNode) { + BaseObjectType baseObjectType = (BaseObjectType) relayNode; + return new Relay().toGlobalId(relayNode.getClass().getSimpleName(), baseObjectType.id); + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/RootObjectType.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/RootObjectType.java index ba38395a..9ef007ff 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/RootObjectType.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/RootObjectType.java @@ -19,7 +19,6 @@ package graphql.kickstart.spring.web.boot.sample.schema.objecttype; -import graphql.kickstart.spring.web.boot.sample.schema.TodoSchema; import com.oembedler.moon.graphql.engine.relay.RelayNode; import com.oembedler.moon.graphql.engine.stereotype.GraphQLDescription; import com.oembedler.moon.graphql.engine.stereotype.GraphQLField; @@ -28,6 +27,7 @@ import com.oembedler.moon.graphql.engine.stereotype.GraphQLIn; import com.oembedler.moon.graphql.engine.stereotype.GraphQLNonNull; import com.oembedler.moon.graphql.engine.stereotype.GraphQLObject; +import graphql.kickstart.spring.web.boot.sample.schema.TodoSchema; import org.springframework.beans.factory.annotation.Autowired; /** @@ -36,22 +36,22 @@ @GraphQLObject("Root") public class RootObjectType { - @GraphQLNonNull - @GraphQLField("version") - @GraphQLDescription("Root query version number") - public static final String VERSION = "0.9.0.2"; + @GraphQLNonNull + @GraphQLField("version") + @GraphQLDescription("Root query version number") + public static final String VERSION = "0.9.0.2"; - @Autowired - @GraphQLIgnore - private TodoSchema todoSchema; + @Autowired + @GraphQLIgnore + private TodoSchema todoSchema; - @GraphQLField - public UserObjectType viewer() { - return todoSchema.getTheOnlyUser(); - } + @GraphQLField + public UserObjectType viewer() { + return todoSchema.getTheOnlyUser(); + } - @GraphQLField - public RelayNode node(@GraphQLID @GraphQLNonNull @GraphQLIn("id") final String id) { - return new UserObjectType(); - } + @GraphQLField + public RelayNode node(@GraphQLID @GraphQLNonNull @GraphQLIn("id") final String id) { + return new UserObjectType(); + } } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/TodoObjectType.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/TodoObjectType.java index 0ec42cff..35753d74 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/TodoObjectType.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/TodoObjectType.java @@ -29,31 +29,35 @@ */ @GraphQLObject("Todo") public class TodoObjectType extends BaseObjectType { - private String text; - private boolean complete; - public String getText() { - return text; - } + private String text; + private boolean complete; - public void setText(String text) { - this.text = text; - } + public String getText() { + return text; + } - public boolean isComplete() { - return complete; - } + public void setText(String text) { + this.text = text; + } - public void setComplete(boolean complete) { - this.complete = complete; - } + public boolean isComplete() { + return complete; + } - @GraphQLObject - public static class TodoConnectionObjectType extends ConnectionObjectType { - } + public void setComplete(boolean complete) { + this.complete = complete; + } - @GraphQLObject - public static class TodoEdgeObjectType extends EdgeObjectType { - } + @GraphQLObject + public static class TodoConnectionObjectType extends + ConnectionObjectType { + + } + + @GraphQLObject + public static class TodoEdgeObjectType extends EdgeObjectType { + + } } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/UserObjectType.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/UserObjectType.java index fc2c88ee..d5885e6d 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/UserObjectType.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/UserObjectType.java @@ -19,11 +19,11 @@ package graphql.kickstart.spring.web.boot.sample.schema.objecttype; -import graphql.kickstart.spring.web.boot.sample.schema.TodoSchema; import com.oembedler.moon.graphql.engine.stereotype.GraphQLField; import com.oembedler.moon.graphql.engine.stereotype.GraphQLIgnore; import com.oembedler.moon.graphql.engine.stereotype.GraphQLIn; import com.oembedler.moon.graphql.engine.stereotype.GraphQLObject; +import graphql.kickstart.spring.web.boot.sample.schema.TodoSchema; import graphql.schema.DataFetchingEnvironment; import org.springframework.beans.factory.annotation.Autowired; @@ -33,27 +33,27 @@ @GraphQLObject("User") public class UserObjectType extends BaseObjectType { - @Autowired - @GraphQLIgnore - private TodoSchema todoSchema; + @Autowired + @GraphQLIgnore + private TodoSchema todoSchema; - private String name = "someId"; + private String name = "someId"; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - @GraphQLField - public TodoObjectType.TodoConnectionObjectType todos(@GraphQLIn("before") String before, - @GraphQLIn("after") String after, - @GraphQLIn(value = "first", defaultSpel = "1") Integer first, - @GraphQLIn(value = "last", defaultProvider = "1") Integer last, - DataFetchingEnvironment environment) { - return todoSchema.getSimpleConnectionTodo().get(environment); - } + @GraphQLField + public TodoObjectType.TodoConnectionObjectType todos(@GraphQLIn("before") String before, + @GraphQLIn("after") String after, + @GraphQLIn(value = "first", defaultSpel = "1") Integer first, + @GraphQLIn(value = "last", defaultProvider = "1") Integer last, + DataFetchingEnvironment environment) { + return todoSchema.getSimpleConnectionTodo().get(environment); + } } diff --git a/example-spring-common/src/main/resources/application.yml b/example-spring-common/src/main/resources/application.yml index c9bd9d29..b7e01142 100644 --- a/example-spring-common/src/main/resources/application.yml +++ b/example-spring-common/src/main/resources/application.yml @@ -1,15 +1,15 @@ spring: - application: - name: graphql-todo-app + application: + name: graphql-todo-app server: - port: 9000 + port: 9000 graphql: - spring-graphql-common: - clientMutationIdName: clientMutationId - injectClientMutationId: true - allowEmptyClientMutationId: false - mutationInputArgumentName: input - outputObjectNamePrefix: Payload - inputObjectNamePrefix: Input - schemaMutationObjectName: Mutation + spring-graphql-common: + clientMutationIdName: clientMutationId + injectClientMutationId: true + allowEmptyClientMutationId: false + mutationInputArgumentName: input + outputObjectNamePrefix: Payload + inputObjectNamePrefix: Input + schemaMutationObjectName: Mutation diff --git a/example-webflux/LICENSE.md b/example-webflux/LICENSE.md index 9deca2c8..8ab1ef6c 100644 --- a/example-webflux/LICENSE.md +++ b/example-webflux/LICENSE.md @@ -2,8 +2,17 @@ The MIT License (MIT) Copyright (c) 2016 Oembedler Inc. and Contributors -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES +OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/example-webflux/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationWebfluxConfiguration.java b/example-webflux/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationWebfluxConfiguration.java index 6e7fc2a2..6cc4ff78 100644 --- a/example-webflux/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationWebfluxConfiguration.java +++ b/example-webflux/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationWebfluxConfiguration.java @@ -34,21 +34,21 @@ @EnableWebFlux public class ApplicationWebfluxConfiguration { - public static void main(String[] args) { - SpringApplication.run(ApplicationWebfluxConfiguration.class, args); - } + public static void main(String[] args) { + SpringApplication.run(ApplicationWebfluxConfiguration.class, args); + } - @Bean - GraphQLSchema schema() { - return GraphQLSchema.newSchema() - .query(GraphQLObjectType.newObject() - .name("query") - .field(field -> field - .name("test") - .type(Scalars.GraphQLString) - .dataFetcher(environment -> "response") - ) - .build()) - .build(); - } + @Bean + GraphQLSchema schema() { + return GraphQLSchema.newSchema() + .query(GraphQLObjectType.newObject() + .name("query") + .field(field -> field + .name("test") + .type(Scalars.GraphQLString) + .dataFetcher(environment -> "response") + ) + .build()) + .build(); + } } diff --git a/example/LICENSE.md b/example/LICENSE.md index 9deca2c8..8ab1ef6c 100644 --- a/example/LICENSE.md +++ b/example/LICENSE.md @@ -2,8 +2,17 @@ The MIT License (MIT) Copyright (c) 2016 Oembedler Inc. and Contributors -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES +OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/example/build.gradle b/example/build.gradle index 5da3e8a2..679121eb 100644 --- a/example/build.gradle +++ b/example/build.gradle @@ -19,7 +19,7 @@ apply plugin: "org.springframework.boot" -dependencies{ +dependencies { implementation(project(":altair-spring-boot-starter")) implementation(project(":graphql-spring-boot-starter")) implementation(project(":graphiql-spring-boot-starter")) diff --git a/example/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java b/example/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java index 7ad38f04..b0b298b7 100644 --- a/example/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java +++ b/example/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java @@ -29,21 +29,21 @@ @SpringBootApplication public class ApplicationBootConfiguration { - public static void main(String[] args) { - SpringApplication.run(ApplicationBootConfiguration.class, args); - } + public static void main(String[] args) { + SpringApplication.run(ApplicationBootConfiguration.class, args); + } - @Bean - GraphQLSchema schema() { - return GraphQLSchema.newSchema() - .query(GraphQLObjectType.newObject() - .name("query") - .field(field -> field - .name("test") - .type(Scalars.GraphQLString) - .dataFetcher(environment -> "response") - ) - .build()) - .build(); - } + @Bean + GraphQLSchema schema() { + return GraphQLSchema.newSchema() + .query(GraphQLObjectType.newObject() + .name("query") + .field(field -> field + .name("test") + .type(Scalars.GraphQLString) + .dataFetcher(environment -> "response") + ) + .build()) + .build(); + } } diff --git a/gradle.properties b/gradle.properties index 274dd8c4..11379870 100644 --- a/gradle.properties +++ b/gradle.properties @@ -16,47 +16,34 @@ # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # - version=8.1.0-SNAPSHOT - ### Project Metadata - -PROJECT_GROUP = com.graphql-java-kickstart -PROJECT_NAME = graphql-spring-boot -PROJECT_DESC = GraphQL Spring Framework Boot -PROJECT_GIT_REPO_URL = https://github.com/graphql-java-kickstart/graphql-spring-boot -PROJECT_LICENSE = MIT -PROJECT_LICENSE_URL = https://github.com/graphql-java-kickstart/spring-boot-graphql/blob/master/LICENSE.md -PROJECT_DEV_ID = apottere -PROJECT_DEV_NAME = Andrew Potter - +PROJECT_GROUP=com.graphql-java-kickstart +PROJECT_NAME=graphql-spring-boot +PROJECT_DESC=GraphQL Spring Framework Boot +PROJECT_GIT_REPO_URL=https://github.com/graphql-java-kickstart/graphql-spring-boot +PROJECT_LICENSE=MIT +PROJECT_LICENSE_URL=https://github.com/graphql-java-kickstart/spring-boot-graphql/blob/master/LICENSE.md +PROJECT_DEV_ID=apottere +PROJECT_DEV_NAME=Andrew Potter VCS=Git - ### - -SOURCE_COMPATIBILITY = 1.8 -TARGET_COMPATIBILITY = 1.8 - +SOURCE_COMPATIBILITY=1.8 +TARGET_COMPATIBILITY=1.8 ### Dependencies - -LIB_GRAPHQL_JAVA_VER = 15.0 -LIB_SPRING_BOOT_VER = 2.3.6.RELEASE -LIB_GRAPHQL_SERVLET_VER = 10.1.0-SNAPSHOT -LIB_GRAPHQL_JAVA_TOOLS_VER = 6.3.0 -LIB_GRAPHQL_ANNOTATIONS_VER = 8.2 -LIB_REFLECTIONS_VER = 0.9.11 +LIB_GRAPHQL_JAVA_VER=15.0 +LIB_SPRING_BOOT_VER=2.3.6.RELEASE +LIB_GRAPHQL_SERVLET_VER=10.1.0-SNAPSHOT +LIB_GRAPHQL_JAVA_TOOLS_VER=6.3.0 +LIB_GRAPHQL_ANNOTATIONS_VER=8.2 +LIB_REFLECTIONS_VER=0.9.11 LIB_APACHE_COMMONS_TEXT=1.8 LIB_JSOUP_VER=1.13.1 kotlin.version=1.3.72 - ### Gradle Plugins - LIB_BINTRAY_PLUGIN_VER=1.8.5 LIB_RELEASE_PLUGIN_VER=2.8.1 - ### - org.gradle.daemon=true - bintray.user=USER bintray.key=KEY diff --git a/gradlew b/gradlew index 4f906e0c..8f890474 100755 --- a/gradlew +++ b/gradlew @@ -26,22 +26,22 @@ # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +while [ -h "$PRG" ]; do + ls=$(ls -ld "$PRG") + link=$(expr "$ls" : '.*-> \(.*\)$') + if expr "$link" : '/.*' >/dev/null; then + PRG="$link" + else + PRG=$(dirname "$PRG")"/$link" + fi done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" +SAVED="$(pwd)" +cd "$(dirname \"$PRG\")/" >/dev/null +APP_HOME="$(pwd -P)" cd "$SAVED" >/dev/null APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +APP_BASE_NAME=$(basename "$0") # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' @@ -49,15 +49,15 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" -warn () { - echo "$*" +warn() { + echo "$*" } -die () { - echo - echo "$*" - echo - exit 1 +die() { + echo + echo "$*" + echo + exit 1 } # OS specific support (must be 'true' or 'false'). @@ -65,119 +65,118 @@ cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$(uname)" in +CYGWIN*) + cygwin=true + ;; +Darwin*) + darwin=true + ;; +MINGW*) + msys=true + ;; +NONSTOP*) + nonstop=true + ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - # Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME +if [ -n "$JAVA_HOME" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ]; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." - fi + fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ]; then + MAX_FD_LIMIT=$(ulimit -H -n) + if [ $? -eq 0 ]; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ]; then + MAX_FD="$MAX_FD_LIMIT" fi + ulimit -n $MAX_FD + if [ $? -ne 0 ]; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" +if [ "$cygwin" = "true" -o "$msys" = "true" ]; then + APP_HOME=$(cygpath --path --mixed "$APP_HOME") + CLASSPATH=$(cygpath --path --mixed "$CLASSPATH") + + JAVACMD=$(cygpath --unix "$JAVACMD") + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=$(find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null) + SEP="" + for dir in $ROOTDIRSRAW; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ]; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@"; do + CHECK=$(echo "$arg" | egrep -c "$OURCYGPATTERN" -) + CHECK2=$(echo "$arg" | egrep -c "^-") ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ]; then ### Added a condition + eval $(echo args$i)=$(cygpath --path --ignore --mixed "$arg") + else + eval $(echo args$i)="\"$arg\"" fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac + i=$(expr $i + 1) + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac fi # Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " +save() { + for i; do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/"; done + echo " " } -APP_ARGS=`save "$@"` +APP_ARGS=$(save "$@") # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" diff --git a/graphql-spring-boot-starter/LICENSE.md b/graphql-spring-boot-starter/LICENSE.md index fb59d139..abf6359c 100644 --- a/graphql-spring-boot-starter/LICENSE.md +++ b/graphql-spring-boot-starter/LICENSE.md @@ -2,8 +2,17 @@ The MIT License (MIT) Copyright (c) 2015 Oembedler Inc. and Contributors -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES +OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLResponse.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLResponse.java index 18f390e9..17fa8ae1 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLResponse.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLResponse.java @@ -9,133 +9,141 @@ import com.graphql.spring.boot.test.helper.GraphQLTestConstantsHelper; import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.ReadContext; -import org.springframework.boot.test.json.JsonContentAssert; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - import java.io.IOException; import java.util.List; import java.util.Objects; +import org.springframework.boot.test.json.JsonContentAssert; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; public class GraphQLResponse { - private final ResponseEntity responseEntity; - private final ObjectMapper mapper; - private final ReadContext context; - - public GraphQLResponse(ResponseEntity responseEntity, ObjectMapper objectMapper) { - this.responseEntity = Objects.requireNonNull(responseEntity); - this.mapper = Objects.requireNonNull(objectMapper); - - Objects.requireNonNull(responseEntity.getBody(), - () -> "Body is empty with status " + responseEntity.getStatusCodeValue()); - context = JsonPath.parse(responseEntity.getBody()); - } - - public JsonNode readTree() throws IOException { - return mapper.readTree(responseEntity.getBody()); - } - - public Object getRaw(String path) { - return get(path, Object.class); - } - - public String get(String path) { - return get(path, String.class); - } - - public T get(String path, Class type) { - return mapper.convertValue(context.read(path), type); - } - - public T get(String path, JavaType type) { - return mapper.convertValue(context.read(path), type); - } - - public List getList(String path, Class type) { - return get(path, mapper.getTypeFactory().constructCollectionType(List.class, type)); - } - - public ReadContext context() { - return context; - } - - public boolean isOk() { - return getStatusCode() == HttpStatus.OK; - } - - public HttpStatus getStatusCode() { - return responseEntity.getStatusCode(); - } - - public ResponseEntity getRawResponse() { - return responseEntity; - } - - /** - * Asserts that no errors are present in the response. An empty or null "errors" array also passes this test. - * @return this object - */ - public GraphQLResponse assertThatNoErrorsArePresent() { - return assertThatListOfErrors().hasNoErrors().and(); - } - - /** - * Returns an assertion for the number of errors in the response. - * @return the assertion for the number of errors. - */ - public NumberOfErrorsAssertion assertThatNumberOfErrors() { - return new NumberOfErrorsAssertion(this); - } - - /** - * Returns an assertion for the list of errors in the response. - * @return the assertion for the list of errors. - */ - public GraphQLErrorListAssertion assertThatListOfErrors() { - return new GraphQLErrorListAssertion(this); - } - - /** - * Returns an assertion for the given field(s). - * @param jsonPath the JSON path of the field(s) to assert. - * @return the assertion for the given field. - */ - public GraphQLFieldAssert assertThatField(final String jsonPath) { - return new GraphQLFieldAssert(this, jsonPath); - } - - /** - * Returns an assertion for the root "data" field. - * @return the assertion for the $.data field. - */ - public GraphQLFieldAssert assertThatDataField() { - return assertThatField(GraphQLTestConstantsHelper.DATA_PATH); - } - - /** - * Returns an assertion for the root "extensions" field. - * @return the assertion for the $.extensions field. - */ - public GraphQLFieldAssert assertThatExtensionsField() { - return assertThatField(GraphQLTestConstantsHelper.EXTENSIONS_PATH); - } - - /** - * Returns an assertion for the root "errors" field. - * @return the assertion for the $.errors field. - */ - public GraphQLFieldAssert assertThatErrorsField() { - return assertThatField(GraphQLTestConstantsHelper.ERRORS_PATH); - } - - /** - * Returns an assertion for the JSON content of the response. Since the Spring Boot Framework does not provide - * an abstract version of {@link JsonContentAssert} (as core AssertJ assertions do), it is not possible - * chain other assertions after this one. - * @return a {@link JsonContentAssert} instance for the content of the response. - */ - public JsonContentAssert assertThatJsonContent() { - return new JsonContentAssert(null, responseEntity.getBody()); - } + private final ResponseEntity responseEntity; + private final ObjectMapper mapper; + private final ReadContext context; + + public GraphQLResponse(ResponseEntity responseEntity, ObjectMapper objectMapper) { + this.responseEntity = Objects.requireNonNull(responseEntity); + this.mapper = Objects.requireNonNull(objectMapper); + + Objects.requireNonNull(responseEntity.getBody(), + () -> "Body is empty with status " + responseEntity.getStatusCodeValue()); + context = JsonPath.parse(responseEntity.getBody()); + } + + public JsonNode readTree() throws IOException { + return mapper.readTree(responseEntity.getBody()); + } + + public Object getRaw(String path) { + return get(path, Object.class); + } + + public String get(String path) { + return get(path, String.class); + } + + public T get(String path, Class type) { + return mapper.convertValue(context.read(path), type); + } + + public T get(String path, JavaType type) { + return mapper.convertValue(context.read(path), type); + } + + public List getList(String path, Class type) { + return get(path, mapper.getTypeFactory().constructCollectionType(List.class, type)); + } + + public ReadContext context() { + return context; + } + + public boolean isOk() { + return getStatusCode() == HttpStatus.OK; + } + + public HttpStatus getStatusCode() { + return responseEntity.getStatusCode(); + } + + public ResponseEntity getRawResponse() { + return responseEntity; + } + + /** + * Asserts that no errors are present in the response. An empty or null "errors" array also passes + * this test. + * + * @return this object + */ + public GraphQLResponse assertThatNoErrorsArePresent() { + return assertThatListOfErrors().hasNoErrors().and(); + } + + /** + * Returns an assertion for the number of errors in the response. + * + * @return the assertion for the number of errors. + */ + public NumberOfErrorsAssertion assertThatNumberOfErrors() { + return new NumberOfErrorsAssertion(this); + } + + /** + * Returns an assertion for the list of errors in the response. + * + * @return the assertion for the list of errors. + */ + public GraphQLErrorListAssertion assertThatListOfErrors() { + return new GraphQLErrorListAssertion(this); + } + + /** + * Returns an assertion for the given field(s). + * + * @param jsonPath the JSON path of the field(s) to assert. + * @return the assertion for the given field. + */ + public GraphQLFieldAssert assertThatField(final String jsonPath) { + return new GraphQLFieldAssert(this, jsonPath); + } + + /** + * Returns an assertion for the root "data" field. + * + * @return the assertion for the $.data field. + */ + public GraphQLFieldAssert assertThatDataField() { + return assertThatField(GraphQLTestConstantsHelper.DATA_PATH); + } + + /** + * Returns an assertion for the root "extensions" field. + * + * @return the assertion for the $.extensions field. + */ + public GraphQLFieldAssert assertThatExtensionsField() { + return assertThatField(GraphQLTestConstantsHelper.EXTENSIONS_PATH); + } + + /** + * Returns an assertion for the root "errors" field. + * + * @return the assertion for the $.errors field. + */ + public GraphQLFieldAssert assertThatErrorsField() { + return assertThatField(GraphQLTestConstantsHelper.ERRORS_PATH); + } + + /** + * Returns an assertion for the JSON content of the response. Since the Spring Boot Framework does + * not provide an abstract version of {@link JsonContentAssert} (as core AssertJ assertions do), + * it is not possible chain other assertions after this one. + * + * @return a {@link JsonContentAssert} instance for the content of the response. + */ + public JsonContentAssert assertThatJsonContent() { + return new JsonContentAssert(null, responseEntity.getBody()); + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestSubscription.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestSubscription.java index 9d1654dd..ac35b609 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestSubscription.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestSubscription.java @@ -53,17 +53,15 @@ public class GraphQLTestSubscription { private static final AtomicInteger ID_COUNTER = new AtomicInteger(1); private static final UriBuilderFactory URI_BUILDER_FACTORY = new DefaultUriBuilderFactory(); private static final Object STATE_LOCK = new Object(); - + private final Environment environment; + private final ObjectMapper objectMapper; + private final String subscriptionPath; @Getter private Session session; private SubscriptionState state = SubscriptionState.builder() .id(ID_COUNTER.incrementAndGet()) .build(); - private final Environment environment; - private final ObjectMapper objectMapper; - private final String subscriptionPath; - public boolean isInitialized() { return state.isInitialized(); } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestTemplate.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestTemplate.java index 5ec0e030..3eb1d508 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestTemplate.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestTemplate.java @@ -1,8 +1,17 @@ package com.graphql.spring.boot.test; +import static java.util.Objects.nonNull; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import lombok.Getter; import lombok.NonNull; import org.springframework.beans.factory.annotation.Value; @@ -17,308 +26,316 @@ import org.springframework.util.MultiValueMap; import org.springframework.util.StreamUtils; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static java.util.Objects.nonNull; - /** * Helper class to test GraphQL queries and mutations. */ public class GraphQLTestTemplate { - private final ResourceLoader resourceLoader; - private final TestRestTemplate restTemplate; - private final String graphqlMapping; - private final ObjectMapper objectMapper; - @Getter - private final HttpHeaders headers = new HttpHeaders(); - - public GraphQLTestTemplate( - final ResourceLoader resourceLoader, - final TestRestTemplate restTemplate, - @Value("${graphql.servlet.mapping:/graphql}") - final String graphqlMapping, - final ObjectMapper objectMapper - ) { - this.resourceLoader = resourceLoader; - this.restTemplate = restTemplate; - this.graphqlMapping = graphqlMapping; - this.objectMapper = objectMapper; + private final ResourceLoader resourceLoader; + private final TestRestTemplate restTemplate; + private final String graphqlMapping; + private final ObjectMapper objectMapper; + @Getter + private final HttpHeaders headers = new HttpHeaders(); + + public GraphQLTestTemplate( + final ResourceLoader resourceLoader, + final TestRestTemplate restTemplate, + @Value("${graphql.servlet.mapping:/graphql}") final String graphqlMapping, + final ObjectMapper objectMapper + ) { + this.resourceLoader = resourceLoader; + this.restTemplate = restTemplate; + this.graphqlMapping = graphqlMapping; + this.objectMapper = objectMapper; + } + + private String createJsonQuery(String graphql, String operation, ObjectNode variables) + throws JsonProcessingException { + + ObjectNode wrapper = objectMapper.createObjectNode(); + wrapper.put("query", graphql); + if (nonNull(operation)) { + wrapper.put("operationName", operation); } - - private String createJsonQuery(String graphql, String operation, ObjectNode variables) - throws JsonProcessingException { - - ObjectNode wrapper = objectMapper.createObjectNode(); - wrapper.put("query", graphql); - if (nonNull(operation)) { - wrapper.put("operationName", operation); - } - wrapper.set("variables", variables); - return objectMapper.writeValueAsString(wrapper); + wrapper.set("variables", variables); + return objectMapper.writeValueAsString(wrapper); + } + + private String loadQuery(String location) throws IOException { + Resource resource = resourceLoader.getResource("classpath:" + location); + return loadResource(resource); + } + + private String loadResource(Resource resource) throws IOException { + try (InputStream inputStream = resource.getInputStream()) { + return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); } - - private String loadQuery(String location) throws IOException { - Resource resource = resourceLoader.getResource("classpath:" + location); - return loadResource(resource); + } + + /** + * @param name Name (key) of HTTP header to add. + * @param value Value of HTTP header to add. + * @deprecated use {{@link #withAdditionalHeader(String, String...)}} instead Add an HTTP header + * that will be sent with each request this sends. + */ + @Deprecated + public void addHeader(final String name, final String value) { + withAdditionalHeader(name, value); + } + + /** + * Add an HTTP header that will be sent with each request this sends. + * + * @param name Name (key) of HTTP header to add. + * @param value Value(s) of HTTP header to add. + * @return self + */ + public GraphQLTestTemplate withAdditionalHeader(final String name, final String... value) { + headers.addAll(name, Arrays.asList(value)); + return this; + } + + /** + * Add multiple HTTP header that will be sent with each request this sends. + * + * @param additionalHeaders additional headers to add + * @return self + */ + public GraphQLTestTemplate withAdditionalHeaders( + final MultiValueMap additionalHeaders) { + headers.addAll(additionalHeaders); + return this; + } + + /** + * Adds a bearer token to the authorization header. + * + * @param token the bearer token + * @return self + */ + public GraphQLTestTemplate withBearerAuth(@NonNull final String token) { + headers.setBearerAuth(token); + return this; + } + + /** + * Adds basic authentication to the authorization header. + * + * @param username the username + * @param password the password + * @param charset the charset used by the credentials + * @return self + */ + public GraphQLTestTemplate withBasicAuth( + @NonNull final String username, + @NonNull final String password, + @Nullable final Charset charset + ) { + headers.setBasicAuth(username, password, charset); + return this; + } + + /** + * Adds basic authentication to the authorization header. + * + * @param username the username + * @param password the password + * @return self + */ + public GraphQLTestTemplate withBasicAuth(@NonNull final String username, + @NonNull final String password) { + headers.setBasicAuth(username, password, null); + return this; + } + + /** + * Adds basic authentication to the authorization header. + * + * @param encodedCredentials the encoded credentials + * @return self + */ + public GraphQLTestTemplate withBasicAuth(@NonNull final String encodedCredentials) { + headers.setBasicAuth(encodedCredentials); + return this; + } + + /** + * @param newHeaders Headers to use. + * @deprecated use {{@link #withHeaders(HttpHeaders)}} instead. Replace any associated HTTP + * headers with the provided headers. + */ + @Deprecated + public void setHeaders(HttpHeaders newHeaders) { + withHeaders(newHeaders); + } + + /** + * Replace any associated HTTP headers with the provided headers. + * + * @param newHeaders Headers to use. + * @return self + */ + public GraphQLTestTemplate withHeaders(final HttpHeaders newHeaders) { + return withClearHeaders().withAdditionalHeaders(newHeaders); + } + + /** + * @deprecated use {{@link #withClearHeaders()}} instead Clear all associated HTTP headers. + */ + @Deprecated + public void clearHeaders() { + withClearHeaders(); + } + + /** + * Clear all associated HTTP headers. + * + * @return self + */ + public GraphQLTestTemplate withClearHeaders() { + headers.clear(); + return this; + } + + /** + * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL + * server. + * + * @param graphqlResource path to the classpath resource containing the GraphQL query + * @return {@link GraphQLResponse} containing the result of query execution + * @throws IOException if the resource cannot be loaded from the classpath + * @deprecated Use {@link #postForResource(String)} instead + */ + @Deprecated + public GraphQLResponse perform(String graphqlResource) throws IOException { + return postForResource(graphqlResource); + } + + /** + * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL + * server. + * + * @param graphqlResource path to the classpath resource containing the GraphQL query + * @param variables the input variables for the GraphQL query + * @return {@link GraphQLResponse} containing the result of query execution + * @throws IOException if the resource cannot be loaded from the classpath + */ + public GraphQLResponse perform(String graphqlResource, ObjectNode variables) throws IOException { + return perform(graphqlResource, null, variables, Collections.emptyList()); + } + + /** + * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL + * server. + * + * @param graphqlResource path to the classpath resource containing the GraphQL query + * @param operationName the name of the GraphQL operation to be executed + * @return {@link GraphQLResponse} containing the result of query execution + * @throws IOException if the resource cannot be loaded from the classpath + */ + public GraphQLResponse perform(String graphqlResource, String operationName) throws IOException { + return perform(graphqlResource, operationName, null, Collections.emptyList()); + } + + /** + * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL + * server. + * + * @param graphqlResource path to the classpath resource containing the GraphQL query + * @param operation the name of the GraphQL operation to be executed + * @param variables the input variables for the GraphQL query + * @return {@link GraphQLResponse} containing the result of query execution + * @throws IOException if the resource cannot be loaded from the classpath + */ + public GraphQLResponse perform(String graphqlResource, String operation, ObjectNode variables) + throws IOException { + return perform(graphqlResource, operation, variables, Collections.emptyList()); + } + + /** + * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL + * server. + * + * @param graphqlResource path to the classpath resource containing the GraphQL query + * @param variables the input variables for the GraphQL query + * @param fragmentResources an ordered list of classpath resources containing GraphQL fragment + * definitions. + * @return {@link GraphQLResponse} containing the result of query execution + * @throws IOException if the resource cannot be loaded from the classpath + */ + public GraphQLResponse perform(String graphqlResource, ObjectNode variables, + List fragmentResources) throws IOException { + return perform(graphqlResource, null, variables, fragmentResources); + } + + /** + * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL + * server. + * + * @param graphqlResource path to the classpath resource containing the GraphQL query + * @param variables the input variables for the GraphQL query + * @param fragmentResources an ordered list of classpath resources containing GraphQL fragment + * definitions. + * @return {@link GraphQLResponse} containing the result of query execution + * @throws IOException if the resource cannot be loaded from the classpath + */ + public GraphQLResponse perform(String graphqlResource, String operationName, ObjectNode variables, + List fragmentResources) throws IOException { + StringBuilder sb = new StringBuilder(); + for (String fragmentResource : fragmentResources) { + sb.append(loadQuery(fragmentResource)); } - - private String loadResource(Resource resource) throws IOException { - try (InputStream inputStream = resource.getInputStream()) { - return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); - } - } - - /** - * @deprecated use {{@link #withAdditionalHeader(String, String...)}} instead - * Add an HTTP header that will be sent with each request this sends. - * - * @param name Name (key) of HTTP header to add. - * @param value Value of HTTP header to add. - */ - @Deprecated - public void addHeader(final String name, final String value) { - withAdditionalHeader(name, value); - } - - /** - * Add an HTTP header that will be sent with each request this sends. - * - * @param name Name (key) of HTTP header to add. - * @param value Value(s) of HTTP header to add. - * @return self - */ - public GraphQLTestTemplate withAdditionalHeader(final String name, final String... value) { - headers.addAll(name, Arrays.asList(value)); - return this; - } - - /** - * Add multiple HTTP header that will be sent with each request this sends. - * - * @param additionalHeaders additional headers to add - * @return self - */ - public GraphQLTestTemplate withAdditionalHeaders(final MultiValueMap additionalHeaders) { - headers.addAll(additionalHeaders); - return this; - } - - /** - * Adds a bearer token to the authorization header. - * @param token the bearer token - * @return self - */ - public GraphQLTestTemplate withBearerAuth(@NonNull final String token) { - headers.setBearerAuth(token); - return this; - } - - /** - * Adds basic authentication to the authorization header. - * @param username the username - * @param password the password - * @param charset the charset used by the credentials - * @return self - */ - public GraphQLTestTemplate withBasicAuth( - @NonNull final String username, - @NonNull final String password, - @Nullable final Charset charset - ) { - headers.setBasicAuth(username, password, charset); - return this; - } - - /** - * Adds basic authentication to the authorization header. - * @param username the username - * @param password the password - * @return self - */ - public GraphQLTestTemplate withBasicAuth(@NonNull final String username, @NonNull final String password) { - headers.setBasicAuth(username, password, null); - return this; - } - - /** - * Adds basic authentication to the authorization header. - * @param encodedCredentials the encoded credentials - * @return self - */ - public GraphQLTestTemplate withBasicAuth(@NonNull final String encodedCredentials) { - headers.setBasicAuth(encodedCredentials); - return this; - } - - /** - * @deprecated use {{@link #withHeaders(HttpHeaders)}} instead. - * Replace any associated HTTP headers with the provided headers. - * - * @param newHeaders Headers to use. - */ - @Deprecated - public void setHeaders(HttpHeaders newHeaders) { - withHeaders(newHeaders); - } - - /** - * Replace any associated HTTP headers with the provided headers. - * - * @param newHeaders Headers to use. - * @return self - */ - public GraphQLTestTemplate withHeaders(final HttpHeaders newHeaders) { - return withClearHeaders().withAdditionalHeaders(newHeaders); - } - - /** - * @deprecated use {{@link #withClearHeaders()}} instead - * Clear all associated HTTP headers. - */ - @Deprecated - public void clearHeaders() { - withClearHeaders(); - } - - /** - * Clear all associated HTTP headers. - * @return self - */ - public GraphQLTestTemplate withClearHeaders() { - headers.clear(); - return this; - } - - /** - * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL server. - * - * @deprecated Use {@link #postForResource(String)} instead - * - * @param graphqlResource path to the classpath resource containing the GraphQL query - * @return {@link GraphQLResponse} containing the result of query execution - * @throws IOException if the resource cannot be loaded from the classpath - */ - @Deprecated - public GraphQLResponse perform(String graphqlResource) throws IOException { - return postForResource(graphqlResource); - } - - /** - * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL server. - * - * @param graphqlResource path to the classpath resource containing the GraphQL query - * @param variables the input variables for the GraphQL query - * @return {@link GraphQLResponse} containing the result of query execution - * @throws IOException if the resource cannot be loaded from the classpath - */ - public GraphQLResponse perform(String graphqlResource, ObjectNode variables) throws IOException { - return perform(graphqlResource, null, variables, Collections.emptyList()); - } - - /** - * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL server. - * - * @param graphqlResource path to the classpath resource containing the GraphQL query - * @param operationName the name of the GraphQL operation to be executed - * @return {@link GraphQLResponse} containing the result of query execution - * @throws IOException if the resource cannot be loaded from the classpath - */ - public GraphQLResponse perform(String graphqlResource, String operationName) throws IOException { - return perform(graphqlResource, operationName, null, Collections.emptyList()); - } - - /** - * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL server. - * - * @param graphqlResource path to the classpath resource containing the GraphQL query - * @param operation the name of the GraphQL operation to be executed - * @param variables the input variables for the GraphQL query - * @return {@link GraphQLResponse} containing the result of query execution - * @throws IOException if the resource cannot be loaded from the classpath - */ - public GraphQLResponse perform(String graphqlResource, String operation, ObjectNode variables) throws IOException { - return perform(graphqlResource, operation, variables, Collections.emptyList()); - } - - /** - * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL server. - * - * @param graphqlResource path to the classpath resource containing the GraphQL query - * @param variables the input variables for the GraphQL query - * @param fragmentResources an ordered list of classpath resources containing GraphQL fragment definitions. - * @return {@link GraphQLResponse} containing the result of query execution - * @throws IOException if the resource cannot be loaded from the classpath - */ - public GraphQLResponse perform(String graphqlResource, ObjectNode variables, List fragmentResources) throws IOException { - return perform(graphqlResource, null, variables, fragmentResources); - } - - /** - * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL server. - * - * @param graphqlResource path to the classpath resource containing the GraphQL query - * @param variables the input variables for the GraphQL query - * @param fragmentResources an ordered list of classpath resources containing GraphQL fragment definitions. - * @return {@link GraphQLResponse} containing the result of query execution - * @throws IOException if the resource cannot be loaded from the classpath - */ - public GraphQLResponse perform(String graphqlResource, String operationName, ObjectNode variables, List fragmentResources) throws IOException { - StringBuilder sb = new StringBuilder(); - for (String fragmentResource : fragmentResources) { - sb.append(loadQuery(fragmentResource)); - } - String graphql = sb.append(loadQuery(graphqlResource)).toString(); - String payload = createJsonQuery(graphql, operationName, variables); - return post(payload); - } - - /** - * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL server. - * - * @param graphqlResource path to the classpath resource containing the GraphQL query - * @return {@link GraphQLResponse} containing the result of query execution - * @throws IOException if the resource cannot be loaded from the classpath - */ - public GraphQLResponse postForResource(String graphqlResource) throws IOException { - return perform(graphqlResource, null, null, Collections.emptyList()); - } - - /** - * Loads a GraphQL query or mutation from the given classpath resource, appending any graphql fragment - * resources provided and sends it to the GraphQL server. - * - * @param graphqlResource path to the classpath resource containing the GraphQL query - * @param fragmentResources an ordered list of classpath resources containing GraphQL fragment definitions. - * @return {@link GraphQLResponse} containing the result of query execution - * @throws IOException if the resource cannot be loaded from the classpath - */ - public GraphQLResponse postForResource(String graphqlResource, List fragmentResources) throws IOException { - return perform(graphqlResource, null, null, fragmentResources); - } - - public GraphQLResponse postMultipart(String query, String variables) { - return postRequest(RequestFactory.forMultipart(query, variables, headers)); - } - - /** - * Performs a GraphQL request with the provided payload. - * @param payload the GraphQL payload - * @return @return {@link GraphQLResponse} containing the result of query execution - */ - public GraphQLResponse post(String payload) { - return postRequest(RequestFactory.forJson(payload, headers)); - } - - private GraphQLResponse postRequest(HttpEntity request) { - ResponseEntity response = restTemplate.exchange(graphqlMapping, HttpMethod.POST, request, String.class); - return new GraphQLResponse(response, objectMapper); - } - -} \ No newline at end of file + String graphql = sb.append(loadQuery(graphqlResource)).toString(); + String payload = createJsonQuery(graphql, operationName, variables); + return post(payload); + } + + /** + * Loads a GraphQL query or mutation from the given classpath resource and sends it to the GraphQL + * server. + * + * @param graphqlResource path to the classpath resource containing the GraphQL query + * @return {@link GraphQLResponse} containing the result of query execution + * @throws IOException if the resource cannot be loaded from the classpath + */ + public GraphQLResponse postForResource(String graphqlResource) throws IOException { + return perform(graphqlResource, null, null, Collections.emptyList()); + } + + /** + * Loads a GraphQL query or mutation from the given classpath resource, appending any graphql + * fragment resources provided and sends it to the GraphQL server. + * + * @param graphqlResource path to the classpath resource containing the GraphQL query + * @param fragmentResources an ordered list of classpath resources containing GraphQL fragment + * definitions. + * @return {@link GraphQLResponse} containing the result of query execution + * @throws IOException if the resource cannot be loaded from the classpath + */ + public GraphQLResponse postForResource(String graphqlResource, List fragmentResources) + throws IOException { + return perform(graphqlResource, null, null, fragmentResources); + } + + public GraphQLResponse postMultipart(String query, String variables) { + return postRequest(RequestFactory.forMultipart(query, variables, headers)); + } + + /** + * Performs a GraphQL request with the provided payload. + * + * @param payload the GraphQL payload + * @return @return {@link GraphQLResponse} containing the result of query execution + */ + public GraphQLResponse post(String payload) { + return postRequest(RequestFactory.forJson(payload, headers)); + } + + private GraphQLResponse postRequest(HttpEntity request) { + ResponseEntity response = restTemplate + .exchange(graphqlMapping, HttpMethod.POST, request, String.class); + return new GraphQLResponse(response, objectMapper); + } + +} diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/JacksonFriendlySourceLocation.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/JacksonFriendlySourceLocation.java index 7953e199..6ed73ce1 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/JacksonFriendlySourceLocation.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/JacksonFriendlySourceLocation.java @@ -10,12 +10,12 @@ */ public class JacksonFriendlySourceLocation extends SourceLocation { - @JsonCreator - public JacksonFriendlySourceLocation( - final @JsonProperty("line") int line, - final @JsonProperty("column") int column, - final @Nullable @JsonProperty("sourceName") String sourceName - ) { - super(line, column, sourceName); - } + @JsonCreator + public JacksonFriendlySourceLocation( + final @JsonProperty("line") int line, + final @JsonProperty("column") int column, + final @Nullable @JsonProperty("sourceName") String sourceName + ) { + super(line, column, sourceName); + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/RequestFactory.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/RequestFactory.java index f8388037..2d7de3fc 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/RequestFactory.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/RequestFactory.java @@ -7,21 +7,21 @@ class RequestFactory { - private RequestFactory() { - // utility class - } + private RequestFactory() { + // utility class + } - static HttpEntity forJson(String json, HttpHeaders headers) { - headers.setContentType(MediaType.APPLICATION_JSON_UTF8); - return new HttpEntity<>(json, headers); - } + static HttpEntity forJson(String json, HttpHeaders headers) { + headers.setContentType(MediaType.APPLICATION_JSON_UTF8); + return new HttpEntity<>(json, headers); + } - static HttpEntity forMultipart(String query, String variables, HttpHeaders headers) { - headers.setContentType(MediaType.MULTIPART_FORM_DATA); - LinkedMultiValueMap values = new LinkedMultiValueMap<>(); - values.add("query", forJson(query, new HttpHeaders())); - values.add("variables", forJson(variables, new HttpHeaders())); - return new HttpEntity<>(values, headers); - } + static HttpEntity forMultipart(String query, String variables, HttpHeaders headers) { + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + LinkedMultiValueMap values = new LinkedMultiValueMap<>(); + values.add("query", forJson(query, new HttpHeaders())); + values.add("variables", forJson(variables, new HttpHeaders())); + return new HttpEntity<>(values, headers); + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/SubscriptionState.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/SubscriptionState.java index 8ed3a72c..2251fa2a 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/SubscriptionState.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/SubscriptionState.java @@ -1,25 +1,24 @@ package com.graphql.spring.boot.test; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; - @Data @Builder @NoArgsConstructor @AllArgsConstructor class SubscriptionState { - private boolean initialized; - private boolean acknowledged; - private boolean started; - private boolean stopped; - private boolean completed; - @Builder.Default - private Queue responses = new ConcurrentLinkedQueue<>(); - private int id; + private boolean initialized; + private boolean acknowledged; + private boolean started; + private boolean stopped; + private boolean completed; + @Builder.Default + private Queue responses = new ConcurrentLinkedQueue<>(); + private int id; } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/TestUtils.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/TestUtils.java index d253c4b6..e18709ab 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/TestUtils.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/TestUtils.java @@ -24,7 +24,8 @@ public static Map assertNoGraphQLErrors(GraphQL gql, String quer return assertNoGraphQLErrors(gql, new HashMap<>(), new Object(), query); } - public static Map assertNoGraphQLErrors(GraphQL gql, Map args, Object context, + public static Map assertNoGraphQLErrors(GraphQL gql, Map args, + Object context, String query) { ExecutionResult result = execute(gql, args, context, query); @@ -40,7 +41,8 @@ private static String formatErrors(ExecutionResult result) { return result.getErrors().stream().map(TestUtils::toString).collect(Collectors.joining("\n")); } - private static ExecutionResult execute(GraphQL gql, Map args, Object context, String query) { + private static ExecutionResult execute(GraphQL gql, Map args, Object context, + String query) { return gql.execute(ExecutionInput.newExecutionInput() .query(query) .context(context) @@ -50,16 +52,20 @@ private static ExecutionResult execute(GraphQL gql, Map args, Ob public static void assertGraphQLError(GraphQL gql, String query, GraphQLError error, GraphQLObjectMapper objectMapper) { - ExecutionResult result = objectMapper.sanitizeErrors(execute(gql, new HashMap<>(), new Object(), query)); + ExecutionResult result = objectMapper + .sanitizeErrors(execute(gql, new HashMap<>(), new Object(), query)); String expectedError = toString(error); if (result.getErrors().isEmpty()) { - throw new AssertionError("GraphQL result did not contain any errors!Expected: \n" + expectedError); + throw new AssertionError( + "GraphQL result did not contain any errors!Expected: \n" + expectedError); } - if (result.getErrors().stream().map(TestUtils::toString).noneMatch(e -> e.equals(expectedError))) { + if (result.getErrors().stream().map(TestUtils::toString) + .noneMatch(e -> e.equals(expectedError))) { throw new AssertionError( - "GraphQL result did not contain expected error!\nExpected:" + expectedError + "\nActual:" + formatErrors( + "GraphQL result did not contain expected error!\nExpected:" + expectedError + "\nActual:" + + formatErrors( result)); } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBigDecimalAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBigDecimalAssert.java index 774217e4..5dfe38ef 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBigDecimalAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBigDecimalAssert.java @@ -1,22 +1,21 @@ package com.graphql.spring.boot.test.assertions; import com.graphql.spring.boot.test.GraphQLResponse; -import org.assertj.core.api.AbstractBigDecimalAssert; - import java.math.BigDecimal; +import org.assertj.core.api.AbstractBigDecimalAssert; public class GraphQLBigDecimalAssert extends AbstractBigDecimalAssert implements GraphQLResponseAssertion { - private final GraphQLResponse graphQlResponse; + private final GraphQLResponse graphQlResponse; - public GraphQLBigDecimalAssert(final GraphQLResponse graphQLResponse, final BigDecimal actual) { - super(actual, GraphQLBigDecimalAssert.class); - this.graphQlResponse = graphQLResponse; - } + public GraphQLBigDecimalAssert(final GraphQLResponse graphQLResponse, final BigDecimal actual) { + super(actual, GraphQLBigDecimalAssert.class); + this.graphQlResponse = graphQLResponse; + } - @Override - public GraphQLResponse and() { - return graphQlResponse; - } + @Override + public GraphQLResponse and() { + return graphQlResponse; + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBigIntegerAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBigIntegerAssert.java index 6b2bfa9a..92c3ef53 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBigIntegerAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBigIntegerAssert.java @@ -1,22 +1,21 @@ package com.graphql.spring.boot.test.assertions; import com.graphql.spring.boot.test.GraphQLResponse; -import org.assertj.core.api.AbstractBigIntegerAssert; - import java.math.BigInteger; +import org.assertj.core.api.AbstractBigIntegerAssert; public class GraphQLBigIntegerAssert extends AbstractBigIntegerAssert implements GraphQLResponseAssertion { - private final GraphQLResponse graphQlResponse; + private final GraphQLResponse graphQlResponse; - public GraphQLBigIntegerAssert(final GraphQLResponse graphQLResponse, final BigInteger actual) { - super(actual, GraphQLBigIntegerAssert.class); - this.graphQlResponse = graphQLResponse; - } + public GraphQLBigIntegerAssert(final GraphQLResponse graphQLResponse, final BigInteger actual) { + super(actual, GraphQLBigIntegerAssert.class); + this.graphQlResponse = graphQLResponse; + } - @Override - public GraphQLResponse and() { - return graphQlResponse; - } + @Override + public GraphQLResponse and() { + return graphQlResponse; + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBooleanAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBooleanAssert.java index 201d3986..3c4496a7 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBooleanAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLBooleanAssert.java @@ -6,15 +6,15 @@ public class GraphQLBooleanAssert extends AbstractBooleanAssert implements GraphQLResponseAssertion { - private final GraphQLResponse graphQlResponse; + private final GraphQLResponse graphQlResponse; - public GraphQLBooleanAssert(final GraphQLResponse graphQLResponse, final Boolean actual) { - super(actual, GraphQLBooleanAssert.class); - this.graphQlResponse = graphQLResponse; - } + public GraphQLBooleanAssert(final GraphQLResponse graphQLResponse, final Boolean actual) { + super(actual, GraphQLBooleanAssert.class); + this.graphQlResponse = graphQLResponse; + } - @Override - public GraphQLResponse and() { - return graphQlResponse; - } + @Override + public GraphQLResponse and() { + return graphQlResponse; + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLByteAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLByteAssert.java index d6d72563..002812f4 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLByteAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLByteAssert.java @@ -6,15 +6,15 @@ public class GraphQLByteAssert extends AbstractByteAssert implements GraphQLResponseAssertion { - private final GraphQLResponse graphQlResponse; + private final GraphQLResponse graphQlResponse; - public GraphQLByteAssert(final GraphQLResponse graphQLResponse, final Byte actual) { - super(actual, GraphQLByteAssert.class); - this.graphQlResponse = graphQLResponse; - } + public GraphQLByteAssert(final GraphQLResponse graphQLResponse, final Byte actual) { + super(actual, GraphQLByteAssert.class); + this.graphQlResponse = graphQLResponse; + } - @Override - public GraphQLResponse and() { - return graphQlResponse; - } + @Override + public GraphQLResponse and() { + return graphQlResponse; + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLErrorListAssertion.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLErrorListAssertion.java index d8daf323..dd22a55e 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLErrorListAssertion.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLErrorListAssertion.java @@ -1,58 +1,60 @@ package com.graphql.spring.boot.test.assertions; +import static com.graphql.spring.boot.test.helper.GraphQLTestConstantsHelper.ERRORS_PATH; +import static java.util.Objects.nonNull; +import static org.assertj.core.api.Assertions.fail; + import com.graphql.spring.boot.test.GraphQLResponse; import com.graphql.spring.boot.test.GraphQLTestError; import com.jayway.jsonpath.PathNotFoundException; import graphql.GraphQLError; +import java.util.List; +import java.util.stream.Collectors; import org.assertj.core.api.FactoryBasedNavigableListAssert; import org.assertj.core.api.ObjectAssert; import org.assertj.core.api.ObjectAssertFactory; -import java.util.List; -import java.util.stream.Collectors; - -import static com.graphql.spring.boot.test.helper.GraphQLTestConstantsHelper.ERRORS_PATH; -import static java.util.Objects.nonNull; -import static org.assertj.core.api.Assertions.fail; - public class GraphQLErrorListAssertion extends FactoryBasedNavigableListAssert< - GraphQLErrorListAssertion, - List, - GraphQLError, - ObjectAssert + GraphQLErrorListAssertion, + List, + GraphQLError, + ObjectAssert > - implements GraphQLResponseAssertion -{ - private final GraphQLResponse graphQLResponse; - - public GraphQLErrorListAssertion(final GraphQLResponse graphQLResponse) { - super(getGraphQLErrors(graphQLResponse), GraphQLErrorListAssertion.class, new ObjectAssertFactory<>()); - this.graphQLResponse = graphQLResponse; + implements GraphQLResponseAssertion { + + private final GraphQLResponse graphQLResponse; + + public GraphQLErrorListAssertion(final GraphQLResponse graphQLResponse) { + super(getGraphQLErrors(graphQLResponse), GraphQLErrorListAssertion.class, + new ObjectAssertFactory<>()); + this.graphQLResponse = graphQLResponse; + } + + private static List getGraphQLErrors( + final GraphQLResponse graphQLResponse) { + List errorList = null; + try { + errorList = graphQLResponse.getList(ERRORS_PATH, GraphQLTestError.class); + } catch (PathNotFoundException e) { + // do nothing, error list is still null } - - public GraphQLResponseAssertion hasNoErrors() { - final List graphQLErrors = getGraphQLErrors(graphQLResponse); - if (nonNull(graphQLErrors) && !graphQLErrors.isEmpty()) { - final String combinedMessage = graphQLErrors.stream() - .map(GraphQLError::toString) - .collect(Collectors.joining(System.lineSeparator())); - fail(String.format("Expected no GraphQL errors, but got %s: %s", graphQLErrors.size(), combinedMessage)); - } - return this; - } - - @Override - public GraphQLResponse and() { - return graphQLResponse; + return errorList; + } + + public GraphQLResponseAssertion hasNoErrors() { + final List graphQLErrors = getGraphQLErrors(graphQLResponse); + if (nonNull(graphQLErrors) && !graphQLErrors.isEmpty()) { + final String combinedMessage = graphQLErrors.stream() + .map(GraphQLError::toString) + .collect(Collectors.joining(System.lineSeparator())); + fail(String.format("Expected no GraphQL errors, but got %s: %s", graphQLErrors.size(), + combinedMessage)); } + return this; + } - private static List getGraphQLErrors(final GraphQLResponse graphQLResponse) { - List errorList = null; - try { - errorList = graphQLResponse.getList(ERRORS_PATH, GraphQLTestError.class); - } catch (PathNotFoundException e) { - // do nothing, error list is still null - } - return errorList; - } + @Override + public GraphQLResponse and() { + return graphQLResponse; + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLFieldAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLFieldAssert.java index 9ef1b80e..1c5620b2 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLFieldAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLFieldAssert.java @@ -1,17 +1,16 @@ package com.graphql.spring.boot.test.assertions; +import static java.util.Objects.nonNull; +import static org.assertj.core.api.Assertions.fail; + import com.fasterxml.jackson.databind.JavaType; import com.graphql.spring.boot.test.GraphQLResponse; import com.jayway.jsonpath.PathNotFoundException; -import lombok.RequiredArgsConstructor; - import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.Objects; - -import static java.util.Objects.nonNull; -import static org.assertj.core.api.Assertions.fail; +import lombok.RequiredArgsConstructor; /** * Provides fluent assertions for a field (specified by a json path) of the GraphQL response. @@ -19,226 +18,258 @@ @RequiredArgsConstructor public class GraphQLFieldAssert implements GraphQLResponseAssertion { - private final GraphQLResponse graphQLResponse; - private final String jsonPath; - - /** - * Asserts that the field specified by the provided JSON path is not present in the response. - * @throws AssertionError if the field is present in the response - * @return self - */ - public GraphQLFieldAssert isNotPresent() { - try { - graphQLResponse.getRaw(jsonPath); - fail("Expected that field %s is not present.", jsonPath); - } catch (PathNotFoundException e) { - // test passed - } - return this; - } + private final GraphQLResponse graphQLResponse; + private final String jsonPath; - /** - * Asserts that the field specified by the provided JSON path is not present in the response or its value is null. - * @throws AssertionError if the field is present in the response and its value is not null. - * @return self - */ - public GraphQLFieldAssert isNotPresentOrNull() { - try { - if (nonNull(graphQLResponse.getRaw(jsonPath))) { - fail("Expected field %s to be null or not present.", jsonPath); - } - } catch (PathNotFoundException e) { - // test passed - } - return this; + /** + * Asserts that the field specified by the provided JSON path is not present in the response. + * + * @return self + * @throws AssertionError if the field is present in the response + */ + public GraphQLFieldAssert isNotPresent() { + try { + graphQLResponse.getRaw(jsonPath); + fail("Expected that field %s is not present.", jsonPath); + } catch (PathNotFoundException e) { + // test passed } + return this; + } - /** - * Asserts that the field specified by the provided JSON path is null. - * @throws AssertionError if the field is not present in the response or its value is not null. - * @return self - */ - public GraphQLFieldAssert isNull() { - try { - if(nonNull(graphQLResponse.getRaw(jsonPath))) { - fail("Expected field %s to be null.", jsonPath); - } - } catch (PathNotFoundException e) { - fail(String.format("Expected field %s to be present.", jsonPath), e); - } - return this; + /** + * Asserts that the field specified by the provided JSON path is not present in the response or + * its value is null. + * + * @return self + * @throws AssertionError if the field is present in the response and its value is not null. + */ + public GraphQLFieldAssert isNotPresentOrNull() { + try { + if (nonNull(graphQLResponse.getRaw(jsonPath))) { + fail("Expected field %s to be null or not present.", jsonPath); + } + } catch (PathNotFoundException e) { + // test passed } + return this; + } - /** - * Asserts that the field specified by the provided JSON path is not null. - * @throws AssertionError if the field is not present in the response or its value is null. - * @return self - */ - public GraphQLFieldAssert isNotNull() { - try { - if (Objects.isNull(graphQLResponse.getRaw(jsonPath))) { - fail("Expected field %s to be non-null.", jsonPath); - } - } catch (PathNotFoundException e) { - fail(String.format("Expected field %s to be present.", jsonPath), e); - } - return this; + /** + * Asserts that the field specified by the provided JSON path is null. + * + * @return self + * @throws AssertionError if the field is not present in the response or its value is not null. + */ + public GraphQLFieldAssert isNull() { + try { + if (nonNull(graphQLResponse.getRaw(jsonPath))) { + fail("Expected field %s to be null.", jsonPath); + } + } catch (PathNotFoundException e) { + fail(String.format("Expected field %s to be present.", jsonPath), e); } + return this; + } - /** - * Returns an assertion for the content of the field as {@link BigDecimal}. - * @return a {@link GraphQLBigDecimalAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to {@link BigDecimal} - */ - public GraphQLBigDecimalAssert asBigDecimal() { - return new GraphQLBigDecimalAssert(graphQLResponse, getFieldAs(BigDecimal.class)); + /** + * Asserts that the field specified by the provided JSON path is not null. + * + * @return self + * @throws AssertionError if the field is not present in the response or its value is null. + */ + public GraphQLFieldAssert isNotNull() { + try { + if (Objects.isNull(graphQLResponse.getRaw(jsonPath))) { + fail("Expected field %s to be non-null.", jsonPath); + } + } catch (PathNotFoundException e) { + fail(String.format("Expected field %s to be present.", jsonPath), e); } + return this; + } - /** - * Returns an assertion for the content of the field as {@link BigInteger}. - * @return a {@link GraphQLBigIntegerAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to {@link BigInteger} - */ - public GraphQLBigIntegerAssert asBigInteger() { - return new GraphQLBigIntegerAssert(graphQLResponse, getFieldAs(BigInteger.class)); - } + /** + * Returns an assertion for the content of the field as {@link BigDecimal}. + * + * @return a {@link GraphQLBigDecimalAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to + * {@link BigDecimal} + */ + public GraphQLBigDecimalAssert asBigDecimal() { + return new GraphQLBigDecimalAssert(graphQLResponse, getFieldAs(BigDecimal.class)); + } - /** - * Returns an assertion for the content of the field as {@link Long}. - * @return a {@link GraphQLLongAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to {@link Long} - */ - public GraphQLLongAssert asLong() { - return new GraphQLLongAssert(graphQLResponse, getFieldAs(Long.class)); - } + /** + * Returns an assertion for the content of the field as {@link BigInteger}. + * + * @return a {@link GraphQLBigIntegerAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to + * {@link BigInteger} + */ + public GraphQLBigIntegerAssert asBigInteger() { + return new GraphQLBigIntegerAssert(graphQLResponse, getFieldAs(BigInteger.class)); + } - /** - * Returns an assertion for the content of the field as {@link Integer}. - * @return a {@link GraphQLIntegerAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to {@link Integer} - */ - public GraphQLIntegerAssert asInteger() { - return new GraphQLIntegerAssert(graphQLResponse, getFieldAs(Integer.class)); - } + /** + * Returns an assertion for the content of the field as {@link Long}. + * + * @return a {@link GraphQLLongAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to + * {@link Long} + */ + public GraphQLLongAssert asLong() { + return new GraphQLLongAssert(graphQLResponse, getFieldAs(Long.class)); + } - /** - * Returns an assertion for the content of the field as {@link Short}. - * @return a {@link GraphQLShortAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to {@link Short} - */ - public GraphQLShortAssert asShort() { - return new GraphQLShortAssert(graphQLResponse, getFieldAs(Short.class)); - } + /** + * Returns an assertion for the content of the field as {@link Integer}. + * + * @return a {@link GraphQLIntegerAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to + * {@link Integer} + */ + public GraphQLIntegerAssert asInteger() { + return new GraphQLIntegerAssert(graphQLResponse, getFieldAs(Integer.class)); + } - /** - * Returns an assertion for the content of the field as {@link Byte}. - * @return a {@link GraphQLByteAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to {@link Byte} - */ - public GraphQLByteAssert asByte() { - return new GraphQLByteAssert(graphQLResponse, getFieldAs(Byte.class)); - } + /** + * Returns an assertion for the content of the field as {@link Short}. + * + * @return a {@link GraphQLShortAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to + * {@link Short} + */ + public GraphQLShortAssert asShort() { + return new GraphQLShortAssert(graphQLResponse, getFieldAs(Short.class)); + } - /** - * Returns an assertion for the content of the field as {@link Boolean}. - * @return a {@link GraphQLBooleanAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to {@link Boolean} - */ - public GraphQLBooleanAssert asBoolean() { - return new GraphQLBooleanAssert(graphQLResponse, getFieldAs(Boolean.class)); - } + /** + * Returns an assertion for the content of the field as {@link Byte}. + * + * @return a {@link GraphQLByteAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to + * {@link Byte} + */ + public GraphQLByteAssert asByte() { + return new GraphQLByteAssert(graphQLResponse, getFieldAs(Byte.class)); + } - /** - * Returns an assertion for the content of the field as {@link String}. - * @return a {@link GraphQLStringAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to {@link String} - */ - public GraphQLStringAssert asString() { - return new GraphQLStringAssert(graphQLResponse, getFieldAs(String.class)); - } + /** + * Returns an assertion for the content of the field as {@link Boolean}. + * + * @return a {@link GraphQLBooleanAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to + * {@link Boolean} + */ + public GraphQLBooleanAssert asBoolean() { + return new GraphQLBooleanAssert(graphQLResponse, getFieldAs(Boolean.class)); + } - /** - * Returns an assertion for the content of the field as an instance of the specified class. - * @param clazz The class of the object. to assert - * @return a {@link GraphQLGenericObjectAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to the specified class - */ - public GraphQLGenericObjectAssert as(final Class clazz) { - return new GraphQLGenericObjectAssert<>(graphQLResponse, getFieldAs(clazz)); - } + /** + * Returns an assertion for the content of the field as {@link String}. + * + * @return a {@link GraphQLStringAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to + * {@link String} + */ + public GraphQLStringAssert asString() { + return new GraphQLStringAssert(graphQLResponse, getFieldAs(String.class)); + } - /** - * Returns an assertion for the content of the field as an instance of the specified type. - * @param javaType The java type definition. - * @return a {@link GraphQLGenericObjectAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to the specified class - */ - public GraphQLGenericObjectAssert as(final JavaType javaType) { - return new GraphQLGenericObjectAssert<>(graphQLResponse, getFieldAs(javaType)); - } + /** + * Returns an assertion for the content of the field as an instance of the specified class. + * + * @param clazz The class of the object. to assert + * @return a {@link GraphQLGenericObjectAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to the + * specified class + */ + public GraphQLGenericObjectAssert as(final Class clazz) { + return new GraphQLGenericObjectAssert<>(graphQLResponse, getFieldAs(clazz)); + } - /** - * Returns an assertion for the content of the field as an instance of the specified list type. - * @param javaListType The java type definition. Expected to define a list type. - * @return a {@link GraphQLListAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to the specified class - * or if the provided type is not a list type. - */ - public GraphQLListAssert asList(final JavaType javaListType) { - return new GraphQLListAssert<>(graphQLResponse, getFieldAs(javaListType)); - } + /** + * Returns an assertion for the content of the field as an instance of the specified type. + * + * @param javaType The java type definition. + * @return a {@link GraphQLGenericObjectAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to the + * specified class + */ + public GraphQLGenericObjectAssert as(final JavaType javaType) { + return new GraphQLGenericObjectAssert<>(graphQLResponse, getFieldAs(javaType)); + } - /** - * Returns an assertion for the content of the field as list of objects. - * @param elementClass the type of objects in the list - * @return a {@link GraphQLGenericObjectAssert} instance - * @throws AssertionError if the path does not exist or the content could not be converted to the specified class - */ - public GraphQLListAssert asListOf(final Class elementClass) { - return new GraphQLListAssert<>(graphQLResponse, getFieldAsList(elementClass)); - } + /** + * Returns an assertion for the content of the field as an instance of the specified list type. + * + * @param javaListType The java type definition. Expected to define a list type. + * @return a {@link GraphQLListAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to the + * specified class or if the provided type is not a list type. + */ + public GraphQLListAssert asList(final JavaType javaListType) { + return new GraphQLListAssert<>(graphQLResponse, getFieldAs(javaListType)); + } - /** - * {@inheritDoc} - */ - @Override - public GraphQLResponse and() { - return graphQLResponse; - } + /** + * Returns an assertion for the content of the field as list of objects. + * + * @param elementClass the type of objects in the list + * @return a {@link GraphQLGenericObjectAssert} instance + * @throws AssertionError if the path does not exist or the content could not be converted to the + * specified class + */ + public GraphQLListAssert asListOf(final Class elementClass) { + return new GraphQLListAssert<>(graphQLResponse, getFieldAsList(elementClass)); + } + + /** + * {@inheritDoc} + */ + @Override + public GraphQLResponse and() { + return graphQLResponse; + } - private T getFieldAs(final Class targetClass) { - try { - return graphQLResponse.get(jsonPath, targetClass); - } catch (PathNotFoundException e) { - fail(String.format("Expected field %s to be present.", jsonPath), e); - return null; - } catch (IllegalArgumentException e) { - fail(String.format("Expected that content of field %s can be converted to %s.", jsonPath, targetClass), e); - return null; - } + private T getFieldAs(final Class targetClass) { + try { + return graphQLResponse.get(jsonPath, targetClass); + } catch (PathNotFoundException e) { + fail(String.format("Expected field %s to be present.", jsonPath), e); + return null; + } catch (IllegalArgumentException e) { + fail(String.format("Expected that content of field %s can be converted to %s.", jsonPath, + targetClass), e); + return null; } + } - private T getFieldAs(final JavaType javaType) { - try { - return graphQLResponse.get(jsonPath, javaType); - } catch (PathNotFoundException e) { - fail(String.format("Expected field %s to be present.", jsonPath), e); - return null; - } catch (IllegalArgumentException e) { - fail(String.format("Expected that content of field %s can be converted to %s.", jsonPath, javaType), e); - return null; - } + private T getFieldAs(final JavaType javaType) { + try { + return graphQLResponse.get(jsonPath, javaType); + } catch (PathNotFoundException e) { + fail(String.format("Expected field %s to be present.", jsonPath), e); + return null; + } catch (IllegalArgumentException e) { + fail(String + .format("Expected that content of field %s can be converted to %s.", jsonPath, javaType), + e); + return null; } + } - private List getFieldAsList(final Class targetClass) { - try { - return graphQLResponse.getList(jsonPath, targetClass); - } catch (PathNotFoundException e) { - fail(String.format("Expected field %s to be present.", jsonPath), e); - return null; - } catch (IllegalArgumentException e) { - fail(String.format("Expected that content of field %s can be converted to %s.", jsonPath, targetClass), e); - return null; - } + private List getFieldAsList(final Class targetClass) { + try { + return graphQLResponse.getList(jsonPath, targetClass); + } catch (PathNotFoundException e) { + fail(String.format("Expected field %s to be present.", jsonPath), e); + return null; + } catch (IllegalArgumentException e) { + fail(String.format("Expected that content of field %s can be converted to %s.", jsonPath, + targetClass), e); + return null; } + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLGenericObjectAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLGenericObjectAssert.java index a3ac4d26..a0194c69 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLGenericObjectAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLGenericObjectAssert.java @@ -7,15 +7,15 @@ public class GraphQLGenericObjectAssert extends AbstractObjectAssert, T> implements GraphQLResponseAssertion { - private final GraphQLResponse graphQLResponse; + private final GraphQLResponse graphQLResponse; - public GraphQLGenericObjectAssert(final GraphQLResponse graphQLResponse, final T actual) { - super(actual, GraphQLGenericObjectAssert.class); - this.graphQLResponse = graphQLResponse; - } + public GraphQLGenericObjectAssert(final GraphQLResponse graphQLResponse, final T actual) { + super(actual, GraphQLGenericObjectAssert.class); + this.graphQLResponse = graphQLResponse; + } - @Override - public GraphQLResponse and() { - return graphQLResponse; - } + @Override + public GraphQLResponse and() { + return graphQLResponse; + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLIntegerAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLIntegerAssert.java index 66f31bee..bc80221a 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLIntegerAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLIntegerAssert.java @@ -2,20 +2,19 @@ import com.graphql.spring.boot.test.GraphQLResponse; import org.assertj.core.api.AbstractIntegerAssert; -import org.assertj.core.api.AbstractLongAssert; public class GraphQLIntegerAssert extends AbstractIntegerAssert implements GraphQLResponseAssertion { - private final GraphQLResponse graphQlResponse; + private final GraphQLResponse graphQlResponse; - public GraphQLIntegerAssert(final GraphQLResponse graphQLResponse, final Integer actual) { - super(actual, GraphQLIntegerAssert.class); - this.graphQlResponse = graphQLResponse; - } + public GraphQLIntegerAssert(final GraphQLResponse graphQLResponse, final Integer actual) { + super(actual, GraphQLIntegerAssert.class); + this.graphQlResponse = graphQLResponse; + } - @Override - public GraphQLResponse and() { - return graphQlResponse; - } + @Override + public GraphQLResponse and() { + return graphQlResponse; + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLListAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLListAssert.java index 3d27388d..c1e53f3d 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLListAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLListAssert.java @@ -1,12 +1,11 @@ package com.graphql.spring.boot.test.assertions; import com.graphql.spring.boot.test.GraphQLResponse; +import java.util.List; import org.assertj.core.api.FactoryBasedNavigableListAssert; import org.assertj.core.api.ObjectAssert; import org.assertj.core.api.ObjectAssertFactory; -import java.util.List; - public class GraphQLListAssert extends FactoryBasedNavigableListAssert< GraphQLListAssert, List, @@ -15,15 +14,15 @@ public class GraphQLListAssert extends FactoryBasedNavigableListAssert< > implements GraphQLResponseAssertion { - private final GraphQLResponse graphQlResponse; + private final GraphQLResponse graphQlResponse; - public GraphQLListAssert(final GraphQLResponse graphQLResponse, final List actual) { - super(actual, GraphQLListAssert.class, new ObjectAssertFactory<>()); - this.graphQlResponse = graphQLResponse; - } + public GraphQLListAssert(final GraphQLResponse graphQLResponse, final List actual) { + super(actual, GraphQLListAssert.class, new ObjectAssertFactory<>()); + this.graphQlResponse = graphQLResponse; + } - @Override - public GraphQLResponse and() { - return graphQlResponse; - } -} \ No newline at end of file + @Override + public GraphQLResponse and() { + return graphQlResponse; + } +} diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLLongAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLLongAssert.java index 183f945e..12316d85 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLLongAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLLongAssert.java @@ -6,15 +6,15 @@ public class GraphQLLongAssert extends AbstractLongAssert implements GraphQLResponseAssertion { - private final GraphQLResponse graphQlResponse; + private final GraphQLResponse graphQlResponse; - public GraphQLLongAssert(final GraphQLResponse graphQLResponse, final Long actual) { - super(actual, GraphQLLongAssert.class); - this.graphQlResponse = graphQLResponse; - } + public GraphQLLongAssert(final GraphQLResponse graphQLResponse, final Long actual) { + super(actual, GraphQLLongAssert.class); + this.graphQlResponse = graphQLResponse; + } - @Override - public GraphQLResponse and() { - return graphQlResponse; - } + @Override + public GraphQLResponse and() { + return graphQlResponse; + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLResponseAssertion.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLResponseAssertion.java index 24dd59ad..2d4b0dc5 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLResponseAssertion.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLResponseAssertion.java @@ -3,14 +3,14 @@ import com.graphql.spring.boot.test.GraphQLResponse; /** - * Common interface for GraphQL assertions. The main purpose of this interface is to allow chaining fluent assertions - * for a {@link GraphQLResponse}. + * Common interface for GraphQL assertions. The main purpose of this interface is to allow chaining + * fluent assertions for a {@link GraphQLResponse}. */ public interface GraphQLResponseAssertion { - /** - * @return the instance of {@link GraphQLResponse} for which this assertion was created. Allows chaining fluent - * assertions. - */ - GraphQLResponse and(); + /** + * @return the instance of {@link GraphQLResponse} for which this assertion was created. Allows + * chaining fluent assertions. + */ + GraphQLResponse and(); } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLShortAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLShortAssert.java index 9200be20..373e698e 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLShortAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLShortAssert.java @@ -1,22 +1,20 @@ package com.graphql.spring.boot.test.assertions; import com.graphql.spring.boot.test.GraphQLResponse; -import org.assertj.core.api.AbstractIntegerAssert; -import org.assertj.core.api.AbstractShortArrayAssert; import org.assertj.core.api.AbstractShortAssert; public class GraphQLShortAssert extends AbstractShortAssert implements GraphQLResponseAssertion { - private final GraphQLResponse graphQlResponse; + private final GraphQLResponse graphQlResponse; - public GraphQLShortAssert(final GraphQLResponse graphQLResponse, final Short actual) { - super(actual, GraphQLShortAssert.class); - this.graphQlResponse = graphQLResponse; - } + public GraphQLShortAssert(final GraphQLResponse graphQLResponse, final Short actual) { + super(actual, GraphQLShortAssert.class); + this.graphQlResponse = graphQLResponse; + } - @Override - public GraphQLResponse and() { - return graphQlResponse; - } + @Override + public GraphQLResponse and() { + return graphQlResponse; + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLStringAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLStringAssert.java index e08bcade..8643be46 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLStringAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLStringAssert.java @@ -6,15 +6,15 @@ public class GraphQLStringAssert extends AbstractStringAssert implements GraphQLResponseAssertion { - private final GraphQLResponse graphQlResponse; + private final GraphQLResponse graphQlResponse; - public GraphQLStringAssert(final GraphQLResponse graphQLResponse, final String actual) { - super(actual, GraphQLStringAssert.class); - this.graphQlResponse = graphQLResponse; - } + public GraphQLStringAssert(final GraphQLResponse graphQLResponse, final String actual) { + super(actual, GraphQLStringAssert.class); + this.graphQlResponse = graphQLResponse; + } - @Override - public GraphQLResponse and() { - return graphQlResponse; - } + @Override + public GraphQLResponse and() { + return graphQlResponse; + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/NumberOfErrorsAssertion.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/NumberOfErrorsAssertion.java index c460ef48..24563c5e 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/NumberOfErrorsAssertion.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/NumberOfErrorsAssertion.java @@ -1,42 +1,41 @@ package com.graphql.spring.boot.test.assertions; +import static com.graphql.spring.boot.test.helper.GraphQLTestConstantsHelper.ERRORS_PATH; +import static java.util.Objects.nonNull; + import com.graphql.spring.boot.test.GraphQLResponse; import com.graphql.spring.boot.test.GraphQLTestError; import com.jayway.jsonpath.PathNotFoundException; -import lombok.Getter; -import org.assertj.core.api.AbstractIntegerAssert; - import java.util.List; - -import static com.graphql.spring.boot.test.helper.GraphQLTestConstantsHelper.ERRORS_PATH; -import static java.util.Objects.nonNull; +import org.assertj.core.api.AbstractIntegerAssert; public class NumberOfErrorsAssertion extends AbstractIntegerAssert implements GraphQLResponseAssertion { - private final GraphQLResponse graphQLResponse; - - public NumberOfErrorsAssertion(final GraphQLResponse response) { - super(getNumberOfErrors(response), NumberOfErrorsAssertion.class); - graphQLResponse = response; + private final GraphQLResponse graphQLResponse; + + public NumberOfErrorsAssertion(final GraphQLResponse response) { + super(getNumberOfErrors(response), NumberOfErrorsAssertion.class); + graphQLResponse = response; + } + + private static Integer getNumberOfErrors(final GraphQLResponse response) { + int numErrors = 0; + try { + final List errorList = response + .getList(ERRORS_PATH, GraphQLTestError.class); + if (nonNull(errorList)) { + numErrors = errorList.size(); + } + } catch (PathNotFoundException e) { + // do nothing, number of errors is zero } + return numErrors; + } - @Override - public GraphQLResponse and() { - return graphQLResponse; - } - - private static Integer getNumberOfErrors(final GraphQLResponse response) { - int numErrors = 0; - try { - final List errorList = response.getList(ERRORS_PATH, GraphQLTestError.class); - if(nonNull(errorList)) { - numErrors = errorList.size(); - } - } catch (PathNotFoundException e) { - // do nothing, number of errors is zero - } - return numErrors; - } + @Override + public GraphQLResponse and() { + return graphQLResponse; + } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/helper/GraphQLTestConstantsHelper.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/helper/GraphQLTestConstantsHelper.java index 245fbcbf..bdb55db6 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/helper/GraphQLTestConstantsHelper.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/helper/GraphQLTestConstantsHelper.java @@ -2,11 +2,11 @@ public final class GraphQLTestConstantsHelper { - public static final String ERRORS_PATH = "$.errors"; - public static final String DATA_PATH = "$.data"; - public static final String EXTENSIONS_PATH = "$.extensions"; + public static final String ERRORS_PATH = "$.errors"; + public static final String DATA_PATH = "$.data"; + public static final String EXTENSIONS_PATH = "$.extensions"; - private GraphQLTestConstantsHelper() { + private GraphQLTestConstantsHelper() { - } + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotNullTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotNullTest.java index 3e443ab0..3dcedf1e 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotNullTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotNullTest.java @@ -1,51 +1,54 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.jayway.jsonpath.PathNotFoundException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLAssertIsNotNullTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should pass if the value at the provided path is not null.") - void shouldPassIfIsNotNull() { - // GIVEN - given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(NON_NULL_VALUE); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatCode(graphQLFieldAssert::isNotNull).doesNotThrowAnyException(); - assertThat(graphQLFieldAssert.isNotNull().and()).isSameAs(graphQLResponse); - } + @Test + @DisplayName("Should pass if the value at the provided path is not null.") + void shouldPassIfIsNotNull() { + // GIVEN + given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(NON_NULL_VALUE); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatCode(graphQLFieldAssert::isNotNull).doesNotThrowAnyException(); + assertThat(graphQLFieldAssert.isNotNull().and()).isSameAs(graphQLResponse); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::isNotNull) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::isNotNull) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path is null.") - void shouldFailIfIsNotNull() { - // GIVEN - given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::isNotNull) - .withMessage("Expected field %s to be non-null.", MOCK_PATH); - } + @Test + @DisplayName("Should fail if the value at the provided path is null.") + void shouldFailIfIsNotNull() { + // GIVEN + given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::isNotNull) + .withMessage("Expected field %s to be non-null.", MOCK_PATH); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotPresentOrNullTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotPresentOrNullTest.java index 7c4add91..98e92a07 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotPresentOrNullTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotPresentOrNullTest.java @@ -1,49 +1,52 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.jayway.jsonpath.PathNotFoundException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLAssertIsNotPresentOrNullTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should pass if the provided path is not present.") - void shouldPassIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatCode(graphQLFieldAssert::isNotPresentOrNull).doesNotThrowAnyException(); - assertThat(graphQLFieldAssert.isNotPresentOrNull().and()).isSameAs(graphQLResponse); - } + @Test + @DisplayName("Should pass if the provided path is not present.") + void shouldPassIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatCode(graphQLFieldAssert::isNotPresentOrNull).doesNotThrowAnyException(); + assertThat(graphQLFieldAssert.isNotPresentOrNull().and()).isSameAs(graphQLResponse); + } - @Test - @DisplayName("Should pass if the value at the provided path is null.") - void shouldPassIfIsNull() { - // GIVEN - given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatCode(graphQLFieldAssert::isNotPresentOrNull).doesNotThrowAnyException(); - assertThat(graphQLFieldAssert.isNotPresentOrNull().and()).isSameAs(graphQLResponse); - } + @Test + @DisplayName("Should pass if the value at the provided path is null.") + void shouldPassIfIsNull() { + // GIVEN + given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatCode(graphQLFieldAssert::isNotPresentOrNull).doesNotThrowAnyException(); + assertThat(graphQLFieldAssert.isNotPresentOrNull().and()).isSameAs(graphQLResponse); + } - @Test - @DisplayName("Should fail if the value at the provided path is not null.") - void shouldFailIfIsNotNull() { - // GIVEN - given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(NON_NULL_VALUE); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::isNotPresentOrNull) - .withMessage("Expected field %s to be null or not present.", MOCK_PATH); - } + @Test + @DisplayName("Should fail if the value at the provided path is not null.") + void shouldFailIfIsNotNull() { + // GIVEN + given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(NON_NULL_VALUE); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::isNotPresentOrNull) + .withMessage("Expected field %s to be null or not present.", MOCK_PATH); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigDecimalTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigDecimalTest.java index d0e78fe7..5a6c2c78 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigDecimalTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigDecimalTest.java @@ -1,74 +1,78 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLBigDecimalAssert; import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.jayway.jsonpath.PathNotFoundException; +import java.math.BigDecimal; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import java.math.BigDecimal; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsBigDecimalTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should return a big decimal assertion (value at specific path is valid number).") - void shouldReturnBigDecimalAssertIfFieldIsNonNull() { - // GIVEN - final BigDecimal value = new BigDecimal("1.23"); - given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLBigDecimalAssert actual = graphQLFieldAssert.asBigDecimal(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(value); - } + @Test + @DisplayName("Should return a big decimal assertion (value at specific path is valid number).") + void shouldReturnBigDecimalAssertIfFieldIsNonNull() { + // GIVEN + final BigDecimal value = new BigDecimal("1.23"); + given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willReturn(value); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLBigDecimalAssert actual = graphQLFieldAssert.asBigDecimal(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(value); + } - @Test - @DisplayName("Should return a big decimal assertion (value at specific path is null).") - void shouldReturnBigDecimalAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLBigDecimalAssert actual = graphQLFieldAssert.asBigDecimal(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a big decimal assertion (value at specific path is null).") + void shouldReturnBigDecimalAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLBigDecimalAssert actual = graphQLFieldAssert.asBigDecimal(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asBigDecimal) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asBigDecimal) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asBigDecimal) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - BigDecimal.class) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asBigDecimal) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + BigDecimal.class) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigIntegerTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigIntegerTest.java index d7eca6d2..190d0e7a 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigIntegerTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigIntegerTest.java @@ -1,74 +1,78 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLBigIntegerAssert; import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.jayway.jsonpath.PathNotFoundException; +import java.math.BigInteger; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import java.math.BigInteger; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsBigIntegerTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should return a big integer assertion (value at specific path is valid number).") - void shouldReturnBigIntegerAssertIfFieldIsNonNull() { - // GIVEN - final BigInteger value = new BigInteger("123"); - given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLBigIntegerAssert actual = graphQLFieldAssert.asBigInteger(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(value); - } + @Test + @DisplayName("Should return a big integer assertion (value at specific path is valid number).") + void shouldReturnBigIntegerAssertIfFieldIsNonNull() { + // GIVEN + final BigInteger value = new BigInteger("123"); + given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willReturn(value); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLBigIntegerAssert actual = graphQLFieldAssert.asBigInteger(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(value); + } - @Test - @DisplayName("Should return a big integer assertion (value at specific path is null).") - void shouldReturnBigIntegerAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLBigIntegerAssert actual = graphQLFieldAssert.asBigInteger(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a big integer assertion (value at specific path is null).") + void shouldReturnBigIntegerAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLBigIntegerAssert actual = graphQLFieldAssert.asBigInteger(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asBigInteger) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asBigInteger) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asBigInteger) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - BigInteger.class) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asBigInteger) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + BigInteger.class) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBooleanTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBooleanTest.java index 49fea025..4847908f 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBooleanTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBooleanTest.java @@ -1,71 +1,76 @@ package com.graphql.spring.boot.test; -import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLBooleanAssert; +import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.jayway.jsonpath.PathNotFoundException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsBooleanTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should return a Boolean assertion (value at specific path is valid Boolean value).") - void shouldReturnBooleanAssertIfFieldIsNonNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willReturn(true); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLBooleanAssert actual = graphQLFieldAssert.asBoolean(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.isTrue().and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(true); - } + @Test + @DisplayName("Should return a Boolean assertion (value at specific path is valid Boolean value).") + void shouldReturnBooleanAssertIfFieldIsNonNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willReturn(true); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLBooleanAssert actual = graphQLFieldAssert.asBoolean(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.isTrue().and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(true); + } - @Test - @DisplayName("Should return a Boolean assertion (value at specific path is null).") - void shouldReturnBooleanAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLBooleanAssert actual = graphQLFieldAssert.asBoolean(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a Boolean assertion (value at specific path is null).") + void shouldReturnBooleanAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLBooleanAssert actual = graphQLFieldAssert.asBoolean(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asBoolean) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asBoolean) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asBoolean) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Boolean.class) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asBoolean) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + Boolean.class) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsByteTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsByteTest.java index 61a860bb..35b8969b 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsByteTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsByteTest.java @@ -1,72 +1,77 @@ package com.graphql.spring.boot.test; -import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLByteAssert; +import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.jayway.jsonpath.PathNotFoundException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsByteTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should return a Byte assertion (value at specific path is valid Byte value).") - void shouldReturnByteAssertIfFieldIsNonNull() { - // GIVEN - final Byte value = 123; - given(graphQLResponse.get(MOCK_PATH, Byte.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLByteAssert actual = graphQLFieldAssert.asByte(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(value); - } + @Test + @DisplayName("Should return a Byte assertion (value at specific path is valid Byte value).") + void shouldReturnByteAssertIfFieldIsNonNull() { + // GIVEN + final Byte value = 123; + given(graphQLResponse.get(MOCK_PATH, Byte.class)).willReturn(value); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLByteAssert actual = graphQLFieldAssert.asByte(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(value); + } - @Test - @DisplayName("Should return a Byte assertion (value at specific path is null).") - void shouldReturnByteAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Byte.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLByteAssert actual = graphQLFieldAssert.asByte(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a Byte assertion (value at specific path is null).") + void shouldReturnByteAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Byte.class)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLByteAssert actual = graphQLFieldAssert.asByte(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Byte.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asByte) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Byte.class)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asByte) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Byte.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asByte) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Byte.class) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Byte.class)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asByte) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + Byte.class) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsIntegerTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsIntegerTest.java index 1aa3998a..5847035e 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsIntegerTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsIntegerTest.java @@ -1,5 +1,9 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.graphql.spring.boot.test.assertions.GraphQLIntegerAssert; import com.jayway.jsonpath.PathNotFoundException; @@ -7,66 +11,67 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsIntegerTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should return a Integer assertion (value at specific path is valid Integer value).") - void shouldReturnIntegerAssertIfFieldIsNonNull() { - // GIVEN - final Integer value = 123; - given(graphQLResponse.get(MOCK_PATH, Integer.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLIntegerAssert actual = graphQLFieldAssert.asInteger(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(value); - } + @Test + @DisplayName("Should return a Integer assertion (value at specific path is valid Integer value).") + void shouldReturnIntegerAssertIfFieldIsNonNull() { + // GIVEN + final Integer value = 123; + given(graphQLResponse.get(MOCK_PATH, Integer.class)).willReturn(value); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLIntegerAssert actual = graphQLFieldAssert.asInteger(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(value); + } - @Test - @DisplayName("Should return a Integer assertion (value at specific path is null).") - void shouldReturnIntegerAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Integer.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLIntegerAssert actual = graphQLFieldAssert.asInteger(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a Integer assertion (value at specific path is null).") + void shouldReturnIntegerAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Integer.class)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLIntegerAssert actual = graphQLFieldAssert.asInteger(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Integer.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asInteger) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Integer.class)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asInteger) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Integer.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asInteger) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Integer.class) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Integer.class)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asInteger) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + Integer.class) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaListTypeTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaListTypeTest.java index 9940c7fb..4a926817 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaListTypeTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaListTypeTest.java @@ -1,80 +1,84 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.type.TypeFactory; import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.graphql.spring.boot.test.assertions.GraphQLListAssert; import com.jayway.jsonpath.PathNotFoundException; +import java.util.Arrays; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import java.util.Arrays; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsJavaListTypeTest extends GraphQLFieldAssertTestBase { - private static final JavaType STRING_LIST_TYPE = TypeFactory.defaultInstance() - .constructCollectionLikeType(List.class, String.class); + private static final JavaType STRING_LIST_TYPE = TypeFactory.defaultInstance() + .constructCollectionLikeType(List.class, String.class); - @Test - @DisplayName("Should return a String list assertion (value at specific path is valid list).") - void shouldReturnStringListAssertIfFieldIsNonNull() { - // GIVEN - final List values = Arrays.asList("value1", "value2"); - given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willReturn(values); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLListAssert actual = graphQLFieldAssert.asList(STRING_LIST_TYPE); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.containsExactlyElementsOf(values).and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(values); - } + @Test + @DisplayName("Should return a String list assertion (value at specific path is valid list).") + void shouldReturnStringListAssertIfFieldIsNonNull() { + // GIVEN + final List values = Arrays.asList("value1", "value2"); + given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willReturn(values); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLListAssert actual = graphQLFieldAssert.asList(STRING_LIST_TYPE); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.containsExactlyElementsOf(values).and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(values); + } - @Test - @DisplayName("Should return a String list assertion (value at specific path is null).") - void shouldReturnStringListAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLListAssert actual = graphQLFieldAssert.asList(STRING_LIST_TYPE); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a String list assertion (value at specific path is null).") + void shouldReturnStringListAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLListAssert actual = graphQLFieldAssert.asList(STRING_LIST_TYPE); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLFieldAssert.asList(STRING_LIST_TYPE)) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLFieldAssert.asList(STRING_LIST_TYPE)) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLFieldAssert.asList(STRING_LIST_TYPE)) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - STRING_LIST_TYPE) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLFieldAssert.asList(STRING_LIST_TYPE)) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + STRING_LIST_TYPE) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaTypeTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaTypeTest.java index 96dd5caa..8799da1f 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaTypeTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaTypeTest.java @@ -1,5 +1,9 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.type.TypeFactory; import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; @@ -9,69 +13,70 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsJavaTypeTest extends GraphQLFieldAssertTestBase { - private static final JavaType FOO_TYPE = TypeFactory.defaultInstance().constructType(Foo.class); + private static final JavaType FOO_TYPE = TypeFactory.defaultInstance().constructType(Foo.class); - @Test - @DisplayName("Should return a generic assertion (value at specific path is non-null).") - void shouldReturnGenericObjectAssertIfFieldIsNonNull() { - // GIVEN - final Foo foo = new Foo("fooBar"); - given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willReturn(foo); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLGenericObjectAssert - actual = graphQLFieldAssert.as(FOO_TYPE); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.isEqualTo(foo).and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(foo); - } + @Test + @DisplayName("Should return a generic assertion (value at specific path is non-null).") + void shouldReturnGenericObjectAssertIfFieldIsNonNull() { + // GIVEN + final Foo foo = new Foo("fooBar"); + given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willReturn(foo); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLGenericObjectAssert + actual = graphQLFieldAssert.as(FOO_TYPE); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.isEqualTo(foo).and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(foo); + } - @Test - @DisplayName("Should return a generic assertion (value at specific path is null).") - void shouldReturnGenericObjectAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLGenericObjectAssert actual = graphQLFieldAssert.as(FOO_TYPE); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a generic assertion (value at specific path is null).") + void shouldReturnGenericObjectAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLGenericObjectAssert actual = graphQLFieldAssert.as(FOO_TYPE); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLFieldAssert.as(FOO_TYPE)) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLFieldAssert.as(FOO_TYPE)) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLFieldAssert.as(FOO_TYPE)) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - FOO_TYPE) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLFieldAssert.as(FOO_TYPE)) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + FOO_TYPE) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsListTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsListTest.java index 952145e8..5bb55b5c 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsListTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsListTest.java @@ -1,76 +1,79 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.graphql.spring.boot.test.assertions.GraphQLListAssert; -import com.graphql.spring.boot.test.assertions.GraphQLStringAssert; import com.jayway.jsonpath.PathNotFoundException; +import java.util.Arrays; +import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import java.util.Arrays; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsListTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should return a String list assertion (value at specific path is valid list).") - void shouldReturnStringListAssertIfFieldIsNonNull() { - // GIVEN - final List values = Arrays.asList("value1", "value2"); - given(graphQLResponse.getList(MOCK_PATH, String.class)).willReturn(values); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLListAssert actual = graphQLFieldAssert.asListOf(String.class); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.containsExactlyElementsOf(values).and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(values); - } + @Test + @DisplayName("Should return a String list assertion (value at specific path is valid list).") + void shouldReturnStringListAssertIfFieldIsNonNull() { + // GIVEN + final List values = Arrays.asList("value1", "value2"); + given(graphQLResponse.getList(MOCK_PATH, String.class)).willReturn(values); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLListAssert actual = graphQLFieldAssert.asListOf(String.class); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.containsExactlyElementsOf(values).and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(values); + } - @Test - @DisplayName("Should return a String list assertion (value at specific path is null).") - void shouldReturnStringListAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.getList(MOCK_PATH, String.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLListAssert actual = graphQLFieldAssert.asListOf(String.class); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a String list assertion (value at specific path is null).") + void shouldReturnStringListAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.getList(MOCK_PATH, String.class)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLListAssert actual = graphQLFieldAssert.asListOf(String.class); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.getList(MOCK_PATH, String.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLFieldAssert.asListOf(String.class)) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.getList(MOCK_PATH, String.class)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLFieldAssert.asListOf(String.class)) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.getList(MOCK_PATH, String.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLFieldAssert.asListOf(String.class)) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - String.class) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.getList(MOCK_PATH, String.class)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLFieldAssert.asListOf(String.class)) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + String.class) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsLongTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsLongTest.java index 29c2a9da..5364bb73 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsLongTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsLongTest.java @@ -1,72 +1,77 @@ package com.graphql.spring.boot.test; -import com.graphql.spring.boot.test.assertions.GraphQLLongAssert; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; +import com.graphql.spring.boot.test.assertions.GraphQLLongAssert; import com.jayway.jsonpath.PathNotFoundException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsLongTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should return a long assertion (value at specific path is valid long value).") - void shouldReturnLongAssertIfFieldIsNonNull() { - // GIVEN - final Long value = 123L; - given(graphQLResponse.get(MOCK_PATH, Long.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLLongAssert actual = graphQLFieldAssert.asLong(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(value); - } + @Test + @DisplayName("Should return a long assertion (value at specific path is valid long value).") + void shouldReturnLongAssertIfFieldIsNonNull() { + // GIVEN + final Long value = 123L; + given(graphQLResponse.get(MOCK_PATH, Long.class)).willReturn(value); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLLongAssert actual = graphQLFieldAssert.asLong(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(value); + } - @Test - @DisplayName("Should return a long assertion (value at specific path is null).") - void shouldReturnLongAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Long.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLLongAssert actual = graphQLFieldAssert.asLong(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a long assertion (value at specific path is null).") + void shouldReturnLongAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Long.class)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLLongAssert actual = graphQLFieldAssert.asLong(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Long.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asLong) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Long.class)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asLong) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Long.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asLong) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Long.class) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Long.class)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asLong) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + Long.class) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsShortTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsShortTest.java index 23c9dfd1..57c53819 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsShortTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsShortTest.java @@ -1,5 +1,9 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.graphql.spring.boot.test.assertions.GraphQLShortAssert; import com.jayway.jsonpath.PathNotFoundException; @@ -7,66 +11,67 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsShortTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should return a Short assertion (value at specific path is valid Short value).") - void shouldReturnShortAssertIfFieldIsNonNull() { - // GIVEN - final Short value = 123; - given(graphQLResponse.get(MOCK_PATH, Short.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLShortAssert actual = graphQLFieldAssert.asShort(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(value); - } + @Test + @DisplayName("Should return a Short assertion (value at specific path is valid Short value).") + void shouldReturnShortAssertIfFieldIsNonNull() { + // GIVEN + final Short value = 123; + given(graphQLResponse.get(MOCK_PATH, Short.class)).willReturn(value); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLShortAssert actual = graphQLFieldAssert.asShort(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.isEqualByComparingTo(value).and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(value); + } - @Test - @DisplayName("Should return a Short assertion (value at specific path is null).") - void shouldReturnShortAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Short.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLShortAssert actual = graphQLFieldAssert.asShort(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a Short assertion (value at specific path is null).") + void shouldReturnShortAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Short.class)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLShortAssert actual = graphQLFieldAssert.asShort(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Short.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asShort) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Short.class)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asShort) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Short.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asShort) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Short.class) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Short.class)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asShort) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + Short.class) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsStringTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsStringTest.java index 5668e4bf..3350ec07 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsStringTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsStringTest.java @@ -1,5 +1,9 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.graphql.spring.boot.test.assertions.GraphQLStringAssert; import com.jayway.jsonpath.PathNotFoundException; @@ -7,66 +11,67 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsStringTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should return a String assertion (value at specific path is valid String value).") - void shouldReturnStringAssertIfFieldIsNonNull() { - // GIVEN - final String value = "some value"; - given(graphQLResponse.get(MOCK_PATH, String.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLStringAssert actual = graphQLFieldAssert.asString(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.isNotBlank().and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(value); - } + @Test + @DisplayName("Should return a String assertion (value at specific path is valid String value).") + void shouldReturnStringAssertIfFieldIsNonNull() { + // GIVEN + final String value = "some value"; + given(graphQLResponse.get(MOCK_PATH, String.class)).willReturn(value); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLStringAssert actual = graphQLFieldAssert.asString(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.isNotBlank().and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(value); + } - @Test - @DisplayName("Should return a String assertion (value at specific path is null).") - void shouldReturnStringAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, String.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLStringAssert actual = graphQLFieldAssert.asString(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a String assertion (value at specific path is null).") + void shouldReturnStringAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, String.class)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLStringAssert actual = graphQLFieldAssert.asString(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, String.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asString) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, String.class)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asString) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, String.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::asString) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - String.class) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, String.class)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::asString) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + String.class) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsTest.java index 7f51f6aa..9f6cd49c 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsTest.java @@ -1,74 +1,77 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.graphql.spring.boot.test.assertions.GraphQLGenericObjectAssert; import com.jayway.jsonpath.PathNotFoundException; -import lombok.AllArgsConstructor; -import lombok.Data; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertAsTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should return a generic assertion (value at specific path is non-null).") - void shouldReturnGenericObjectAssertIfFieldIsNonNull() { - // GIVEN - final Foo foo = new Foo("fooBar"); - given(graphQLResponse.get(MOCK_PATH, Foo.class)).willReturn(foo); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLGenericObjectAssert actual = graphQLFieldAssert.as(Foo.class); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual.isEqualTo(foo).and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isSameAs(foo); - } + @Test + @DisplayName("Should return a generic assertion (value at specific path is non-null).") + void shouldReturnGenericObjectAssertIfFieldIsNonNull() { + // GIVEN + final Foo foo = new Foo("fooBar"); + given(graphQLResponse.get(MOCK_PATH, Foo.class)).willReturn(foo); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLGenericObjectAssert actual = graphQLFieldAssert.as(Foo.class); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual.isEqualTo(foo).and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isSameAs(foo); + } - @Test - @DisplayName("Should return a generic assertion (value at specific path is null).") - void shouldReturnGenericObjectAssertIfFieldIsNull() { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Foo.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - final GraphQLGenericObjectAssert actual = graphQLFieldAssert.as(Foo.class); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual.and()).isSameAs(graphQLResponse); - assertThat(actual).extracting("actual").isNull(); - } + @Test + @DisplayName("Should return a generic assertion (value at specific path is null).") + void shouldReturnGenericObjectAssertIfFieldIsNull() { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Foo.class)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN + final GraphQLGenericObjectAssert actual = graphQLFieldAssert.as(Foo.class); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual.and()).isSameAs(graphQLResponse); + assertThat(actual).extracting("actual").isNull(); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Foo.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLFieldAssert.as(Foo.class)) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Foo.class)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLFieldAssert.as(Foo.class)) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path cannot be converted.") - void shouldFailIfCannotBeConverted(final @Mock IllegalArgumentException illegalArgumentException) { - // GIVEN - given(graphQLResponse.get(MOCK_PATH, Foo.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLFieldAssert.as(Foo.class)) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Foo.class) - .withCause(illegalArgumentException); - } + @Test + @DisplayName("Should fail if the value at the provided path cannot be converted.") + void shouldFailIfCannotBeConverted( + final @Mock IllegalArgumentException illegalArgumentException) { + // GIVEN + given(graphQLResponse.get(MOCK_PATH, Foo.class)).willThrow(illegalArgumentException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLFieldAssert.as(Foo.class)) + .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, + Foo.class) + .withCause(illegalArgumentException); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNotPresentTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNotPresentTest.java index 5c54cd50..363bb04b 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNotPresentTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNotPresentTest.java @@ -1,46 +1,47 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.jayway.jsonpath.PathNotFoundException; +import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import java.util.stream.Stream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertIsNotPresentTest extends GraphQLFieldAssertTestBase { - private static Stream valuesThatShouldCauseFailure() { - return Stream.of(null, NON_NULL_VALUE); - } + private static Stream valuesThatShouldCauseFailure() { + return Stream.of(null, NON_NULL_VALUE); + } - @ParameterizedTest(name = "value = {0}") - @MethodSource("valuesThatShouldCauseFailure") - @DisplayName("Should fail if the value at the provided path is present.") - void shouldFailIfValueIsPresent(final String value) { - // GIVEN - given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::isNotPresent) - .withMessage("Expected that field %s is not present.", MOCK_PATH); - } + @ParameterizedTest(name = "value = {0}") + @MethodSource("valuesThatShouldCauseFailure") + @DisplayName("Should fail if the value at the provided path is present.") + void shouldFailIfValueIsPresent(final String value) { + // GIVEN + given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(value); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::isNotPresent) + .withMessage("Expected that field %s is not present.", MOCK_PATH); + } - @Test - @DisplayName("Should pass if the path is not present in the response.") - void shouldPassIfNotPresent() { - // GIVEN - given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(PathNotFoundException.class); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatCode(graphQLFieldAssert::isNotPresent).doesNotThrowAnyException(); - assertThat(graphQLFieldAssert.isNotPresent().and()).isSameAs(graphQLResponse); - } + @Test + @DisplayName("Should pass if the path is not present in the response.") + void shouldPassIfNotPresent() { + // GIVEN + given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(PathNotFoundException.class); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatCode(graphQLFieldAssert::isNotPresent).doesNotThrowAnyException(); + assertThat(graphQLFieldAssert.isNotPresent().and()).isSameAs(graphQLResponse); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNullTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNullTest.java index b0351601..f1eb2453 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNullTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNullTest.java @@ -1,51 +1,54 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.jayway.jsonpath.PathNotFoundException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.mockito.BDDMockito.given; - public class GraphQLFieldAssertIsNullTest extends GraphQLFieldAssertTestBase { - @Test - @DisplayName("Should pass if the value at the provided path is null.") - void shouldPassIfNull() { - // GIVEN - given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatCode(graphQLFieldAssert::isNull).doesNotThrowAnyException(); - assertThat(graphQLFieldAssert.isNull().and()).isSameAs(graphQLResponse); - } + @Test + @DisplayName("Should pass if the value at the provided path is null.") + void shouldPassIfNull() { + // GIVEN + given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(null); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatCode(graphQLFieldAssert::isNull).doesNotThrowAnyException(); + assertThat(graphQLFieldAssert.isNull().and()).isSameAs(graphQLResponse); + } - @Test - @DisplayName("Should fail if the value at the provided path is missing.") - void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { - // GIVEN - given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::isNull) - .withMessage("Expected field %s to be present.", MOCK_PATH) - .withCause(pathNotFoundException); - } + @Test + @DisplayName("Should fail if the value at the provided path is missing.") + void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { + // GIVEN + given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(pathNotFoundException); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::isNull) + .withMessage("Expected field %s to be present.", MOCK_PATH) + .withCause(pathNotFoundException); + } - @Test - @DisplayName("Should fail if the value at the provided path is not null.") - void shouldFailIfIsNotNull() { - // GIVEN - given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(NON_NULL_VALUE); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLFieldAssert::isNull) - .withMessage("Expected field %s to be null.", MOCK_PATH); - } + @Test + @DisplayName("Should fail if the value at the provided path is not null.") + void shouldFailIfIsNotNull() { + // GIVEN + given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(NON_NULL_VALUE); + final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, + MOCK_PATH); + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLFieldAssert::isNull) + .withMessage("Expected field %s to be null.", MOCK_PATH); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertTestBase.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertTestBase.java index ad455d36..9b47aa9f 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertTestBase.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertTestBase.java @@ -9,15 +9,16 @@ @ExtendWith(MockitoExtension.class) public class GraphQLFieldAssertTestBase { - protected static final String MOCK_PATH = "test.path"; - protected static final String NON_NULL_VALUE = "non-null"; + protected static final String MOCK_PATH = "test.path"; + protected static final String NON_NULL_VALUE = "non-null"; - @Mock - protected GraphQLResponse graphQLResponse; + @Mock + protected GraphQLResponse graphQLResponse; - @Data - @AllArgsConstructor - protected static class Foo { - private String bar; - } + @Data + @AllArgsConstructor + protected static class Foo { + + private String bar; + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLResponseTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLResponseTest.java index f670381b..f6ab384a 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLResponseTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLResponseTest.java @@ -1,11 +1,24 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.fail; + import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.graphql.spring.boot.test.assertions.GraphQLErrorListAssertion; import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.graphql.spring.boot.test.assertions.NumberOfErrorsAssertion; import graphql.ErrorType; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -22,278 +35,277 @@ import org.springframework.http.ResponseEntity; import org.springframework.util.StreamUtils; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.nio.charset.StandardCharsets; -import java.time.LocalDate; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Stream; - -import static org.assertj.core.api.Assertions.*; - @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class GraphQLResponseTest { - private static final String DATA_PATH_TEST = "$.data.test"; - private static final String INNER_FOO_LIST_DATA_PATH = "$.data.externalList[*].fooList"; - private static final String NESTED_LIST_RESPONSE_FILE = "response-with-nested-list.json"; - private static final String EMPTY_OBJECT_RESPONSE = "{}"; + private static final String DATA_PATH_TEST = "$.data.test"; + private static final String INNER_FOO_LIST_DATA_PATH = "$.data.externalList[*].fooList"; + private static final String NESTED_LIST_RESPONSE_FILE = "response-with-nested-list.json"; + private static final String EMPTY_OBJECT_RESPONSE = "{}"; - @Autowired - private ObjectMapper objectMapper; + @Autowired + private ObjectMapper objectMapper; - private static Stream testGetStringArguments() { - return Stream.of( - Arguments.of("{\"data\": {\"test\": 2}}", "2"), - Arguments.of("{\"data\": {\"test\": \"2\"}}", "2"), - Arguments.of("{\"data\": {\"test\": \"2020-02-23\"}}", "2020-02-23") - ); - } + private static Stream testGetStringArguments() { + return Stream.of( + Arguments.of("{\"data\": {\"test\": 2}}", "2"), + Arguments.of("{\"data\": {\"test\": \"2\"}}", "2"), + Arguments.of("{\"data\": {\"test\": \"2020-02-23\"}}", "2020-02-23") + ); + } - private static Stream testGetArguments() { - return Stream.of( - Arguments.of("{\"data\": {\"test\": \"2\"}}", Integer.class, 2), - Arguments.of("{\"data\": {\"test\": \"2\"}}", String.class, "2"), - Arguments.of("{\"data\": {\"test\": \"2\"}}", BigDecimal.class, new BigDecimal("2")), - Arguments.of("{\"data\": {\"test\": \"2020-02-23\"}}", LocalDate.class, LocalDate.parse("2020-02-23")), - Arguments.of("{\"data\": {\"test\": {\"foo\": \"fizzBuzz\", \"bar\": 13.8 }}}", FooBar.class, + private static Stream testGetArguments() { + return Stream.of( + Arguments.of("{\"data\": {\"test\": \"2\"}}", Integer.class, 2), + Arguments.of("{\"data\": {\"test\": \"2\"}}", String.class, "2"), + Arguments.of("{\"data\": {\"test\": \"2\"}}", BigDecimal.class, new BigDecimal("2")), + Arguments.of("{\"data\": {\"test\": \"2020-02-23\"}}", LocalDate.class, + LocalDate.parse("2020-02-23")), + Arguments + .of("{\"data\": {\"test\": {\"foo\": \"fizzBuzz\", \"bar\": 13.8 }}}", FooBar.class, new FooBar("fizzBuzz", new BigDecimal("13.8"))) - ); - } + ); + } - private static Stream testGetListArguments() { - return Stream.of( - Arguments.of("{\"data\": {\"test\": [\"2\", \"1\"]}}", Integer.class, Arrays.asList(2, 1)), - Arguments.of("{\"data\": {\"test\": [\"2\", \"1\"]}}", String.class, Arrays.asList("2", "1")), - Arguments.of("{\"data\": {\"test\": [\"2\", \"1\"]}}", BigDecimal.class, - Arrays.asList(new BigDecimal("2"), new BigDecimal("1"))), - Arguments.of("{\"data\": {\"test\": [\"2020-02-23\", \"2020-02-24\"]}}", LocalDate.class, - Arrays.asList(LocalDate.parse("2020-02-23"), LocalDate.parse("2020-02-24"))), - Arguments.of("{\"data\":{\"test\":[{\"foo\":\"fizz\",\"bar\":1.23},{\"foo\":\"buzz\",\"bar\":32.12}]}}", + private static Stream testGetListArguments() { + return Stream.of( + Arguments.of("{\"data\": {\"test\": [\"2\", \"1\"]}}", Integer.class, Arrays.asList(2, 1)), + Arguments + .of("{\"data\": {\"test\": [\"2\", \"1\"]}}", String.class, Arrays.asList("2", "1")), + Arguments.of("{\"data\": {\"test\": [\"2\", \"1\"]}}", BigDecimal.class, + Arrays.asList(new BigDecimal("2"), new BigDecimal("1"))), + Arguments.of("{\"data\": {\"test\": [\"2020-02-23\", \"2020-02-24\"]}}", LocalDate.class, + Arrays.asList(LocalDate.parse("2020-02-23"), LocalDate.parse("2020-02-24"))), + Arguments + .of("{\"data\":{\"test\":[{\"foo\":\"fizz\",\"bar\":1.23},{\"foo\":\"buzz\",\"bar\":32.12}]}}", FooBar.class, Arrays.asList( new FooBar("fizz", new BigDecimal("1.23")), new FooBar("buzz", new BigDecimal("32.12")) ) ) - ); - } + ); + } - private static String loadClassPathResource(final String path) { - try(InputStream resourceStream = new ClassPathResource(path).getInputStream()) { - return StreamUtils.copyToString(resourceStream, StandardCharsets.UTF_8); - } catch (IOException e) { - fail("Test setup error - failed to load test resource.", e); - return ""; - } + private static String loadClassPathResource(final String path) { + try (InputStream resourceStream = new ClassPathResource(path).getInputStream()) { + return StreamUtils.copyToString(resourceStream, StandardCharsets.UTF_8); + } catch (IOException e) { + fail("Test setup error - failed to load test resource.", e); + return ""; } + } - @DisplayName("Should get the JSON node's value as a String.") - @ParameterizedTest - @MethodSource("testGetStringArguments") - public void testGetString(final String bodyString, final String expected) { - //GIVEN - final GraphQLResponse graphQLResponse = createResponse(bodyString); - //WHEN - final String actual = graphQLResponse.get(DATA_PATH_TEST); - //THEN - assertThat(actual).isEqualTo(expected); - } + @DisplayName("Should get the JSON node's value as a String.") + @ParameterizedTest + @MethodSource("testGetStringArguments") + public void testGetString(final String bodyString, final String expected) { + //GIVEN + final GraphQLResponse graphQLResponse = createResponse(bodyString); + //WHEN + final String actual = graphQLResponse.get(DATA_PATH_TEST); + //THEN + assertThat(actual).isEqualTo(expected); + } - @DisplayName("Should get the JSON node's value as an instance of a specified class.") - @ParameterizedTest - @MethodSource("testGetArguments") - public void testGet(final String bodyString, final Class clazz, final T expected) { - //GIVEN - final GraphQLResponse graphQLResponse = createResponse(bodyString); - //WHEN - final T actual = graphQLResponse.get(DATA_PATH_TEST, clazz); - //THEN - assertThat(actual).isInstanceOf(clazz).isEqualTo(expected); - } + @DisplayName("Should get the JSON node's value as an instance of a specified class.") + @ParameterizedTest + @MethodSource("testGetArguments") + public void testGet(final String bodyString, final Class clazz, final T expected) { + //GIVEN + final GraphQLResponse graphQLResponse = createResponse(bodyString); + //WHEN + final T actual = graphQLResponse.get(DATA_PATH_TEST, clazz); + //THEN + assertThat(actual).isInstanceOf(clazz).isEqualTo(expected); + } - @DisplayName("Should get the JSON node's value as a List.") - @ParameterizedTest - @MethodSource("testGetListArguments") - public void testGetList(final String bodyString, final Class clazz, final List expected) { - //GIVEN - final GraphQLResponse graphQLResponse = createResponse(bodyString); - //WHEN - final List actual = graphQLResponse.getList(DATA_PATH_TEST, clazz); - //THEN - assertThat(actual).containsExactlyElementsOf(expected); - } + @DisplayName("Should get the JSON node's value as a List.") + @ParameterizedTest + @MethodSource("testGetListArguments") + public void testGetList(final String bodyString, final Class clazz, + final List expected) { + //GIVEN + final GraphQLResponse graphQLResponse = createResponse(bodyString); + //WHEN + final List actual = graphQLResponse.getList(DATA_PATH_TEST, clazz); + //THEN + assertThat(actual).containsExactlyElementsOf(expected); + } - @DisplayName("Should get field as defined by Jackson's JavaType.") - @Test - public void testGetAsJavaType() { - // GIVEN - final List> expected = Arrays.asList(Arrays.asList("foo1", "foo2"), - Collections.singletonList("foo3")); - final JavaType stringList = objectMapper.getTypeFactory().constructCollectionType(List.class, String.class); - final JavaType listOfStringLists = objectMapper.getTypeFactory().constructCollectionType(List.class, + @DisplayName("Should get field as defined by Jackson's JavaType.") + @Test + public void testGetAsJavaType() { + // GIVEN + final List> expected = Arrays.asList(Arrays.asList("foo1", "foo2"), + Collections.singletonList("foo3")); + final JavaType stringList = objectMapper.getTypeFactory() + .constructCollectionType(List.class, String.class); + final JavaType listOfStringLists = objectMapper.getTypeFactory() + .constructCollectionType(List.class, stringList); - // WHEN - final List> actual = createResponse(loadClassPathResource(NESTED_LIST_RESPONSE_FILE)) - .get(INNER_FOO_LIST_DATA_PATH, listOfStringLists); - // THEN - assertThat(actual).containsExactlyElementsOf(expected); + // WHEN + final List> actual = createResponse( + loadClassPathResource(NESTED_LIST_RESPONSE_FILE)) + .get(INNER_FOO_LIST_DATA_PATH, listOfStringLists); + // THEN + assertThat(actual).containsExactlyElementsOf(expected); - } + } - @DisplayName("Should throw illegal argument exception if type is incompatible") - @Test - public void testGetAsJavaTypeConversionError() { - // GIVEN - final JavaType stringType = objectMapper.getTypeFactory().constructType(String.class); - // WHEN - final GraphQLResponse actual = createResponse(loadClassPathResource(NESTED_LIST_RESPONSE_FILE)); - // THEN - assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> actual.get(INNER_FOO_LIST_DATA_PATH, stringType)); + @DisplayName("Should throw illegal argument exception if type is incompatible") + @Test + public void testGetAsJavaTypeConversionError() { + // GIVEN + final JavaType stringType = objectMapper.getTypeFactory().constructType(String.class); + // WHEN + final GraphQLResponse actual = createResponse(loadClassPathResource(NESTED_LIST_RESPONSE_FILE)); + // THEN + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> actual.get(INNER_FOO_LIST_DATA_PATH, stringType)); - } + } - @ParameterizedTest - @ValueSource(strings = { - "{\"data\": { \"foo\":\"bar\" } }", - "{\"errors\": null, \"data\": { \"foo\":\"bar\"} }", - "{\"errors\": [], \"data\": { \"foo\":\"bar\"} }" - }) - @DisplayName("Should pass the assertion if no errors are present.") - void testExpectNoErrorsPass(final String response) { - // WHEN - final GraphQLResponse graphQLResponse = createResponse(response); - // THEN - assertThat(graphQLResponse.assertThatNoErrorsArePresent()) - .as("Should not throw an exception. Should return GraphQL response instance.") - .isSameAs(graphQLResponse); - } + @ParameterizedTest + @ValueSource(strings = { + "{\"data\": { \"foo\":\"bar\" } }", + "{\"errors\": null, \"data\": { \"foo\":\"bar\"} }", + "{\"errors\": [], \"data\": { \"foo\":\"bar\"} }" + }) + @DisplayName("Should pass the assertion if no errors are present.") + void testExpectNoErrorsPass(final String response) { + // WHEN + final GraphQLResponse graphQLResponse = createResponse(response); + // THEN + assertThat(graphQLResponse.assertThatNoErrorsArePresent()) + .as("Should not throw an exception. Should return GraphQL response instance.") + .isSameAs(graphQLResponse); + } - @Test - @DisplayName("Should throw assertion error if an error is present in the response.") - void testExpectNoErrorsFail() { - // GIVEN - final String response = "{\"errors\": [{\"message\": \"Test error.\"}], \"data\": { \"foo\":\"bar\"} }"; - // WHEN - final GraphQLResponse graphQLResponse = createResponse(response); - // THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(graphQLResponse::assertThatNoErrorsArePresent) - .withMessage("Expected no GraphQL errors, but got 1: : Test error."); - } + @Test + @DisplayName("Should throw assertion error if an error is present in the response.") + void testExpectNoErrorsFail() { + // GIVEN + final String response = "{\"errors\": [{\"message\": \"Test error.\"}], \"data\": { \"foo\":\"bar\"} }"; + // WHEN + final GraphQLResponse graphQLResponse = createResponse(response); + // THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(graphQLResponse::assertThatNoErrorsArePresent) + .withMessage("Expected no GraphQL errors, but got 1: : Test error."); + } - @Test - @DisplayName("Should return an assertion for the number of errors.") - void testNumberOfErrorsAssertion() { - // GIVEN - final String response = "{\"errors\": [{\"message\": \"Test error.\"}, {\"message\": \"Test error 2.\"}], " + @Test + @DisplayName("Should return an assertion for the number of errors.") + void testNumberOfErrorsAssertion() { + // GIVEN + final String response = + "{\"errors\": [{\"message\": \"Test error.\"}, {\"message\": \"Test error 2.\"}], " + "\"data\": { \"foo\":\"bar\"} }"; - final GraphQLResponse graphQLResponse = createResponse(response); - // WHEN - final NumberOfErrorsAssertion actual = graphQLResponse.assertThatNumberOfErrors(); - // THEN - assertThat(actual).extracting("actual").isEqualTo(2); - assertThat(actual.and()).isSameAs(graphQLResponse); - } + final GraphQLResponse graphQLResponse = createResponse(response); + // WHEN + final NumberOfErrorsAssertion actual = graphQLResponse.assertThatNumberOfErrors(); + // THEN + assertThat(actual).extracting("actual").isEqualTo(2); + assertThat(actual.and()).isSameAs(graphQLResponse); + } - @Test - @DisplayName("Should return an assertion for the list of errors.") - void testErrorListAssertion() { - // GIVEN - final String response = "{\"errors\": [{\"message\": \"Test error.\", \"errorType\": \"DataFetchingException\"}], " + @Test + @DisplayName("Should return an assertion for the list of errors.") + void testErrorListAssertion() { + // GIVEN + final String response = + "{\"errors\": [{\"message\": \"Test error.\", \"errorType\": \"DataFetchingException\"}], " + "\"data\": { \"foo\":\"bar\"} }"; - final GraphQLResponse graphQLResponse = createResponse(response); - // WHEN - final GraphQLErrorListAssertion actual = graphQLResponse.assertThatListOfErrors(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual).extracting("actual").isEqualTo(Collections.singletonList(GraphQLTestError.builder() + final GraphQLResponse graphQLResponse = createResponse(response); + // WHEN + final GraphQLErrorListAssertion actual = graphQLResponse.assertThatListOfErrors(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual).extracting("actual") + .isEqualTo(Collections.singletonList(GraphQLTestError.builder() .message("Test error.").errorType(ErrorType.DataFetchingException).build())); - assertThat(actual.and()).isSameAs(graphQLResponse); - } + assertThat(actual.and()).isSameAs(graphQLResponse); + } - @Test - @DisplayName("Should return an assertion for the json content of the response.") - void testFieldAssertion() { - // GIVEN - final String response = "{ \"data\": { \"foo\":\"bar\"} }"; - final GraphQLResponse graphQLResponse = createResponse(response); - // WHEN - final JsonContentAssert actual = graphQLResponse.assertThatJsonContent(); - // THEN - assertThat(actual).isNotNull(); - assertThat(actual).extracting("actual").isEqualTo(response); - } + @Test + @DisplayName("Should return an assertion for the json content of the response.") + void testFieldAssertion() { + // GIVEN + final String response = "{ \"data\": { \"foo\":\"bar\"} }"; + final GraphQLResponse graphQLResponse = createResponse(response); + // WHEN + final JsonContentAssert actual = graphQLResponse.assertThatJsonContent(); + // THEN + assertThat(actual).isNotNull(); + assertThat(actual).extracting("actual").isEqualTo(response); + } - @Test - @DisplayName("Should return an assertion for the data field.") - void testDataFieldAssertion() { - // GIVEN - final GraphQLResponse response = createResponse(EMPTY_OBJECT_RESPONSE); - // WHEN - final GraphQLFieldAssert actual = response.assertThatDataField(); - // THEN - assertThatAssertionIsCorrect(actual, response, "$.data"); - } + @Test + @DisplayName("Should return an assertion for the data field.") + void testDataFieldAssertion() { + // GIVEN + final GraphQLResponse response = createResponse(EMPTY_OBJECT_RESPONSE); + // WHEN + final GraphQLFieldAssert actual = response.assertThatDataField(); + // THEN + assertThatAssertionIsCorrect(actual, response, "$.data"); + } - @Test - @DisplayName("Should return an assertion for the errors field.") - void testErrorFieldAssertion() { - // GIVEN - final GraphQLResponse response = createResponse(EMPTY_OBJECT_RESPONSE); - // WHEN - final GraphQLFieldAssert actual = response.assertThatErrorsField(); - // THEN - assertThatAssertionIsCorrect(actual, response, "$.errors"); - } + @Test + @DisplayName("Should return an assertion for the errors field.") + void testErrorFieldAssertion() { + // GIVEN + final GraphQLResponse response = createResponse(EMPTY_OBJECT_RESPONSE); + // WHEN + final GraphQLFieldAssert actual = response.assertThatErrorsField(); + // THEN + assertThatAssertionIsCorrect(actual, response, "$.errors"); + } - @Test - @DisplayName("Should return an assertion for the extensions field.") - void testErrorExtensionsAssertion() { - // GIVEN - final GraphQLResponse response = createResponse(EMPTY_OBJECT_RESPONSE); - // WHEN - final GraphQLFieldAssert actual = response.assertThatExtensionsField(); - // THEN - assertThatAssertionIsCorrect(actual, response, "$.extensions"); - } + @Test + @DisplayName("Should return an assertion for the extensions field.") + void testErrorExtensionsAssertion() { + // GIVEN + final GraphQLResponse response = createResponse(EMPTY_OBJECT_RESPONSE); + // WHEN + final GraphQLFieldAssert actual = response.assertThatExtensionsField(); + // THEN + assertThatAssertionIsCorrect(actual, response, "$.extensions"); + } - @Test - @DisplayName("Should return a field assertion for the specific field.") - void testJsonAssertion() { - // GIVEN - final String path = "$any.path"; - final GraphQLResponse graphQLResponse = createResponse(EMPTY_OBJECT_RESPONSE); - // WHEN - final GraphQLFieldAssert actual = graphQLResponse.assertThatField(path); - // THEN - assertThatAssertionIsCorrect(actual, graphQLResponse, path); - } + @Test + @DisplayName("Should return a field assertion for the specific field.") + void testJsonAssertion() { + // GIVEN + final String path = "$any.path"; + final GraphQLResponse graphQLResponse = createResponse(EMPTY_OBJECT_RESPONSE); + // WHEN + final GraphQLFieldAssert actual = graphQLResponse.assertThatField(path); + // THEN + assertThatAssertionIsCorrect(actual, graphQLResponse, path); + } - private GraphQLResponse createResponse(final String s) { - return new GraphQLResponse(ResponseEntity.ok(s), objectMapper); - } + private GraphQLResponse createResponse(final String s) { + return new GraphQLResponse(ResponseEntity.ok(s), objectMapper); + } - private void assertThatAssertionIsCorrect( - final GraphQLFieldAssert actual, - final GraphQLResponse expectedResponse, - final Object expectedPath - ) { - assertThat(actual).isNotNull(); - assertThat(actual).extracting("graphQLResponse", "jsonPath") - .containsExactly(expectedResponse, expectedPath); - } + private void assertThatAssertionIsCorrect( + final GraphQLFieldAssert actual, + final GraphQLResponse expectedResponse, + final Object expectedPath + ) { + assertThat(actual).isNotNull(); + assertThat(actual).extracting("graphQLResponse", "jsonPath") + .containsExactly(expectedResponse, expectedPath); + } - @Data - @AllArgsConstructor - @NoArgsConstructor - private static class FooBar { + @Data + @AllArgsConstructor + @NoArgsConstructor + private static class FooBar { - private String foo; - private BigDecimal bar; - } + private String foo; + private BigDecimal bar; + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLSubscriptionTestAwaitNoAnswerTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLSubscriptionTestAwaitNoAnswerTest.java index db27fd1b..9c45ab00 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLSubscriptionTestAwaitNoAnswerTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLSubscriptionTestAwaitNoAnswerTest.java @@ -1,58 +1,58 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - @DisplayName("Testing awaitNoResponse methods") public class GraphQLSubscriptionTestAwaitNoAnswerTest extends GraphQLTestSubscriptionTestBase { - @Test - @DisplayName("Should succeed if no responses arrived / default stopAfter.") - void shouldAwaitNoResponseSucceedIfNoResponsesArrivedDefaultStopAfter() { - // WHEN - THEN - graphQLTestSubscription - .start(SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE) - .waitAndExpectNoResponse(TIMEOUT); - assertThatSubscriptionWasStopped(); - } + @Test + @DisplayName("Should succeed if no responses arrived / default stopAfter.") + void shouldAwaitNoResponseSucceedIfNoResponsesArrivedDefaultStopAfter() { + // WHEN - THEN + graphQLTestSubscription + .start(SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE) + .waitAndExpectNoResponse(TIMEOUT); + assertThatSubscriptionWasStopped(); + } - @ParameterizedTest - @ValueSource(booleans = {true, false}) - @DisplayName("Should succeed if no responses arrive.") - void shouldAwaitNoResponseSucceedIfNoResponsesArrived( - final boolean stopAfter - ) { - // WHEN - THEN - graphQLTestSubscription - .start(SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE) - .waitAndExpectNoResponse(TIMEOUT, stopAfter); - assertThatSubscriptionStoppedStatusIs(stopAfter); - } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + @DisplayName("Should succeed if no responses arrive.") + void shouldAwaitNoResponseSucceedIfNoResponsesArrived( + final boolean stopAfter + ) { + // WHEN - THEN + graphQLTestSubscription + .start(SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE) + .waitAndExpectNoResponse(TIMEOUT, stopAfter); + assertThatSubscriptionStoppedStatusIs(stopAfter); + } - @Test - @DisplayName("Should raise assertion error if any response arrived / default stop after.") - void shouldRaiseAssertionErrorIfResponseArrivedDefaultStopAfter() { - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> graphQLTestSubscription - .start(TIMER_SUBSCRIPTION_RESOURCE) - .waitAndExpectNoResponse(TIMEOUT)); - assertThatSubscriptionWasStopped(); - } + @Test + @DisplayName("Should raise assertion error if any response arrived / default stop after.") + void shouldRaiseAssertionErrorIfResponseArrivedDefaultStopAfter() { + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> graphQLTestSubscription + .start(TIMER_SUBSCRIPTION_RESOURCE) + .waitAndExpectNoResponse(TIMEOUT)); + assertThatSubscriptionWasStopped(); + } - @ParameterizedTest - @ValueSource(booleans = {true, false}) - @DisplayName("Should raise assertion error if any response arrived.") - void shouldRaiseAssertionErrorIfResponseArrived( - final boolean stopAfter - ) { - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> graphQLTestSubscription - .start(TIMER_SUBSCRIPTION_RESOURCE) - .waitAndExpectNoResponse(TIMEOUT, stopAfter)); - assertThatSubscriptionStoppedStatusIs(stopAfter); - } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + @DisplayName("Should raise assertion error if any response arrived.") + void shouldRaiseAssertionErrorIfResponseArrived( + final boolean stopAfter + ) { + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> graphQLTestSubscription + .start(TIMER_SUBSCRIPTION_RESOURCE) + .waitAndExpectNoResponse(TIMEOUT, stopAfter)); + assertThatSubscriptionStoppedStatusIs(stopAfter); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAwaitAndGetResponseTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAwaitAndGetResponseTest.java index 901d33b8..a8c7cf28 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAwaitAndGetResponseTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAwaitAndGetResponseTest.java @@ -1,129 +1,134 @@ package com.graphql.spring.boot.test; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; -import static org.assertj.core.api.Assertions.assertThat; - -public class GraphQLTestSubscriptionAwaitAndGetResponseTest extends GraphQLTestSubscriptionTestBase { +public class GraphQLTestSubscriptionAwaitAndGetResponseTest extends + GraphQLTestSubscriptionTestBase { - @Test - @DisplayName("Should await and get single response.") - void shouldAwaitAndGetResponse() { - // WHEN - graphQLTestSubscription - .start(TIMER_SUBSCRIPTION_RESOURCE) - .awaitAndGetNextResponse(TIMEOUT) - .assertThatField(DATA_TIMER_FIELD).asLong().isZero(); - // THEN - assertThatSubscriptionWasStopped(); - } + @Test + @DisplayName("Should await and get single response.") + void shouldAwaitAndGetResponse() { + // WHEN + graphQLTestSubscription + .start(TIMER_SUBSCRIPTION_RESOURCE) + .awaitAndGetNextResponse(TIMEOUT) + .assertThatField(DATA_TIMER_FIELD).asLong().isZero(); + // THEN + assertThatSubscriptionWasStopped(); + } - @Test - @DisplayName("Should await and get multiple responses.") - void shouldAwaitAndGetMultipleResponses() { - // WHEN - final List graphQLResponses = graphQLTestSubscription - .start(TIMER_SUBSCRIPTION_RESOURCE) - .awaitAndGetNextResponses(TIMEOUT, 5); - // THEN - assertThat(graphQLResponses) - .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) - .containsExactly(0L, 1L, 2L, 3L, 4L); - assertThatSubscriptionWasStopped(); - } + @Test + @DisplayName("Should await and get multiple responses.") + void shouldAwaitAndGetMultipleResponses() { + // WHEN + final List graphQLResponses = graphQLTestSubscription + .start(TIMER_SUBSCRIPTION_RESOURCE) + .awaitAndGetNextResponses(TIMEOUT, 5); + // THEN + assertThat(graphQLResponses) + .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) + .containsExactly(0L, 1L, 2L, 3L, 4L); + assertThatSubscriptionWasStopped(); + } - @Test - @DisplayName("Should await and get all responses / default stopAfter.") - void shouldAwaitAndGetAllResponsesDefaultStopAfter() { - // WHEN - final List graphQLResponses = graphQLTestSubscription - .start(TIMER_SUBSCRIPTION_RESOURCE) - .awaitAndGetAllResponses(TIMEOUT); - // THEN - assertThat(graphQLResponses) - .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) - .containsExactly(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); - assertThatSubscriptionWasStopped(); - } + @Test + @DisplayName("Should await and get all responses / default stopAfter.") + void shouldAwaitAndGetAllResponsesDefaultStopAfter() { + // WHEN + final List graphQLResponses = graphQLTestSubscription + .start(TIMER_SUBSCRIPTION_RESOURCE) + .awaitAndGetAllResponses(TIMEOUT); + // THEN + assertThat(graphQLResponses) + .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) + .containsExactly(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); + assertThatSubscriptionWasStopped(); + } - @ParameterizedTest - @ValueSource(booleans = {true, false}) - @DisplayName("Should await and get all responses.") - void shouldAwaitAndGetAllResponses( - final boolean stopAfter - ) { - // WHEN - final List graphQLResponses = graphQLTestSubscription - .start(TIMER_SUBSCRIPTION_RESOURCE) - .awaitAndGetAllResponses(TIMEOUT, stopAfter); - // THEN - assertThat(graphQLResponses) - .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) - .containsExactly(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); - assertThatSubscriptionStoppedStatusIs(stopAfter); - } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + @DisplayName("Should await and get all responses.") + void shouldAwaitAndGetAllResponses( + final boolean stopAfter + ) { + // WHEN + final List graphQLResponses = graphQLTestSubscription + .start(TIMER_SUBSCRIPTION_RESOURCE) + .awaitAndGetAllResponses(TIMEOUT, stopAfter); + // THEN + assertThat(graphQLResponses) + .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) + .containsExactly(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); + assertThatSubscriptionStoppedStatusIs(stopAfter); + } - @Test - @DisplayName("Should handle multiple subsequent await and get calls, assuming stopAfter was false.") - void shouldWorkWithMultipleAwaitAndGetCalls() { - // GIVEN - graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE); + @Test + @DisplayName("Should handle multiple subsequent await and get calls, assuming stopAfter was false.") + void shouldWorkWithMultipleAwaitAndGetCalls() { + // GIVEN + graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE); - // WHEN - graphQLTestSubscription.awaitAndGetNextResponse(TIMEOUT, false).assertThatField(DATA_TIMER_FIELD) - .asLong().isZero(); - // THEN - assertThatSubscriptionWasNotStopped(); + // WHEN + graphQLTestSubscription.awaitAndGetNextResponse(TIMEOUT, false) + .assertThatField(DATA_TIMER_FIELD) + .asLong().isZero(); + // THEN + assertThatSubscriptionWasNotStopped(); - // WHEN - final List graphQLResponses = graphQLTestSubscription.awaitAndGetNextResponses(TIMEOUT, 3, false); - // THEN - assertThat(graphQLResponses) - .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) - .containsExactly(1L, 2L, 3L); - assertThatSubscriptionWasNotStopped(); + // WHEN + final List graphQLResponses = graphQLTestSubscription + .awaitAndGetNextResponses(TIMEOUT, 3, false); + // THEN + assertThat(graphQLResponses) + .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) + .containsExactly(1L, 2L, 3L); + assertThatSubscriptionWasNotStopped(); - // WHEN - final List graphQLResponses2 = graphQLTestSubscription.awaitAndGetAllResponses(TIMEOUT); - // THEN - assertThat(graphQLResponses2) - .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) - .containsExactly(4L, 5L, 6L, 7L, 8L, 9L); - assertThatSubscriptionWasStopped(); - } + // WHEN + final List graphQLResponses2 = graphQLTestSubscription + .awaitAndGetAllResponses(TIMEOUT); + // THEN + assertThat(graphQLResponses2) + .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) + .containsExactly(4L, 5L, 6L, 7L, 8L, 9L); + assertThatSubscriptionWasStopped(); + } - @Test - @DisplayName("Should properly handle subscriptions with input variables.") - void shouldHandleSubscriptionWithParameters() { - // GIVEN - final String param = String.valueOf(UUID.randomUUID()); - final Map startPayload = Collections.singletonMap("param", param); - // WHEN - THEN - graphQLTestSubscription - .start(SUBSCRIPTION_WITH_PARAMETER_RESOURCE, startPayload) - .awaitAndGetNextResponse(TIMEOUT) - .assertThatField(DATA_SUBSCRIPTION_WITH_PARAMETER_FIELD).asString().isEqualTo(param); - } + @Test + @DisplayName("Should properly handle subscriptions with input variables.") + void shouldHandleSubscriptionWithParameters() { + // GIVEN + final String param = String.valueOf(UUID.randomUUID()); + final Map startPayload = Collections.singletonMap("param", param); + // WHEN - THEN + graphQLTestSubscription + .start(SUBSCRIPTION_WITH_PARAMETER_RESOURCE, startPayload) + .awaitAndGetNextResponse(TIMEOUT) + .assertThatField(DATA_SUBSCRIPTION_WITH_PARAMETER_FIELD).asString().isEqualTo(param); + } - @Test - @DisplayName("Should properly work with subscriptions that expect an init payload.") - void shouldSubscriptionWithInitPayload() { - // GIVEN - final String initParamValue = String.valueOf(UUID.randomUUID()); - final Map initPayload = Collections.singletonMap("initParamValue", initParamValue); - // WHEN - THEN - graphQLTestSubscription - .init(initPayload) - .start(SUBSCRIPTION_WITH_INIT_PAYLOAD_RESOURCE) - .awaitAndGetNextResponse(TIMEOUT) - .assertThatField(DATA_SUBSCRIPTION_WITH_INIT_PAYLOAD_FIELD).asString().isEqualTo(initParamValue); - } + @Test + @DisplayName("Should properly work with subscriptions that expect an init payload.") + void shouldSubscriptionWithInitPayload() { + // GIVEN + final String initParamValue = String.valueOf(UUID.randomUUID()); + final Map initPayload = Collections + .singletonMap("initParamValue", initParamValue); + // WHEN - THEN + graphQLTestSubscription + .init(initPayload) + .start(SUBSCRIPTION_WITH_INIT_PAYLOAD_RESOURCE) + .awaitAndGetNextResponse(TIMEOUT) + .assertThatField(DATA_SUBSCRIPTION_WITH_INIT_PAYLOAD_FIELD).asString() + .isEqualTo(initParamValue); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionErrorTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionErrorTest.java index 8738490c..ad14be0e 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionErrorTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionErrorTest.java @@ -3,19 +3,17 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; - @DisplayName("Test error message handling.") public class GraphQLTestSubscriptionErrorTest extends GraphQLTestSubscriptionTestBase { - @Test - @DisplayName("Should handle error messages.") - void shouldHandleErrorMessages() { - // WHEN - THEN - graphQLTestSubscription.start(SUBSCRIPTION_THAT_THROWS_EXCEPTION) - .awaitAndGetNextResponse(TIMEOUT) - .assertThatDataField().isNotPresent() - .and() - .assertThatListOfErrors().isNotEmpty(); - } + @Test + @DisplayName("Should handle error messages.") + void shouldHandleErrorMessages() { + // WHEN - THEN + graphQLTestSubscription.start(SUBSCRIPTION_THAT_THROWS_EXCEPTION) + .awaitAndGetNextResponse(TIMEOUT) + .assertThatDataField().isNotPresent() + .and() + .assertThatListOfErrors().isNotEmpty(); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionGetRemainingResponsesTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionGetRemainingResponsesTest.java index 260ac6fc..e6b31623 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionGetRemainingResponsesTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionGetRemainingResponsesTest.java @@ -1,33 +1,35 @@ package com.graphql.spring.boot.test; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + @DisplayName("Testing getRemainingResponses") -public class GraphQLTestSubscriptionGetRemainingResponsesTest extends GraphQLTestSubscriptionTestBase { +public class GraphQLTestSubscriptionGetRemainingResponsesTest extends + GraphQLTestSubscriptionTestBase { - @Test - @DisplayName("Should properly return remaining responses after the Subscription was stopped.") - void shouldGetRemainingResponses() throws InterruptedException { - // WHEN - graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE).awaitAndGetNextResponse(TIMEOUT, false); - Thread.sleep(TIMEOUT); - graphQLTestSubscription.stop(); - // THEN - assertThatSubscriptionWasStopped(); - assertThat(graphQLTestSubscription.getRemainingResponses()) - .extracting(graphQLResponse -> graphQLResponse.get(DATA_TIMER_FIELD, Long.class)) - .containsExactly(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); - } + @Test + @DisplayName("Should properly return remaining responses after the Subscription was stopped.") + void shouldGetRemainingResponses() throws InterruptedException { + // WHEN + graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE) + .awaitAndGetNextResponse(TIMEOUT, false); + Thread.sleep(TIMEOUT); + graphQLTestSubscription.stop(); + // THEN + assertThatSubscriptionWasStopped(); + assertThat(graphQLTestSubscription.getRemainingResponses()) + .extracting(graphQLResponse -> graphQLResponse.get(DATA_TIMER_FIELD, Long.class)) + .containsExactly(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); + } - @Test - @DisplayName("Should raise assertion error if called before the subscription was stopped.") - void shouldRaiseAssertionErrorIfCalledBeforeSubscriptionIsStopped() { - // WHEN - THEN - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLTestSubscription.getRemainingResponses()); - } + @Test + @DisplayName("Should raise assertion error if called before the subscription was stopped.") + void shouldRaiseAssertionErrorIfCalledBeforeSubscriptionIsStopped() { + // WHEN - THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLTestSubscription.getRemainingResponses()); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionResetTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionResetTest.java index 71622407..ecd1cfd0 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionResetTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionResetTest.java @@ -1,87 +1,87 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.test.util.ReflectionTestUtils; -import java.util.Queue; - -import static org.assertj.core.api.Assertions.assertThat; - @DisplayName("Testing reset") public class GraphQLTestSubscriptionResetTest extends GraphQLTestSubscriptionTestBase { - @Test - @DisplayName("Should work if subscription was not yet started.") - void shouldWorkIfSubscriptionWasNotStarted() { - // WHEN - final int firstId = getSubscriptionId(); - graphQLTestSubscription.reset(); - // THEN - assertThatSubscriptionWasReset(); - assertThatNewIdWasGenerated(firstId); - } + @Test + @DisplayName("Should work if subscription was not yet started.") + void shouldWorkIfSubscriptionWasNotStarted() { + // WHEN + final int firstId = getSubscriptionId(); + graphQLTestSubscription.reset(); + // THEN + assertThatSubscriptionWasReset(); + assertThatNewIdWasGenerated(firstId); + } - @Test - @DisplayName("Should work if subscription is still active.") - void shouldWorkIfSubscriptionIsStillActive() { - // GIVEN - final int firstId = getSubscriptionId(); - graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE); - // WHEN - graphQLTestSubscription.reset(); - // THEN - assertThatSubscriptionWasReset(); - assertThatNewIdWasGenerated(firstId); - } + @Test + @DisplayName("Should work if subscription is still active.") + void shouldWorkIfSubscriptionIsStillActive() { + // GIVEN + final int firstId = getSubscriptionId(); + graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE); + // WHEN + graphQLTestSubscription.reset(); + // THEN + assertThatSubscriptionWasReset(); + assertThatNewIdWasGenerated(firstId); + } - @Test - @DisplayName("Should work if subscription was stopped.") - void shouldWorkIfSubscriptionWasAlreadyStopped() { - // GIVEN - final int firstId = getSubscriptionId(); - graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE).stop(); - // WHEN - graphQLTestSubscription.reset(); - // THEN - assertThatSubscriptionWasReset(); - assertThatNewIdWasGenerated(firstId); - } + @Test + @DisplayName("Should work if subscription was stopped.") + void shouldWorkIfSubscriptionWasAlreadyStopped() { + // GIVEN + final int firstId = getSubscriptionId(); + graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE).stop(); + // WHEN + graphQLTestSubscription.reset(); + // THEN + assertThatSubscriptionWasReset(); + assertThatNewIdWasGenerated(firstId); + } - @Test - @DisplayName("Should allow starting a new subscription after reset.") - void shouldAllowStartingNewSubscriptionAfterReset() { - // GIVEN - startAndAssertThatNewSubscriptionWorks(); - // WHEN - graphQLTestSubscription.reset(); - // THEN - startAndAssertThatNewSubscriptionWorks(); - } + @Test + @DisplayName("Should allow starting a new subscription after reset.") + void shouldAllowStartingNewSubscriptionAfterReset() { + // GIVEN + startAndAssertThatNewSubscriptionWorks(); + // WHEN + graphQLTestSubscription.reset(); + // THEN + startAndAssertThatNewSubscriptionWorks(); + } - private void startAndAssertThatNewSubscriptionWorks() { - final Integer actual = graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE) - .awaitAndGetNextResponse(TIMEOUT) - .get("$.data.timer", Integer.class); - assertThat(actual).isZero(); - } + private void startAndAssertThatNewSubscriptionWorks() { + final Integer actual = graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE) + .awaitAndGetNextResponse(TIMEOUT) + .get("$.data.timer", Integer.class); + assertThat(actual).isZero(); + } - private void assertThatSubscriptionWasReset() { - assertThat(graphQLTestSubscription.isInitialized()).isFalse(); - assertThat(graphQLTestSubscription.isAcknowledged()).isFalse(); - assertThat(graphQLTestSubscription.isStarted()).isFalse(); - assertThat(graphQLTestSubscription.isStopped()).isFalse(); - assertThat(graphQLTestSubscription.isCompleted()).isFalse(); - assertThat(((SubscriptionState) ReflectionTestUtils.getField(graphQLTestSubscription, GraphQLTestSubscription.class, + private void assertThatSubscriptionWasReset() { + assertThat(graphQLTestSubscription.isInitialized()).isFalse(); + assertThat(graphQLTestSubscription.isAcknowledged()).isFalse(); + assertThat(graphQLTestSubscription.isStarted()).isFalse(); + assertThat(graphQLTestSubscription.isStopped()).isFalse(); + assertThat(graphQLTestSubscription.isCompleted()).isFalse(); + assertThat(((SubscriptionState) ReflectionTestUtils + .getField(graphQLTestSubscription, GraphQLTestSubscription.class, "state")).getResponses()).isEmpty(); - assertThat(graphQLTestSubscription.getSession()).isNull(); - } + assertThat(graphQLTestSubscription.getSession()).isNull(); + } - private void assertThatNewIdWasGenerated(int previousId) { - assertThat(getSubscriptionId()).isEqualTo(previousId + 1); - } + private void assertThatNewIdWasGenerated(int previousId) { + assertThat(getSubscriptionId()).isEqualTo(previousId + 1); + } - private int getSubscriptionId() { - return ((SubscriptionState) ReflectionTestUtils.getField(graphQLTestSubscription, GraphQLTestSubscription.class, "state")).getId(); - } + private int getSubscriptionId() { + return ((SubscriptionState) ReflectionTestUtils + .getField(graphQLTestSubscription, GraphQLTestSubscription.class, "state")).getId(); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionTestBase.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionTestBase.java index 5320a7a8..280bad9b 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionTestBase.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionTestBase.java @@ -1,5 +1,7 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; + import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -7,59 +9,58 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.Environment; -import static org.assertj.core.api.Assertions.assertThat; - @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class GraphQLTestSubscriptionTestBase { - protected static final String TIMER_SUBSCRIPTION_RESOURCE = "timer-subscription-resource.graphql"; - protected static final String SUBSCRIPTION_WITH_PARAMETER_RESOURCE = "subscription-with-param-resource.graphql"; - protected static final String SUBSCRIPTION_WITH_INIT_PAYLOAD_RESOURCE - = "subscription-with-init-payload-resource.graphql"; - protected static final String SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE - = "subscription-that-times-out-resource.graphql"; - protected static final String SUBSCRIPTION_THAT_THROWS_EXCEPTION - = "subscription-that-throws-exception-resource.graphql"; - protected static final String DATA_TIMER_FIELD = "$.data.timer"; - protected static final String DATA_SUBSCRIPTION_WITH_PARAMETER_FIELD = "$.data.subscriptionWithParameter"; - protected static final String DATA_SUBSCRIPTION_WITH_INIT_PAYLOAD_FIELD = "$.data.subscriptionWithInitPayload"; - protected static final int TIMEOUT = 2000; + protected static final String TIMER_SUBSCRIPTION_RESOURCE = "timer-subscription-resource.graphql"; + protected static final String SUBSCRIPTION_WITH_PARAMETER_RESOURCE = "subscription-with-param-resource.graphql"; + protected static final String SUBSCRIPTION_WITH_INIT_PAYLOAD_RESOURCE + = "subscription-with-init-payload-resource.graphql"; + protected static final String SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE + = "subscription-that-times-out-resource.graphql"; + protected static final String SUBSCRIPTION_THAT_THROWS_EXCEPTION + = "subscription-that-throws-exception-resource.graphql"; + protected static final String DATA_TIMER_FIELD = "$.data.timer"; + protected static final String DATA_SUBSCRIPTION_WITH_PARAMETER_FIELD = "$.data.subscriptionWithParameter"; + protected static final String DATA_SUBSCRIPTION_WITH_INIT_PAYLOAD_FIELD = "$.data.subscriptionWithInitPayload"; + protected static final int TIMEOUT = 2000; - @Autowired - protected Environment environment; + @Autowired + protected Environment environment; - @Autowired - protected ObjectMapper objectMapper; + @Autowired + protected ObjectMapper objectMapper; - protected GraphQLTestSubscription graphQLTestSubscription; + protected GraphQLTestSubscription graphQLTestSubscription; - @BeforeEach - protected void setUp() { - graphQLTestSubscription = new GraphQLTestSubscription(environment, objectMapper, "subscriptions"); - } + @BeforeEach + protected void setUp() { + graphQLTestSubscription = new GraphQLTestSubscription(environment, objectMapper, + "subscriptions"); + } - @AfterEach - protected void tearDown() { - graphQLTestSubscription.reset(); - } + @AfterEach + protected void tearDown() { + graphQLTestSubscription.reset(); + } - protected void assertThatSubscriptionStoppedStatusIs(boolean isStopped) { - if (isStopped) { - assertThatSubscriptionWasStopped(); - } else { - assertThatSubscriptionWasNotStopped(); - } + protected void assertThatSubscriptionStoppedStatusIs(boolean isStopped) { + if (isStopped) { + assertThatSubscriptionWasStopped(); + } else { + assertThatSubscriptionWasNotStopped(); } + } - protected void assertThatSubscriptionWasStopped() { - assertThat(graphQLTestSubscription.isStopped()) - .as("Subscription should be stopped.") - .isTrue(); - } + protected void assertThatSubscriptionWasStopped() { + assertThat(graphQLTestSubscription.isStopped()) + .as("Subscription should be stopped.") + .isTrue(); + } - protected void assertThatSubscriptionWasNotStopped() { - assertThat(graphQLTestSubscription.isStopped()) - .as("Subscription should not be stopped.") - .isFalse(); - } + protected void assertThatSubscriptionWasNotStopped() { + assertThat(graphQLTestSubscription.isStopped()) + .as("Subscription should not be stopped.") + .isFalse(); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionUsageErrorHandlingTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionUsageErrorHandlingTest.java index b5033db2..51ff09e1 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionUsageErrorHandlingTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionUsageErrorHandlingTest.java @@ -1,64 +1,64 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - @DisplayName("Testing if usage errors are properly handled.") public class GraphQLTestSubscriptionUsageErrorHandlingTest extends GraphQLTestSubscriptionTestBase { - @Test - @DisplayName("Should raise an assertion error if init is called after init.") - void shouldRaiseAssertionErrorIfInitAfterInit() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLTestSubscription.init().init()); - } + @Test + @DisplayName("Should raise an assertion error if init is called after init.") + void shouldRaiseAssertionErrorIfInitAfterInit() { + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLTestSubscription.init().init()); + } - @Test - @DisplayName("Should raise an assertion error if awaitAndGet times out.") - void shouldRaiseAssertionErrorIfAwaitAndGetTimesOut() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLTestSubscription - .start(SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE) - .awaitAndGetNextResponse(TIMEOUT)); - } + @Test + @DisplayName("Should raise an assertion error if awaitAndGet times out.") + void shouldRaiseAssertionErrorIfAwaitAndGetTimesOut() { + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLTestSubscription + .start(SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE) + .awaitAndGetNextResponse(TIMEOUT)); + } - @Test - @DisplayName("Should raise an assertion error if awaitAndGet methods are called before start.") - void shouldRaiseAssertionErrorIfGettingResponseWithoutStart() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLTestSubscription.init().awaitAndGetNextResponse(TIMEOUT)); - } + @Test + @DisplayName("Should raise an assertion error if awaitAndGet methods are called before start.") + void shouldRaiseAssertionErrorIfGettingResponseWithoutStart() { + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLTestSubscription.init().awaitAndGetNextResponse(TIMEOUT)); + } - @Test - @DisplayName("Should raise an assertion error if stop is called before init.") - void shouldRaiseAssertionErrorIfStopWithoutStart() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLTestSubscription.stop()); - } + @Test + @DisplayName("Should raise an assertion error if stop is called before init.") + void shouldRaiseAssertionErrorIfStopWithoutStart() { + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLTestSubscription.stop()); + } - @Test - @DisplayName("Should raise an assertion error if stop is called after stop.") - void shouldRaiseAssertionErrorIfStopAfterStop() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE).stop().stop()); - } + @Test + @DisplayName("Should raise an assertion error if stop is called after stop.") + void shouldRaiseAssertionErrorIfStopAfterStop() { + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE).stop().stop()); + } - @Test - @DisplayName("Should raise an assertion error if awaitAndGet methods are called after stop.") - void shouldRaiseAssertionErrorIfGettingResponseAfterStop() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLTestSubscription - .start(TIMER_SUBSCRIPTION_RESOURCE) - .stop() - .awaitAndGetNextResponse(TIMEOUT)); - } + @Test + @DisplayName("Should raise an assertion error if awaitAndGet methods are called after stop.") + void shouldRaiseAssertionErrorIfGettingResponseAfterStop() { + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLTestSubscription + .start(TIMER_SUBSCRIPTION_RESOURCE) + .stop() + .awaitAndGetNextResponse(TIMEOUT)); + } - @Test - @DisplayName("Should raise an assertion error if the provided GraphQL resource could not be found.") - void shouldRaiseAssertionErrorIfGraphQLResourceCouldNotBeFound() { - assertThatExceptionOfType(AssertionError.class) - .isThrownBy(() -> graphQLTestSubscription.start("non-existing-file.graphql")); - } + @Test + @DisplayName("Should raise an assertion error if the provided GraphQL resource could not be found.") + void shouldRaiseAssertionErrorIfGraphQLResourceCouldNotBeFound() { + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLTestSubscription.start("non-existing-file.graphql")); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateIntegrationTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateIntegrationTest.java index 6d58ee87..6c702b49 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateIntegrationTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateIntegrationTest.java @@ -4,6 +4,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.graphql.spring.boot.test.beans.FooBar; import graphql.GraphQLError; +import java.io.IOException; +import java.util.Collections; +import java.util.UUID; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -13,172 +16,173 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.http.HttpHeaders; -import java.awt.*; -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.UUID; - @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class GraphQLTestTemplateIntegrationTest { - private static final String SIMPLE_TEST_QUERY = "simple-test-query.graphql"; - private static final String SIMPLE_TEST_QUERY_WITH_FRAGMENTS = "simple-test-query-with-fragments.graphql"; - private static final String TEST_FRAGMENT_FILE = "foo-bar-fragment.graphql"; - private static final String QUERY_WITH_VARIABLES = "query-with-variables.graphql"; - private static final String COMPLEX_TEST_QUERY = "complex-query.graphql"; - private static final String MULTIPLE_QUERIES = "multiple-queries.graphql"; - private static final String INPUT_STRING_VALUE = "input-value"; - private static final String INPUT_STRING_NAME = "input"; - private static final String INPUT_HEADER_NAME = "headerName"; - private static final String TEST_HEADER_NAME = "x-test"; - private static final String TEST_HEADER_VALUE = String.valueOf(UUID.randomUUID()); - private static final String FOO = "FOO"; - private static final String BAR = "BAR"; - private static final String TEST = "TEST"; - private static final String DATA_FIELD_FOO_BAR = "$.data.fooBar"; - private static final String DATA_FIELD_QUERY_WITH_VARIABLES = "$.data.queryWithVariables"; - private static final String DATA_FIELD_OTHER_QUERY = "$.data.otherQuery"; - private static final String DATA_FIELD_QUERY_WITH_HEADER = "$.data.queryWithHeader"; - private static final String DATA_FIELD_DUMMY = "$.data.dummy"; - private static final String OPERATION_NAME_WITH_VARIABLES = "withVariable"; - private static final String OPERATION_NAME_TEST_QUERY_1 = "testQuery1"; - private static final String OPERATION_NAME_TEST_QUERY_2 = "testQuery2"; - private static final String OPERATION_NAME_COMPLEX_QUERY = "complexQuery"; - private static final String GRAPHQL_ENDPOINT = "/graphql"; - - @Autowired - private ResourceLoader resourceLoader; - - @Autowired - private TestRestTemplate testRestTemplate; - - @Autowired - private ObjectMapper objectMapper; - - private GraphQLTestTemplate graphQLTestTemplate; - - @BeforeEach - void setUp() { - graphQLTestTemplate = new GraphQLTestTemplate(resourceLoader, testRestTemplate, GRAPHQL_ENDPOINT, objectMapper); - } - - @Test - @DisplayName("Test postForResource with only the GraphQL resource provided.") - void testPostForResource() throws IOException { - graphQLTestTemplate.postForResource(SIMPLE_TEST_QUERY) - .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_OTHER_QUERY).asString().isEqualTo(TEST); - } - - @Test - @DisplayName("Test postForResource with fragments.") - void testPostForResourceWithFragments() throws IOException { - graphQLTestTemplate.postForResource(SIMPLE_TEST_QUERY_WITH_FRAGMENTS, + private static final String SIMPLE_TEST_QUERY = "simple-test-query.graphql"; + private static final String SIMPLE_TEST_QUERY_WITH_FRAGMENTS = "simple-test-query-with-fragments.graphql"; + private static final String TEST_FRAGMENT_FILE = "foo-bar-fragment.graphql"; + private static final String QUERY_WITH_VARIABLES = "query-with-variables.graphql"; + private static final String COMPLEX_TEST_QUERY = "complex-query.graphql"; + private static final String MULTIPLE_QUERIES = "multiple-queries.graphql"; + private static final String INPUT_STRING_VALUE = "input-value"; + private static final String INPUT_STRING_NAME = "input"; + private static final String INPUT_HEADER_NAME = "headerName"; + private static final String TEST_HEADER_NAME = "x-test"; + private static final String TEST_HEADER_VALUE = String.valueOf(UUID.randomUUID()); + private static final String FOO = "FOO"; + private static final String BAR = "BAR"; + private static final String TEST = "TEST"; + private static final String DATA_FIELD_FOO_BAR = "$.data.fooBar"; + private static final String DATA_FIELD_QUERY_WITH_VARIABLES = "$.data.queryWithVariables"; + private static final String DATA_FIELD_OTHER_QUERY = "$.data.otherQuery"; + private static final String DATA_FIELD_QUERY_WITH_HEADER = "$.data.queryWithHeader"; + private static final String DATA_FIELD_DUMMY = "$.data.dummy"; + private static final String OPERATION_NAME_WITH_VARIABLES = "withVariable"; + private static final String OPERATION_NAME_TEST_QUERY_1 = "testQuery1"; + private static final String OPERATION_NAME_TEST_QUERY_2 = "testQuery2"; + private static final String OPERATION_NAME_COMPLEX_QUERY = "complexQuery"; + private static final String GRAPHQL_ENDPOINT = "/graphql"; + + @Autowired + private ResourceLoader resourceLoader; + + @Autowired + private TestRestTemplate testRestTemplate; + + @Autowired + private ObjectMapper objectMapper; + + private GraphQLTestTemplate graphQLTestTemplate; + + @BeforeEach + void setUp() { + graphQLTestTemplate = new GraphQLTestTemplate(resourceLoader, testRestTemplate, + GRAPHQL_ENDPOINT, objectMapper); + } + + @Test + @DisplayName("Test postForResource with only the GraphQL resource provided.") + void testPostForResource() throws IOException { + graphQLTestTemplate.postForResource(SIMPLE_TEST_QUERY) + .assertThatNoErrorsArePresent() + .assertThatField(DATA_FIELD_OTHER_QUERY).asString().isEqualTo(TEST); + } + + @Test + @DisplayName("Test postForResource with fragments.") + void testPostForResourceWithFragments() throws IOException { + graphQLTestTemplate.postForResource(SIMPLE_TEST_QUERY_WITH_FRAGMENTS, + Collections.singletonList(TEST_FRAGMENT_FILE)) + .assertThatNoErrorsArePresent() + .assertThatField(DATA_FIELD_FOO_BAR).as(FooBar.class) + .usingRecursiveComparison() + .ignoringAllOverriddenEquals() + .isEqualTo(FooBar.builder().foo(FOO).bar(BAR).build()); + } + + @Test + @DisplayName("Test perform with variables.") + void testPerformWithVariables() throws IOException { + // GIVEN + final ObjectNode variables = objectMapper.createObjectNode(); + variables.put(INPUT_STRING_NAME, INPUT_STRING_VALUE); + // WHEN - THEN + graphQLTestTemplate.perform(QUERY_WITH_VARIABLES, variables) + .assertThatNoErrorsArePresent() + .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString().isEqualTo(INPUT_STRING_VALUE); + } + + @Test + @DisplayName("Test perform with variables and operation name") + void testPerformWithOperationAndVariables() throws IOException { + // GIVEN + final ObjectNode variables = objectMapper.createObjectNode(); + variables.put(INPUT_STRING_NAME, INPUT_STRING_VALUE); + // WHEN - THEN + graphQLTestTemplate.perform(MULTIPLE_QUERIES, OPERATION_NAME_WITH_VARIABLES, variables) + .assertThatNoErrorsArePresent() + .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString().isEqualTo(INPUT_STRING_VALUE); + } + + @Test + @DisplayName("Test perform with variables and fragments") + void testPerformWithVariablesAndFragments() throws IOException { + // GIVEN + final FooBar expected = new FooBar(String.valueOf(UUID.randomUUID()), + String.valueOf(UUID.randomUUID())); + final ObjectNode variables = objectMapper.valueToTree(expected); + // WHEN - THEN + graphQLTestTemplate + .perform(SIMPLE_TEST_QUERY_WITH_FRAGMENTS, variables, + Collections.singletonList(TEST_FRAGMENT_FILE)) + .assertThatNoErrorsArePresent() + .assertThatField(DATA_FIELD_FOO_BAR) + .as(FooBar.class).usingRecursiveComparison().ignoringAllOverriddenEquals() + .isEqualTo(expected); + } + + @Test + @DisplayName("Test perform with operation name.") + void testPerformWithOperationName() throws IOException { + // WHEN - THEN + graphQLTestTemplate.perform(MULTIPLE_QUERIES, OPERATION_NAME_TEST_QUERY_1) + .assertThatNoErrorsArePresent() + .assertThatField(DATA_FIELD_DUMMY).asBoolean().isTrue(); + graphQLTestTemplate.perform(MULTIPLE_QUERIES, OPERATION_NAME_TEST_QUERY_2) + .assertThatNoErrorsArePresent() + .assertThatField(DATA_FIELD_OTHER_QUERY).asString().isEqualTo(TEST); + } + + @Test + @DisplayName("Test perform with GraphQL errors.") + void testPerformWithGraphQLError() throws IOException { + graphQLTestTemplate + .postForResource(SIMPLE_TEST_QUERY, Collections.singletonList(TEST_FRAGMENT_FILE)) + .assertThatDataField().isNotPresentOrNull() + .and().assertThatNumberOfErrors().isOne() + .and().assertThatListOfErrors().extracting(GraphQLError::getMessage) + .allMatch(message -> message.contains("UnusedFragment")); + } + + @Test + @DisplayName("Test perform with all possible inputs.") + void testPerformWithAllInputs() throws IOException { + // GIVEN + final ObjectNode variables = objectMapper.createObjectNode(); + variables.put(INPUT_STRING_NAME, INPUT_STRING_VALUE); + variables.put(INPUT_HEADER_NAME, TEST_HEADER_NAME); + final HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.add(TEST_HEADER_NAME, TEST_HEADER_VALUE); + // WHEN - THEN + graphQLTestTemplate + .withHeaders(httpHeaders) + .perform(COMPLEX_TEST_QUERY, OPERATION_NAME_COMPLEX_QUERY, variables, Collections.singletonList(TEST_FRAGMENT_FILE)) - .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_FOO_BAR).as(FooBar.class) - .usingRecursiveComparison() - .ignoringAllOverriddenEquals() - .isEqualTo(FooBar.builder().foo(FOO).bar(BAR).build()); - } - - @Test - @DisplayName("Test perform with variables.") - void testPerformWithVariables() throws IOException { - // GIVEN - final ObjectNode variables = objectMapper.createObjectNode(); - variables.put(INPUT_STRING_NAME, INPUT_STRING_VALUE); - // WHEN - THEN - graphQLTestTemplate.perform(QUERY_WITH_VARIABLES, variables) - .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString().isEqualTo(INPUT_STRING_VALUE); - } - - @Test - @DisplayName("Test perform with variables and operation name") - void testPerformWithOperationAndVariables() throws IOException { - // GIVEN - final ObjectNode variables = objectMapper.createObjectNode(); - variables.put(INPUT_STRING_NAME, INPUT_STRING_VALUE); - // WHEN - THEN - graphQLTestTemplate.perform(MULTIPLE_QUERIES, OPERATION_NAME_WITH_VARIABLES, variables) - .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString().isEqualTo(INPUT_STRING_VALUE); - } - - @Test - @DisplayName("Test perform with variables and fragments") - void testPerformWithVariablesAndFragments() throws IOException { - // GIVEN - final FooBar expected = new FooBar(String.valueOf(UUID.randomUUID()), String.valueOf(UUID.randomUUID())); - final ObjectNode variables = objectMapper.valueToTree(expected); - // WHEN - THEN - graphQLTestTemplate - .perform(SIMPLE_TEST_QUERY_WITH_FRAGMENTS, variables, Collections.singletonList(TEST_FRAGMENT_FILE)) - .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_FOO_BAR) - .as(FooBar.class).usingRecursiveComparison().ignoringAllOverriddenEquals().isEqualTo(expected); - } - - @Test - @DisplayName("Test perform with operation name.") - void testPerformWithOperationName() throws IOException { - // WHEN - THEN - graphQLTestTemplate.perform(MULTIPLE_QUERIES, OPERATION_NAME_TEST_QUERY_1) - .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_DUMMY).asBoolean().isTrue(); - graphQLTestTemplate.perform(MULTIPLE_QUERIES, OPERATION_NAME_TEST_QUERY_2) - .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_OTHER_QUERY).asString().isEqualTo(TEST); - } - - @Test - @DisplayName("Test perform with GraphQL errors.") - void testPerformWithGraphQLError() throws IOException { - graphQLTestTemplate.postForResource(SIMPLE_TEST_QUERY, Collections.singletonList(TEST_FRAGMENT_FILE)) - .assertThatDataField().isNotPresentOrNull() - .and().assertThatNumberOfErrors().isOne() - .and().assertThatListOfErrors().extracting(GraphQLError::getMessage) - .allMatch(message -> message.contains("UnusedFragment")); - } - - @Test - @DisplayName("Test perform with all possible inputs.") - void testPerformWithAllInputs() throws IOException { - // GIVEN - final ObjectNode variables = objectMapper.createObjectNode(); - variables.put(INPUT_STRING_NAME, INPUT_STRING_VALUE); - variables.put(INPUT_HEADER_NAME, TEST_HEADER_NAME); - final HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.add(TEST_HEADER_NAME, TEST_HEADER_VALUE); - // WHEN - THEN - graphQLTestTemplate - .withHeaders(httpHeaders) - .perform(COMPLEX_TEST_QUERY, OPERATION_NAME_COMPLEX_QUERY, variables, - Collections.singletonList(TEST_FRAGMENT_FILE)) - .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_QUERY_WITH_HEADER).asString().isEqualTo(TEST_HEADER_VALUE) - .and().assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString().isEqualTo(INPUT_STRING_VALUE) - .and().assertThatField(DATA_FIELD_FOO_BAR).as(FooBar.class).isEqualTo(new FooBar(FOO, BAR)); - } - - @Test - @DisplayName("Test post with custom payload.") - void testPost() { - // GIVEN - final HttpHeaders httpHeaders = new HttpHeaders(); - httpHeaders.add(TEST_HEADER_NAME, TEST_HEADER_VALUE); - final String payload = "{\"query\":" - + "\"query ($input: String!, $headerName: String!) " - + "{ queryWithVariables(input: $input) queryWithHeader(headerName: $headerName) }\", " - + "\"variables\": {\"input\": \"input-value\", \"headerName\": \"x-test\"}}"; - // WHEN - THEN - graphQLTestTemplate - .withHeaders(httpHeaders) - .post(payload) - .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString().isEqualTo(INPUT_STRING_VALUE) - .and().assertThatField(DATA_FIELD_QUERY_WITH_HEADER).asString().isEqualTo(TEST_HEADER_VALUE); - } + .assertThatNoErrorsArePresent() + .assertThatField(DATA_FIELD_QUERY_WITH_HEADER).asString().isEqualTo(TEST_HEADER_VALUE) + .and().assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString() + .isEqualTo(INPUT_STRING_VALUE) + .and().assertThatField(DATA_FIELD_FOO_BAR).as(FooBar.class).isEqualTo(new FooBar(FOO, BAR)); + } + + @Test + @DisplayName("Test post with custom payload.") + void testPost() { + // GIVEN + final HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.add(TEST_HEADER_NAME, TEST_HEADER_VALUE); + final String payload = "{\"query\":" + + "\"query ($input: String!, $headerName: String!) " + + "{ queryWithVariables(input: $input) queryWithHeader(headerName: $headerName) }\", " + + "\"variables\": {\"input\": \"input-value\", \"headerName\": \"x-test\"}}"; + // WHEN - THEN + graphQLTestTemplate + .withHeaders(httpHeaders) + .post(payload) + .assertThatNoErrorsArePresent() + .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString().isEqualTo(INPUT_STRING_VALUE) + .and().assertThatField(DATA_FIELD_QUERY_WITH_HEADER).asString() + .isEqualTo(TEST_HEADER_VALUE); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateTest.java index 1fea3f62..9cbca931 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateTest.java @@ -1,6 +1,10 @@ package com.graphql.spring.boot.test; +import static org.assertj.core.api.Assertions.assertThat; + import com.fasterxml.jackson.databind.ObjectMapper; +import java.nio.charset.StandardCharsets; +import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -10,180 +14,179 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.http.HttpHeaders; -import java.nio.charset.StandardCharsets; -import java.util.Collections; - -import static org.assertj.core.api.Assertions.assertThat; - @ExtendWith(MockitoExtension.class) class GraphQLTestTemplateTest { - private static final String GRAPHQL_ENDPOINT = "/test-graphql-endpoint"; - private static final String HEADER_NAME_1 = "header-1"; - private static final String HEADER_VALUE_1 = "value-1"; - private static final String HEADER_NAME_2 = "header-2"; - private static final String HEADER_VALUE_2 = "value-2"; - private static final String MOCK_BEARER_TOKEN = "mock token"; - private static final String TEST_USERNAME = "test"; - private static final String TEST_PASSWORD = "value"; - private static final String ENCODED_BASIC_AUTH = "dGVzdDp2YWx1ZQ=="; - private static final String BASIC_AUTH_PREFIX = "Basic "; - private static final String BEARER_AUTH_PREFIX = "Bearer "; - - @Mock - private ResourceLoader resourceLoader; - - @Mock - private TestRestTemplate testRestTemplate; - - private GraphQLTestTemplate graphQLTestTemplate; - - @BeforeEach - void setUp() { - graphQLTestTemplate = new GraphQLTestTemplate(resourceLoader, testRestTemplate, GRAPHQL_ENDPOINT, - new ObjectMapper()); - } - - @Test - void testAddHeader() { - // WHEN - graphQLTestTemplate.addHeader(HEADER_NAME_1, HEADER_VALUE_1); - graphQLTestTemplate.addHeader(HEADER_NAME_2, HEADER_VALUE_2); - // THEN - assertThatContainsAllHeaders(); - } - - @Test - void testWithAdditionalHeader() { - // WHEN - final GraphQLTestTemplate actual = graphQLTestTemplate - .withAdditionalHeader(HEADER_NAME_1, HEADER_VALUE_1) - .withAdditionalHeader(HEADER_NAME_2, HEADER_VALUE_2); - // THEN - assertThat(actual).isSameAs(graphQLTestTemplate); - assertThatContainsAllHeaders(); - } - - @Test - void testWithAdditionalHeaders() { - // GIVEN - graphQLTestTemplate.getHeaders().add(HEADER_NAME_1, HEADER_VALUE_1); - final HttpHeaders additionalHeaders = new HttpHeaders(); - additionalHeaders.add(HEADER_NAME_2, HEADER_VALUE_2); - // WHEN - final GraphQLTestTemplate actualGraphqlTestTemplate = graphQLTestTemplate - .withAdditionalHeaders(additionalHeaders); - // THEN - assertThat(actualGraphqlTestTemplate).isSameAs(graphQLTestTemplate); - assertThatContainsAllHeaders(); - } - - @Test - void testWithHeaders() { - // GIVEN - graphQLTestTemplate.getHeaders().add(HEADER_NAME_1, HEADER_VALUE_1); - final HttpHeaders newHeaders = new HttpHeaders(); - newHeaders.add(HEADER_NAME_2, HEADER_VALUE_2); - // WHEN - final GraphQLTestTemplate actual = graphQLTestTemplate - .withHeaders(newHeaders); - // THEN - assertThat(actual).isSameAs(graphQLTestTemplate); - assertThat(actual.getHeaders()).hasSize(1); - assertThatContainsSecondHeader(); - } - - @Test - void testSetHeaders() { - // GIVEN - graphQLTestTemplate.getHeaders().add(HEADER_NAME_1, HEADER_VALUE_1); - final HttpHeaders newHeaders = new HttpHeaders(); - newHeaders.add(HEADER_NAME_2, HEADER_VALUE_2); - // WHEN - graphQLTestTemplate.setHeaders(newHeaders); - // THEN - assertThat(graphQLTestTemplate.getHeaders()).hasSize(1); - assertThatContainsSecondHeader(); - } - - @Test - void testWithClearHeaders() { - // GIVEN - graphQLTestTemplate.getHeaders().add(HEADER_NAME_1, HEADER_VALUE_1); - // WHEN - final GraphQLTestTemplate actual = graphQLTestTemplate.withClearHeaders(); - // THEN - assertThat(graphQLTestTemplate).isSameAs(actual); - assertThat(graphQLTestTemplate.getHeaders()).isEmpty(); - } - - @Test - void testClearHeaders() { - // GIVEN - graphQLTestTemplate.getHeaders().add(HEADER_NAME_1, HEADER_VALUE_1); - // WHEN - graphQLTestTemplate.clearHeaders(); - // THEN - assertThat(graphQLTestTemplate.getHeaders()).isEmpty(); - } - - @Test - void testWithBearerAuth() { - // WHEN - final GraphQLTestTemplate actual = graphQLTestTemplate.withBearerAuth(MOCK_BEARER_TOKEN); - // THEN - assertThat(actual).isSameAs(graphQLTestTemplate); - assertAuthHeader(BEARER_AUTH_PREFIX, MOCK_BEARER_TOKEN); - } - - @Test - void testWithEncodedBasicAuth() { - // WHEN - final GraphQLTestTemplate actual = graphQLTestTemplate.withBasicAuth(ENCODED_BASIC_AUTH); - // THEN - assertThat(actual).isSameAs(graphQLTestTemplate); - assertAuthHeader(BASIC_AUTH_PREFIX, ENCODED_BASIC_AUTH); - } - - @Test - void testWithBasicAuth() { - // WHEN - final GraphQLTestTemplate actual = graphQLTestTemplate.withBasicAuth(TEST_USERNAME, TEST_PASSWORD); - // THEN - assertThat(actual).isSameAs(graphQLTestTemplate); - assertAuthHeader(BASIC_AUTH_PREFIX, ENCODED_BASIC_AUTH); - } - - @Test - void testWithBasicAuthCharset() { - // WHEN - final GraphQLTestTemplate actual = graphQLTestTemplate.withBasicAuth(TEST_USERNAME, TEST_PASSWORD, + private static final String GRAPHQL_ENDPOINT = "/test-graphql-endpoint"; + private static final String HEADER_NAME_1 = "header-1"; + private static final String HEADER_VALUE_1 = "value-1"; + private static final String HEADER_NAME_2 = "header-2"; + private static final String HEADER_VALUE_2 = "value-2"; + private static final String MOCK_BEARER_TOKEN = "mock token"; + private static final String TEST_USERNAME = "test"; + private static final String TEST_PASSWORD = "value"; + private static final String ENCODED_BASIC_AUTH = "dGVzdDp2YWx1ZQ=="; + private static final String BASIC_AUTH_PREFIX = "Basic "; + private static final String BEARER_AUTH_PREFIX = "Bearer "; + + @Mock + private ResourceLoader resourceLoader; + + @Mock + private TestRestTemplate testRestTemplate; + + private GraphQLTestTemplate graphQLTestTemplate; + + @BeforeEach + void setUp() { + graphQLTestTemplate = new GraphQLTestTemplate(resourceLoader, testRestTemplate, + GRAPHQL_ENDPOINT, + new ObjectMapper()); + } + + @Test + void testAddHeader() { + // WHEN + graphQLTestTemplate.addHeader(HEADER_NAME_1, HEADER_VALUE_1); + graphQLTestTemplate.addHeader(HEADER_NAME_2, HEADER_VALUE_2); + // THEN + assertThatContainsAllHeaders(); + } + + @Test + void testWithAdditionalHeader() { + // WHEN + final GraphQLTestTemplate actual = graphQLTestTemplate + .withAdditionalHeader(HEADER_NAME_1, HEADER_VALUE_1) + .withAdditionalHeader(HEADER_NAME_2, HEADER_VALUE_2); + // THEN + assertThat(actual).isSameAs(graphQLTestTemplate); + assertThatContainsAllHeaders(); + } + + @Test + void testWithAdditionalHeaders() { + // GIVEN + graphQLTestTemplate.getHeaders().add(HEADER_NAME_1, HEADER_VALUE_1); + final HttpHeaders additionalHeaders = new HttpHeaders(); + additionalHeaders.add(HEADER_NAME_2, HEADER_VALUE_2); + // WHEN + final GraphQLTestTemplate actualGraphqlTestTemplate = graphQLTestTemplate + .withAdditionalHeaders(additionalHeaders); + // THEN + assertThat(actualGraphqlTestTemplate).isSameAs(graphQLTestTemplate); + assertThatContainsAllHeaders(); + } + + @Test + void testWithHeaders() { + // GIVEN + graphQLTestTemplate.getHeaders().add(HEADER_NAME_1, HEADER_VALUE_1); + final HttpHeaders newHeaders = new HttpHeaders(); + newHeaders.add(HEADER_NAME_2, HEADER_VALUE_2); + // WHEN + final GraphQLTestTemplate actual = graphQLTestTemplate + .withHeaders(newHeaders); + // THEN + assertThat(actual).isSameAs(graphQLTestTemplate); + assertThat(actual.getHeaders()).hasSize(1); + assertThatContainsSecondHeader(); + } + + @Test + void testSetHeaders() { + // GIVEN + graphQLTestTemplate.getHeaders().add(HEADER_NAME_1, HEADER_VALUE_1); + final HttpHeaders newHeaders = new HttpHeaders(); + newHeaders.add(HEADER_NAME_2, HEADER_VALUE_2); + // WHEN + graphQLTestTemplate.setHeaders(newHeaders); + // THEN + assertThat(graphQLTestTemplate.getHeaders()).hasSize(1); + assertThatContainsSecondHeader(); + } + + @Test + void testWithClearHeaders() { + // GIVEN + graphQLTestTemplate.getHeaders().add(HEADER_NAME_1, HEADER_VALUE_1); + // WHEN + final GraphQLTestTemplate actual = graphQLTestTemplate.withClearHeaders(); + // THEN + assertThat(graphQLTestTemplate).isSameAs(actual); + assertThat(graphQLTestTemplate.getHeaders()).isEmpty(); + } + + @Test + void testClearHeaders() { + // GIVEN + graphQLTestTemplate.getHeaders().add(HEADER_NAME_1, HEADER_VALUE_1); + // WHEN + graphQLTestTemplate.clearHeaders(); + // THEN + assertThat(graphQLTestTemplate.getHeaders()).isEmpty(); + } + + @Test + void testWithBearerAuth() { + // WHEN + final GraphQLTestTemplate actual = graphQLTestTemplate.withBearerAuth(MOCK_BEARER_TOKEN); + // THEN + assertThat(actual).isSameAs(graphQLTestTemplate); + assertAuthHeader(BEARER_AUTH_PREFIX, MOCK_BEARER_TOKEN); + } + + @Test + void testWithEncodedBasicAuth() { + // WHEN + final GraphQLTestTemplate actual = graphQLTestTemplate.withBasicAuth(ENCODED_BASIC_AUTH); + // THEN + assertThat(actual).isSameAs(graphQLTestTemplate); + assertAuthHeader(BASIC_AUTH_PREFIX, ENCODED_BASIC_AUTH); + } + + @Test + void testWithBasicAuth() { + // WHEN + final GraphQLTestTemplate actual = graphQLTestTemplate + .withBasicAuth(TEST_USERNAME, TEST_PASSWORD); + // THEN + assertThat(actual).isSameAs(graphQLTestTemplate); + assertAuthHeader(BASIC_AUTH_PREFIX, ENCODED_BASIC_AUTH); + } + + @Test + void testWithBasicAuthCharset() { + // WHEN + final GraphQLTestTemplate actual = graphQLTestTemplate + .withBasicAuth(TEST_USERNAME, TEST_PASSWORD, StandardCharsets.UTF_8); - // THEN - assertThat(actual).isSameAs(graphQLTestTemplate); - assertAuthHeader(BASIC_AUTH_PREFIX, ENCODED_BASIC_AUTH); - } - - private void assertAuthHeader(final String authPrefix, final String authValue) { - assertThatContainsHeader(HttpHeaders.AUTHORIZATION, authPrefix + authValue); - } - - private void assertThatContainsAllHeaders() { - final HttpHeaders actual = graphQLTestTemplate.getHeaders(); - assertThat(actual).hasSize(2); - assertThatContainsFirstHeader(); - assertThatContainsSecondHeader(); - } - - private void assertThatContainsSecondHeader() { - assertThatContainsHeader(HEADER_NAME_2, HEADER_VALUE_2); - } - - private void assertThatContainsFirstHeader() { - assertThatContainsHeader(HEADER_NAME_1, HEADER_VALUE_1); - } - - private void assertThatContainsHeader(final String headerName, final String headerValue) { - assertThat(graphQLTestTemplate.getHeaders()).containsEntry(headerName, Collections.singletonList(headerValue)); - } + // THEN + assertThat(actual).isSameAs(graphQLTestTemplate); + assertAuthHeader(BASIC_AUTH_PREFIX, ENCODED_BASIC_AUTH); + } + + private void assertAuthHeader(final String authPrefix, final String authValue) { + assertThatContainsHeader(HttpHeaders.AUTHORIZATION, authPrefix + authValue); + } + + private void assertThatContainsAllHeaders() { + final HttpHeaders actual = graphQLTestTemplate.getHeaders(); + assertThat(actual).hasSize(2); + assertThatContainsFirstHeader(); + assertThatContainsSecondHeader(); + } + + private void assertThatContainsSecondHeader() { + assertThatContainsHeader(HEADER_NAME_2, HEADER_VALUE_2); + } + + private void assertThatContainsFirstHeader() { + assertThatContainsHeader(HEADER_NAME_1, HEADER_VALUE_1); + } + + private void assertThatContainsHeader(final String headerName, final String headerValue) { + assertThat(graphQLTestTemplate.getHeaders()) + .containsEntry(headerName, Collections.singletonList(headerValue)); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/TestApplication.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/TestApplication.java index 8f4ab79f..02a89a21 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/TestApplication.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/TestApplication.java @@ -6,7 +6,7 @@ @SpringBootApplication public class TestApplication { - public static void main(String[] args) { - SpringApplication.run(TestApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(TestApplication.class, args); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/DummyQuery.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/DummyQuery.java index 74ccb2bf..26aecc58 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/DummyQuery.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/DummyQuery.java @@ -3,37 +3,36 @@ import graphql.kickstart.servlet.context.GraphQLServletContext; import graphql.kickstart.tools.GraphQLQueryResolver; import graphql.schema.DataFetchingEnvironment; -import org.springframework.stereotype.Service; - import java.util.Optional; +import org.springframework.stereotype.Service; @Service public class DummyQuery implements GraphQLQueryResolver { - public boolean dummy() { - return true; - } - - public String otherQuery() { - return "TEST"; - } - - public FooBar fooBar(String foo, String bar) { - return FooBar.builder() - .bar(Optional.ofNullable(bar).orElse("BAR")) - .foo(Optional.ofNullable(foo).orElse("FOO")) - .build(); - } - - public String queryWithVariables(final String input) { - return input; - } - - public String queryWithHeader( - final String headerName, - final DataFetchingEnvironment dataFetchingEnvironment - ) { - return ((GraphQLServletContext) dataFetchingEnvironment.getContext()).getHttpServletRequest() - .getHeader(headerName); - } + public boolean dummy() { + return true; + } + + public String otherQuery() { + return "TEST"; + } + + public FooBar fooBar(String foo, String bar) { + return FooBar.builder() + .bar(Optional.ofNullable(bar).orElse("BAR")) + .foo(Optional.ofNullable(foo).orElse("FOO")) + .build(); + } + + public String queryWithVariables(final String input) { + return input; + } + + public String queryWithHeader( + final String headerName, + final DataFetchingEnvironment dataFetchingEnvironment + ) { + return ((GraphQLServletContext) dataFetchingEnvironment.getContext()).getHttpServletRequest() + .getHeader(headerName); + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/FooBar.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/FooBar.java index 92270d70..d321c772 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/FooBar.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/FooBar.java @@ -10,6 +10,7 @@ @NoArgsConstructor @AllArgsConstructor public class FooBar { - private String foo; - private String bar; + + private String foo; + private String bar; } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/SubscriptionListener.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/SubscriptionListener.java index 85e0b42c..5a54a9e2 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/SubscriptionListener.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/SubscriptionListener.java @@ -13,19 +13,21 @@ @RequiredArgsConstructor public class SubscriptionListener implements ApolloSubscriptionConnectionListener { - private final ObjectMapper objectMapper; + private final ObjectMapper objectMapper; - @Getter - private String expectedConnectionInitParamValue; + @Getter + private String expectedConnectionInitParamValue; - @Override - public void onConnect(final SubscriptionSession session, final OperationMessage message) { - final InitPayload initPayload = objectMapper.convertValue(message.getPayload(), InitPayload.class); - expectedConnectionInitParamValue = initPayload.getInitParamValue(); - } + @Override + public void onConnect(final SubscriptionSession session, final OperationMessage message) { + final InitPayload initPayload = objectMapper + .convertValue(message.getPayload(), InitPayload.class); + expectedConnectionInitParamValue = initPayload.getInitParamValue(); + } - @Data - private static class InitPayload { - private String initParamValue; - } + @Data + private static class InitPayload { + + private String initParamValue; + } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/TestSubscriptions.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/TestSubscriptions.java index 00798a11..d28312b8 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/TestSubscriptions.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/TestSubscriptions.java @@ -2,35 +2,34 @@ import graphql.kickstart.tools.GraphQLSubscriptionResolver; import io.reactivex.Flowable; +import java.util.concurrent.TimeUnit; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; -import java.util.concurrent.TimeUnit; - @Service @RequiredArgsConstructor public class TestSubscriptions implements GraphQLSubscriptionResolver { - private final SubscriptionListener subscriptionListener; + private final SubscriptionListener subscriptionListener; - public Flowable timer() { - return Flowable - .intervalRange(0, 10, 0,1, TimeUnit.MILLISECONDS); - } + public Flowable timer() { + return Flowable + .intervalRange(0, 10, 0, 1, TimeUnit.MILLISECONDS); + } - public Flowable subscriptionWithParameter(final String param) { - return Flowable.just(param); - } + public Flowable subscriptionWithParameter(final String param) { + return Flowable.just(param); + } - public Flowable subscriptionWithInitPayload() { - return Flowable.just(subscriptionListener.getExpectedConnectionInitParamValue()); - } + public Flowable subscriptionWithInitPayload() { + return Flowable.just(subscriptionListener.getExpectedConnectionInitParamValue()); + } - public Flowable subscriptionThatTimesOut() { - return Flowable.interval(20000, 20000, TimeUnit.MILLISECONDS); - } + public Flowable subscriptionThatTimesOut() { + return Flowable.interval(20000, 20000, TimeUnit.MILLISECONDS); + } - public Flowable subscriptionThatThrowsException() { - throw new RuntimeException("Test exception."); - } + public Flowable subscriptionThatThrowsException() { + throw new RuntimeException("Test exception."); + } } diff --git a/graphql-spring-boot-test/src/test/resources/response-with-nested-list.json b/graphql-spring-boot-test/src/test/resources/response-with-nested-list.json index ffac2f16..ad65c001 100644 --- a/graphql-spring-boot-test/src/test/resources/response-with-nested-list.json +++ b/graphql-spring-boot-test/src/test/resources/response-with-nested-list.json @@ -1,16 +1,17 @@ { "data": { - "externalList": [ - { - "fooList": [ - "foo1", "foo2" - ] - }, - { - "fooList": [ - "foo3" - ] - } - ] + "externalList": [ + { + "fooList": [ + "foo1", + "foo2" + ] + }, + { + "fooList": [ + "foo3" + ] + } + ] } -} \ No newline at end of file +} diff --git a/voyager-spring-boot-starter/LICENSE.md b/voyager-spring-boot-starter/LICENSE.md index 9deca2c8..8ab1ef6c 100644 --- a/voyager-spring-boot-starter/LICENSE.md +++ b/voyager-spring-boot-starter/LICENSE.md @@ -2,8 +2,17 @@ The MIT License (MIT) Copyright (c) 2016 Oembedler Inc. and Contributors -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, +sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT +NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES +OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.