diff --git a/src/main/java/graphql/execution/ValuesResolverConversion.java b/src/main/java/graphql/execution/ValuesResolverConversion.java index 20e9feb552..ca804c1cc9 100644 --- a/src/main/java/graphql/execution/ValuesResolverConversion.java +++ b/src/main/java/graphql/execution/ValuesResolverConversion.java @@ -658,7 +658,13 @@ private static Object literalToInternalValueImpl( ) { if (inputValue instanceof VariableReference) { String variableName = ((VariableReference) inputValue).getName(); - return coercedVariables.get(variableName); + Object variableValue = coercedVariables.get(variableName); + // a nullable variable with a default value is allowed in a non null position (eg a list item), so an explicit null + // has to be rejected here rather than ending up in a non null list + if (variableValue == null && isNonNull(type)) { + throw new NonNullableValueCoercedAsNullException(type); + } + return variableValue; } if (inputValue instanceof NullValue) { return null; @@ -808,7 +814,8 @@ private static Object literalToInternalValueForInputObject( locale); coercedValues.put(fieldName, coercedDefaultValue); } else if (isNonNull(fieldType) && (!hasValue || isNullValue(value))) { - return assertShouldNeverHappen("Should have been validated before"); + // a nullable variable with a default value is allowed in a non null position, so an explicit null gets here + throw new NonNullableValueCoercedAsNullException(fieldName, emptyList(), fieldType); } else if (hasValue) { if (isNullValue(value)) { coercedValues.put(fieldName, value); diff --git a/src/test/groovy/graphql/execution/ValuesResolverNullabilityTest.groovy b/src/test/groovy/graphql/execution/ValuesResolverNullabilityTest.groovy new file mode 100644 index 0000000000..30e498c123 --- /dev/null +++ b/src/test/groovy/graphql/execution/ValuesResolverNullabilityTest.groovy @@ -0,0 +1,173 @@ +package graphql.execution + +import graphql.ErrorType +import graphql.ExceptionWhileDataFetching +import graphql.ExecutionInput +import graphql.ExecutionResult +import graphql.GraphQL +import graphql.ParseAndValidate +import graphql.TestUtil +import graphql.schema.DataFetcher +import spock.lang.Specification + +class ValuesResolverNullabilityTest extends Specification { + + def "nullable variable with a non-null default at #argumentType with variables #variables"() { + given: + def received = [] + DataFetcher fetcher = { env -> + received.add(env.getArgument('arg')) + 'resolved' + } + def graphQL = buildGraphQL(argumentType, fetcher) + def query = 'query($v: String = "x") { f(arg: ' + literal + ') good }' + + when: + def result = executeValid(graphQL, query, variables) + + then: + result.data == [f: fails ? null : 'resolved', good: 'good'] + result.errors.size() == (fails ? 1 : 0) + result.errors*.path == (fails ? [['f']] : []) + result.errors.every { it instanceof ExceptionWhileDataFetching && it.exception instanceof NonNullableValueCoercedAsNullException } + received == (fails ? [] : [expectedValue]) + + where: + argumentType | literal | variables | expectedValue | fails + '[String!]!' | '[$v]' | [:] | ['x'] | false + '[String!]!' | '[$v]' | [v: 'z'] | ['z'] | false + '[String!]!' | '[$v]' | [v: null] | null | true + 'RequiredInput'| '{a: $v}' | [:] | [a: 'x'] | false + 'RequiredInput'| '{a: $v}' | [v: 'z'] | [a: 'z'] | false + 'RequiredInput'| '{a: $v}' | [v: null] | null | true + 'ListInput' | '{items:[$v]}'| [:] | [items: ['x']] | false + 'ListInput' | '{items:[$v]}'| [v: 'z'] | [items: ['z']] | false + 'ListInput' | '{items:[$v]}'| [v: null] | null | true + '[[String!]!]!'| '[[$v]]' | [:] | [['x']] | false + '[[String!]!]!'| '[[$v]]' | [v: 'z'] | [['z']] | false + '[[String!]!]!'| '[[$v]]' | [v: null] | null | true + } + + def "input field default distinguishes omission from null for #variableDefinition with #variables"() { + given: + def received = [] + DataFetcher fetcher = { env -> + received.add(env.getArgument('arg')) + 'resolved' + } + def graphQL = buildGraphQL('DefaultInput', fetcher) + def query = 'query($v: ' + variableDefinition + ') { f(arg: {a: $v}) good }' + + when: + def result = executeValid(graphQL, query, variables) + + then: + result.data == [f: fails ? null : 'resolved', good: 'good'] + result.errors.size() == (fails ? 1 : 0) + result.errors*.path == (fails ? [['f']] : []) + result.errors.every { it instanceof ExceptionWhileDataFetching && it.exception instanceof NonNullableValueCoercedAsNullException } + received == (fails ? [] : [[a: expectedValue]]) + + where: + variableDefinition | variables | expectedValue | fails + 'String' | [:] | 'd' | false + 'String' | [v: 'z'] | 'z' | false + 'String' | [v: null] | null | true + 'String = "x"' | [:] | 'x' | false + 'String = "x"' | [v: null] | null | true + 'String = null' | [:] | null | true + } + + def "nullable positions preserve missing and null variables in #literal with #variables"() { + given: + def received = [] + DataFetcher fetcher = { env -> + received.add(env.getArgument('arg')) + 'resolved' + } + def graphQL = buildGraphQL(argumentType, fetcher) + def query = 'query($v: String) { f(arg: ' + literal + ') }' + + when: + def result = executeValid(graphQL, query, variables) + + then: + result.errors.empty + result.data == [f: 'resolved'] + received == [expectedValue] + + where: + argumentType | literal | variables | expectedValue + '[String]' | '[$v]' | [:] | [null] + '[String]' | '[$v]' | [v: null] | [null] + 'NullableInput'| '{a: $v}' | [:] | [:] + 'NullableInput'| '{a: $v}' | [v: null] | [a: null] + } + + def "a nullable variable without a non-null default cannot be used as a non-null list item"() { + given: + int calls = 0 + DataFetcher fetcher = { calls++; 'unexpected' } + def graphQL = buildGraphQL('[String!]!', fetcher) + def input = ExecutionInput.newExecutionInput('query($v: ' + variableDefinition + ') { f(arg: [$v]) }').build() + + when: + def result = graphQL.execute(input) + + then: + !result.dataPresent + result.errors.size() == 1 + result.errors[0].errorType == ErrorType.ValidationError + calls == 0 + + where: + variableDefinition << ['String', 'String = null'] + } + + def "#operation coercion error uses the response alias and propagates through #resultType"() { + given: + DataFetcher fetcher = { env -> + env.getArgument('arg') + 'unexpected' + } + def graphQL = buildGraphQL('[String!]!', fetcher, resultType) + def query = operation + '($v: String = "x") { alias: f(arg: [$v]) }' + + when: + def result = executeValid(graphQL, query, [v: null]) + + then: + result.dataPresent + result.data == (resultType == 'String!' ? null : [alias: null]) + result.errors.size() == 1 + result.errors[0].path == ['alias'] + !result.errors[0].locations.empty + result.errors[0] instanceof ExceptionWhileDataFetching + result.errors[0].exception instanceof NonNullableValueCoercedAsNullException + + where: + operation | resultType + 'query' | 'String' + 'query' | 'String!' + 'mutation' | 'String' + 'mutation' | 'String!' + } + + private GraphQL buildGraphQL(String argumentType, DataFetcher fetcher, String resultType = 'String') { + def sdl = """ + input RequiredInput { a: String! } + input DefaultInput { a: String! = "d" } + input NullableInput { a: String } + input ListInput { items: [String!] } + type Query { f(arg: $argumentType): $resultType good: String! } + type Mutation { f(arg: $argumentType): $resultType } + """ + TestUtil.graphQL(sdl, [Query: [f: fetcher, good: { 'good' } as DataFetcher], Mutation: [f: fetcher]]).build() + } + + private ExecutionResult executeValid(GraphQL graphQL, String query, Map variables) { + def input = ExecutionInput.newExecutionInput(query).variables(variables).build() + assert !ParseAndValidate.parseAndValidate(graphQL.graphQLSchema, input).isFailure() + graphQL.execute(input) + } +} diff --git a/src/test/groovy/graphql/execution/ValuesResolverTest.groovy b/src/test/groovy/graphql/execution/ValuesResolverTest.groovy index 291314f575..cc4d7e7a4b 100644 --- a/src/test/groovy/graphql/execution/ValuesResolverTest.groovy +++ b/src/test/groovy/graphql/execution/ValuesResolverTest.groovy @@ -1365,6 +1365,41 @@ class ValuesResolverTest extends Specification { error.message == "Argument 'arg' has coerced Null value for NonNull type 'inputObject!'" } + def "list item of Non-Nullable type and with null variable value throws error"() { + given: + // eg query($var: String = "default") { field(arg: [$var]) } with {"var": null} + def fieldArgument = newArgument().name("arg").type(list(nonNull(GraphQLString))).build() + def argument = new Argument("arg", new ArrayValue([new VariableReference("var")])) + + when: + def variables = CoercedVariables.of(["var": null]) + ValuesResolver.getArgumentValues([fieldArgument], [argument], variables, graphQLContext, locale) + + then: + def error = thrown(NonNullableValueCoercedAsNullException) + error.message == "Coerced Null value for NonNull type 'String!'" + } + + def "input object field of Non-Nullable type and with null variable value throws error"() { + given: + // eg query($var: String = "default") { field(arg: {name: $var}) } with {"var": null} + def inputObjectType = newInputObject() + .name("inputObject") + .field(newInputObjectField().name("name").type(nonNull(GraphQLString))) + .build() + + def fieldArgument = newArgument().name("arg").type(inputObjectType).build() + def argument = new Argument("arg", new ObjectValue([new ObjectField("name", new VariableReference("var"))])) + + when: + def variables = CoercedVariables.of(["var": null]) + ValuesResolver.getArgumentValues([fieldArgument], [argument], variables, graphQLContext, locale) + + then: + def error = thrown(NonNullableValueCoercedAsNullException) + error.message == "Field 'name' has coerced Null value for NonNull type 'String!'" + } + def "invalid enum error message is not nested and contains source location - issue 2560"() { when: def graphQL = TestUtil.graphQL('''