def rejects_none_and_undefined_errors(): with raises(TypeError) as exc_info: # noinspection PyTypeChecker format_error(None) # type: ignore assert str(exc_info.value) == "Expected a GraphQLError." with raises(TypeError) as exc_info: # noinspection PyTypeChecker format_error(Undefined) # type: ignore assert str(exc_info.value) == "Expected a GraphQLError."
def rejects_none_and_undefined_errors(): with raises(TypeError) as exc_info: # noinspection PyTypeChecker format_error(None) # type: ignore assert str(exc_info.value) == "Received no error object." with raises(TypeError) as exc_info: # noinspection PyTypeChecker format_error(Undefined) # type: ignore assert str(exc_info.value) == "Received no error object."
def execute_query(self, request, query, variables): result = schema.execute(query, context=request, variables=variables) if result.errors: return JsonResponse( {'errors': [format_error(e) for e in result.errors]}) else: return JsonResponse({'data': result.data})
def run_check(self): test_type = self.type data = Data(test=test_data) DataType = GraphQLObjectType( name='DataType', fields=lambda: { 'test': GraphQLField(test_type), 'nest': GraphQLField(DataType, resolver=lambda *_: data) } ) schema = GraphQLSchema(query=DataType) response = execute(schema, ast, data) if response.errors: result = { 'data': response.data, 'errors': [format_error(e) for e in response.errors] } else: result = { 'data': response.data } assert result == expected
def run_check(self): # type: (Any) -> None test_type = self.type data = Data(test=test_data) DataType = GraphQLObjectType( name="DataType", fields=lambda: { "test": GraphQLField(test_type), "nest": GraphQLField(DataType, resolver=lambda *_: data), }, ) schema = GraphQLSchema(query=DataType) response = execute(schema, ast, data) if response.errors: result = { "data": response.data, "errors": [format_error(e) for e in response.errors], } else: result = {"data": response.data} assert result == expected
def test_cannot_use_client_schema_for_general_execution(): customScalar = GraphQLScalarType(name='CustomScalar', serialize=lambda: None) schema = GraphQLSchema(query=GraphQLObjectType( name='Query', fields={ 'foo': GraphQLField(GraphQLString, args=OrderedDict([('custom1', GraphQLArgument(customScalar)), ('custom2', GraphQLArgument(customScalar))])) })) introspection = graphql(schema, introspection_query) client_schema = build_client_schema(introspection.data) class data: foo = 'bar' result = graphql( client_schema, 'query NoNo($v: CustomScalar) { foo(custom1: 123, custom2: $v) }', data, {'v': 'baz'}) assert result.data == {'foo': None} assert [format_error(e) for e in result.errors] == [{ 'locations': [{ 'column': 32, 'line': 1 }], 'message': 'Client Schema cannot be used for execution.' }]
def default_error_formatter_includes_path(): path = ['path', 3, 'to', 'field'] # noinspection PyArgumentEqualDefault e = GraphQLError('msg', None, None, None, path) formatted = format_error(e) assert formatted == e.formatted assert formatted == {'message': 'msg', 'locations': None, 'path': path}
def query(): # TODO: lock the playground behind debug mode if "text/html" == request.accept_mimetypes.best: return render_template("playground.html") try: graphql_query = request.json["query"] variables = request.json.get("variables") operation_name = request.json.get("operationName") except KeyError: abort(400, "No GraphQL query found in the request") context = {"request": request} result = graphql_sync( schema, graphql_query, root_value=None, variable_values=variables, context_value=context, operation_name=operation_name, ) response_data = {"data": result.data} if result.errors: response_data["errors"] = [format_error(err) for err in result.errors] return response_data
def default_error_formatter_includes_path(): path = ["path", 3, "to", "field"] # noinspection PyArgumentEqualDefault e = GraphQLError("msg", None, None, None, path) formatted = format_error(e) assert formatted == e.formatted assert formatted == {"message": "msg", "locations": None, "path": path}
def test_query_foo_with_null_geojson(self): # Query using for foos based on the related User foo_results = graphql_query_foos(self.client, variables=dict(key='fookit') ) assert not R.prop('errors', foo_results), R.dump_json(R.map(lambda e: format_error(e), R.prop('errors', foo_results))) assert 1 == R.length(R.map(R.omit_deep(omit_props), R.item_path(['data', 'foos'], foo_results)))
def formats_graphql_error(): source = Source( """ query { something }""" ) path: List[Union[int, str]] = ["one", 2] extensions = {"ext": None} error = GraphQLError( "test message", Node(), source, [14, 40], path, ValueError("original"), extensions=extensions, ) formatted = format_error(error) assert formatted == error.formatted assert formatted == { "message": "test message", "locations": [{"line": 2, "column": 14}, {"line": 3, "column": 20}], "path": path, "extensions": extensions, }
def test_create_user(self): values = dict(username="******", firstName='T', lastName='Rex', password=make_password("rrrrhhh", salt='not_random')) result = graphql_update_or_create_user(self.client, values) assert not R.prop('errors', result), R.dump_json(R.map(lambda e: format_error(e), R.prop('errors', result))) # look at the users added and omit the non-determinant values self.assertMatchSnapshot( R.omit_deep(omit_props, R.item_path(['data', 'createUser', 'user'], result)))
def uses_default_message(): # noinspection PyTypeChecker formatted = format_error(GraphQLError(None)) # type: ignore assert formatted == { "message": "An unknown error occurred.", "locations": None, "path": None, }
def includes_extension_fields(): error = GraphQLError("msg", extensions={"foo": "bar"}) formatted = format_error(error) assert formatted == error.formatted assert formatted == { "message": "msg", "locations": None, "path": None, "extensions": {"foo": "bar"}, }
def test_parse_error(): query = ''' qeury ''' result = graphql(StarWarsSchema, query) assert result.invalid formatted_error = format_error(result.errors[0]) assert formatted_error['locations'] == [{'column': 9, 'line': 2}] assert 'Syntax Error GraphQL request (2:9) Unexpected Name "qeury"' in formatted_error['message'] assert result.data is None
def test_errors_on_addition_of_input_field_of_incorrect_type(self): params = {'input': {'a': 'foo', 'b': 'bar', 'c': 'baz', 'd': 'dog'}} with raises(GraphQLError) as excinfo: check(self.doc, {}, params) assert format_error(excinfo.value) == { 'locations': [{'column': 13, 'line': 2}], 'message': 'Variable "$input" got invalid value {}.\n' 'In field "d": Expected type "ComplexScalar", found "dog".'.format(stringify(params['input'])) }
def test_errors_on_addition_of_unknown_input_field(self): params = {'input': {'a': 'foo', 'b': 'bar', 'c': 'baz', 'extra': 'dog'}} with raises(GraphQLError) as excinfo: check(self.doc, {}, params) assert format_error(excinfo.value) == { 'locations': [{'column': 13, 'line': 2}], 'message': 'Variable "$input" got invalid value {}.\n' 'In field "extra": Unknown field.'.format(stringify(params['input'])) }
def test_errors_on_omission_of_nested_non_null(self): params = {'input': {'a': 'foo', 'b': 'bar'}} with raises(GraphQLError) as excinfo: check(self.doc, {}, params) assert format_error(excinfo.value) == { 'locations': [{'column': 13, 'line': 2}], 'message': 'Variable "$input" got invalid value {}.\n' 'In field "c": Expected "String!", found null.'.format(stringify(params['input'])) }
def test_parse_error(): query = """ qeury """ result = graphql(StarWarsSchema, query) assert result.invalid formatted_error = format_error(result.errors[0]) assert formatted_error["locations"] == [{"column": 9, "line": 2}] assert ('Syntax Error GraphQL (2:9) Unexpected Name "qeury"' in formatted_error["message"]) assert result.data is None
def test_query(self): user_results = graphql_query_users(self.client) format_error(R.prop('errors', user_results)[0]) assert not R.prop('errors', user_results), R.dump_json(R.map(lambda e: format_error(e), R.prop('errors', user_results))) assert 2 == R.length(R.map(R.omit_deep(omit_props), R.item_path(['data', 'users'], user_results))) # Query using for foos based on the related User foo_results = graphql_query_foos( self.client, variables=dict( user=R.pick(['id'], self.lion.__dict__), # Test filters name_contains='oo', name_contains_not='jaberwaki' ) ) assert not R.prop('errors', foo_results), R.dump_json(R.map(lambda e: format_error(e), R.prop('errors', foo_results))) assert 1 == R.length(R.map(R.omit_deep(omit_props), R.item_path(['data', 'foos'], foo_results))) # Make sure the Django instance in the json blob was resolved assert self.cat.id == R.item_path(['data', 'foos', 0, 'data', 'friend', 'id'], foo_results)
def test_errors_on_incorrect_type(self): params = {'input': 'foo bar'} with raises(GraphQLError) as excinfo: check(self.doc, {}, params) assert format_error(excinfo.value) == { 'locations': [{'column': 13, 'line': 2}], 'message': 'Variable "$input" got invalid value {}.\n' 'Expected "TestInputObject", found not an object.'.format(stringify(params['input'])) }
def test_parse_error(): query = ''' qeury ''' result = graphql(StarWarsSchema, query) assert result.invalid formatted_error = format_error(result.errors[0]) assert formatted_error['locations'] == [{'column': 9, 'line': 2}] assert 'Syntax Error GraphQL (2:9) Unexpected Name "qeury"' in formatted_error[ 'message'] assert result.data is None
def test_parse_error(client): result = None with pytest.raises(Exception) as excinfo: query = gql(''' qeury ''') result = client.execute(query) error = excinfo.value formatted_error = format_error(error) assert formatted_error['locations'] == [{'column': 13, 'line': 2}] assert 'Syntax Error GraphQL request (2:13) Unexpected Name "qeury"' in formatted_error['message'] assert not result
def test_errors_on_addition_of_unknown_input_field(self): # type: () -> None params = {"input": {"a": "foo", "b": "bar", "c": "baz", "extra": "dog"}} with raises(GraphQLError) as excinfo: check(self.doc, {}, params) assert format_error(excinfo.value) == { "locations": [{"column": 13, "line": 2}], "message": 'Variable "$input" got invalid value {}.\n' 'In field "extra": Unknown field.'.format(stringify(params["input"])), }
def test_does_not_allow_non_nullable_inputs_to_be_omitted_in_a_variable(): doc = ''' query SetsNonNullable($value: String!) { fieldWithNonNullableStringInput(input: $value) } ''' with raises(GraphQLError) as excinfo: check(doc, {}) assert format_error(excinfo.value) == { 'locations': [{'column': 27, 'line': 2}], 'message': 'Variable "$value" of required type "String!" was not provided.' }
def check(doc, data, expected): ast = parse(doc) response = execute(schema, ast, data) if response.errors: result = { 'data': response.data, 'errors': [format_error(e) for e in response.errors] } else: result = {'data': response.data} assert result == expected
def test_does_not_allow_non_null_lists_of_non_nulls_to_be_null(): doc = ''' query q($input: [String!]!) { nnListNN(input: $input) } ''' with raises(GraphQLError) as excinfo: check(doc, {}, {'input': None}) assert format_error(excinfo.value) == { 'locations': [{'column': 13, 'line': 2}], 'message': 'Variable "$input" of required type "[String!]!" was not provided.' }
def default_error_formatter_includes_extension_fields(): # noinspection PyArgumentEqualDefault e = GraphQLError("msg", None, None, None, None, None, {"foo": "bar"}) formatted = format_error(e) assert formatted == e.formatted assert formatted == { "message": "msg", "locations": None, "path": None, "extensions": { "foo": "bar" }, }
def test_parse_error(client): result = None with pytest.raises(Exception) as exc_info: query = gql(""" qeury """) result = client.execute(query) error = exc_info.value formatted_error = format_error(error) assert formatted_error["locations"] == [{"column": 13, "line": 2}] assert ('Syntax Error GraphQL request (2:13) Unexpected Name "qeury"' in formatted_error["message"]) assert not result
def default_error_formatter_includes_extension_fields(): # noinspection PyArgumentEqualDefault e = GraphQLError('msg', None, None, None, None, None, {'foo': 'bar'}) formatted = format_error(e) assert formatted == e.formatted assert formatted == { 'message': 'msg', 'locations': None, 'path': None, 'extensions': { 'foo': 'bar' } }
def check(doc, expected, args=None): ast = parse(doc) response = execute(schema, ast, variable_values=args) if response.errors: result = { 'data': response.data, 'errors': [format_error(e) for e in response.errors] } else: result = {'data': response.data} assert result == expected
def test_fails_as_expected_on_the_type_root_field_without_an_arg(): TestType = GraphQLObjectType('TestType', { 'testField': GraphQLField(GraphQLString) }) schema = GraphQLSchema(TestType) request = ''' { __type { name } }''' result = graphql(schema, request) expected_error = {'message': ProvidedNonNullArguments.missing_field_arg_message('__type', 'name', 'String!'), 'locations': [dict(line=3, column=9)]} assert (expected_error in [format_error(error) for error in result.errors])
def check(doc, data, expected): ast = parse(doc) response = execute(schema, ast, data) if response.errors: result = { 'data': response.data, 'errors': [format_error(e) for e in response.errors] } else: result = { 'data': response.data } assert result == expected
def test_does_not_allow_unknown_types_to_be_used_as_values(): doc = ''' query q($input: UnknownType!) { fieldWithObjectInput(input: $input) } ''' params = {'input': 'whoknows'} with raises(GraphQLError) as excinfo: check(doc, {}, params) assert format_error(excinfo.value) == { 'locations': [{'column': 13, 'line': 2}], 'message': 'Variable "$input" expected value of type "UnknownType!" which cannot be used as an input type.' }
def check(doc, expected, args=None): ast = parse(doc) response = execute(schema, ast, variable_values=args) if response.errors: result = { 'data': response.data, 'errors': [format_error(e) for e in response.errors] } else: result = { 'data': response.data } assert result == expected
def test_does_not_allow_non_null_lists_of_non_nulls_to_contain_null(): doc = ''' query q($input: [String!]!) { nnListNN(input: $input) } ''' params = {'input': ['A', None, 'B']} with raises(GraphQLError) as excinfo: check(doc, {}, params) assert format_error(excinfo.value) == { 'locations': [{'column': 13, 'line': 2}], 'message': 'Variable "$input" got invalid value {}.\n' 'In element #1: Expected "String!", found null.'.format(stringify(params['input'])) }
def test_errors_on_deep_nested_errors_and_with_many_errors(self): nested_doc = ''' query q($input: TestNestedInputObject) { fieldWithNestedObjectInput(input: $input) } ''' params = {'input': {'na': {'a': 'foo'}}} with raises(GraphQLError) as excinfo: check(nested_doc, {}, params) assert format_error(excinfo.value) == { 'locations': [{'column': 19, 'line': 2}], 'message': 'Variable "$input" got invalid value {}.\n' 'In field "na": In field "c": Expected "String!", found null.\n' 'In field "nb": Expected "String!", found null.'.format(stringify(params['input'])) }
def test_cannot_use_client_schema_for_general_execution(): customScalar = GraphQLScalarType( name='CustomScalar', serialize=lambda: None ) schema = GraphQLSchema( query=GraphQLObjectType( name='Query', fields={ 'foo': GraphQLField( GraphQLString, args=OrderedDict([ ('custom1', GraphQLArgument(customScalar)), ('custom2', GraphQLArgument(customScalar)) ]) ) } ) ) introspection = graphql(schema, introspection_query) client_schema = build_client_schema(introspection.data) class data: foo = 'bar' result = graphql( client_schema, 'query NoNo($v: CustomScalar) { foo(custom1: 123, custom2: $v) }', data, {'v': 'baz'} ) assert result.data == {'foo': None} assert [format_error(e) for e in result.errors] == [ {'locations': [{'column': 32, 'line': 1}], 'message': 'Client Schema cannot be used for execution.'} ]