From 2417cadcea5afa6a3d1974c0e898d1b3ec8adec6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Pito=C5=84?= Date: Thu, 8 Feb 2024 16:29:17 +0100 Subject: [PATCH] Handle unset variables in schema proxy --- CHANGELOG.md | 1 + ariadne_graphql_proxy/proxy_schema.py | 10 ++++--- tests/test_proxy_schema.py | 38 +++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 81f6413..3492531 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## UNRELEASED - Added `CacheSerializer`, `NoopCacheSerializer` and `JSONCacheSerializer`. Changed `CacheBackend`, `InMemoryCache`, `CloudflareCacheBackend` and `DynamoDBCacheBackend` to accept `serializer` initialization option. +- Fixed schema proxy returning an error when variable defined in an operation is missing from its variables. ## 0.2.0 (2023-09-25) diff --git a/ariadne_graphql_proxy/proxy_schema.py b/ariadne_graphql_proxy/proxy_schema.py index 3560253..7856162 100644 --- a/ariadne_graphql_proxy/proxy_schema.py +++ b/ariadne_graphql_proxy/proxy_schema.py @@ -235,9 +235,13 @@ async def root_resolver( "operationName": operation_name, "query": print_ast(query_document), "variables": ( - variables - if not variables - else {key: variables[key] for key in query_variables} + { + key: variables[key] + for key in query_variables + if key in variables + } + if variables + else None ), }, ) diff --git a/tests/test_proxy_schema.py b/tests/test_proxy_schema.py index 69226fe..b3fa647 100644 --- a/tests/test_proxy_schema.py +++ b/tests/test_proxy_schema.py @@ -771,6 +771,44 @@ async def test_proxy_schema_splits_variables_from_fragments_between_schemas( } +@pytest.mark.asyncio +async def test_proxy_schema_handles_omitted_optional_variables( + httpx_mock, + schema_json, +): + httpx_mock.add_response(url="http://graphql.example.com/", json=schema_json) + + proxy_schema = ProxySchema() + proxy_schema.add_remote_schema("http://graphql.example.com/") + proxy_schema.get_final_schema() + + await proxy_schema.root_resolver( + {}, + "TestQuery", + {"arg": "test"}, + parse( + """ + query TestQuery($arg: Generic, $other: Generic) { + basic(arg: $arg, other: $other) + } + """ + ), + ) + + request = httpx_mock.get_requests(url="http://graphql.example.com/")[-1] + assert json.loads(request.content) == { + "operationName": "TestQuery", + "variables": {"arg": "test"}, + "query": dedent( + """ + query TestQuery($arg: Generic, $other: Generic) { + basic(arg: $arg, other: $other) + } + """ + ).strip(), + } + + def test_insert_field_adds_field_into_local_schemas_with_given_type( schema, complex_schema ):