Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/main/java/graphql/execution/ValuesResolverConversion.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ye old nullability on variables - this has long been a challenge around is a value present but null versus null because its absent.

I am not sure this is correct or that we can tell here if a value is present and was set explicitly to null versus being null

We may have to use graphql.execution.CoercedVariables#containsKey to distinguish

I would like @andimarek to comment on this PR

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fair concern, but i don't think the distinction changes the outcome at either site.

externalValueToInternalValueForVariables only puts a key into CoercedVariables when the variable was supplied (explicit null included) or has a default, so get() returning null here means either an explicit null or an absent variable with no default. for a non-null target both are invalid: graphql-js valueFromAST rejects a missing variable in a non-null list item the same way it rejects an explicit null. the one place absent has to behave differently is an input field with a default, and that branch already goes through containsKey (hasValue) and runs before the line i changed, so an absent variable still picks up the field default.

i ran the combinations against this branch to check:

query($v: String = "x") { list(arg: [$v]) }            no variables  -> [x]
query($v: String = "x") { list(arg: [$v]) }            {"v": null}   -> Coerced Null value for NonNull type 'String!'
query($v: String) { nullableItems(arg: [$v]) }          no variables  -> [null]  (unchanged)
query($v: String) { nullableItems(arg: [$v]) }          {"v": null}   -> [null]  (unchanged)
query($v: String) { obj(arg: {a: $v}) }   a: String! = "d"   no variables -> [a:d]
query($v: String) { obj(arg: {a: $v}) }   a: String! = "d"   {"v": null}  -> Field 'a' has coerced Null value for NonNull type 'String!'

an absent variable without a default can only reach the list item check with validation bypassed (a nullable variable with no default isn't allowed in a [String!] position, and a non-null variable fails variable coercion first), and rejecting it there still matches graphql-js. happy to switch the list item check to containsKey if you'd rather see the absent case spelled out, but the result would be the same.

}
if (inputValue instanceof NullValue) {
return null;
Expand Down Expand Up @@ -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);
Expand Down
173 changes: 173 additions & 0 deletions src/test/groovy/graphql/execution/ValuesResolverNullabilityTest.groovy
Original file line number Diff line number Diff line change
@@ -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<String, Object> variables) {
def input = ExecutionInput.newExecutionInput(query).variables(variables).build()
assert !ParseAndValidate.parseAndValidate(graphQL.graphQLSchema, input).isFailure()
graphQL.execute(input)
}
}
35 changes: 35 additions & 0 deletions src/test/groovy/graphql/execution/ValuesResolverTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -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('''
Expand Down
Loading