sgqlc 17__tar.gz → 18__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. {sgqlc-17 → sgqlc-18}/PKG-INFO +6 -2
  2. {sgqlc-17 → sgqlc-18}/doc/source/conf.py +2 -2
  3. {sgqlc-17 → sgqlc-18}/pyproject.toml +2 -1
  4. {sgqlc-17 → sgqlc-18}/sgqlc/__init__.py +1 -1
  5. {sgqlc-17 → sgqlc-18}/sgqlc/endpoint/base.py +30 -0
  6. {sgqlc-17 → sgqlc-18}/sgqlc/endpoint/http.py +5 -4
  7. {sgqlc-17 → sgqlc-18}/sgqlc/endpoint/httpx.py +20 -10
  8. {sgqlc-17 → sgqlc-18}/sgqlc/endpoint/requests.py +10 -4
  9. {sgqlc-17 → sgqlc-18}/sgqlc/endpoint/websocket.py +4 -3
  10. {sgqlc-17 → sgqlc-18}/tests/test-endpoint-http.py +64 -2
  11. {sgqlc-17 → sgqlc-18}/tests/test-endpoint-httpx.py +85 -2
  12. {sgqlc-17 → sgqlc-18}/tests/test-endpoint-requests.py +64 -2
  13. {sgqlc-17 → sgqlc-18}/tests/test-endpoint-websocket.py +57 -1
  14. {sgqlc-17 → sgqlc-18}/AUTHORS +0 -0
  15. {sgqlc-17 → sgqlc-18}/LICENSE +0 -0
  16. {sgqlc-17 → sgqlc-18}/README.rst +0 -0
  17. {sgqlc-17 → sgqlc-18}/doc/source/_static/.keepme +0 -0
  18. {sgqlc-17 → sgqlc-18}/doc/source/_static/logo-sgqlc.png +0 -0
  19. {sgqlc-17 → sgqlc-18}/doc/source/favicon-sgqlc.png +0 -0
  20. {sgqlc-17 → sgqlc-18}/doc/source/index.rst +0 -0
  21. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.codegen.rst +0 -0
  22. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.endpoint.base.rst +0 -0
  23. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.endpoint.http.rst +0 -0
  24. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.endpoint.requests.rst +0 -0
  25. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.endpoint.rst +0 -0
  26. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.endpoint.websocket.rst +0 -0
  27. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.introspection.rst +0 -0
  28. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.operation.rst +0 -0
  29. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.rst +0 -0
  30. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.types.datetime.rst +0 -0
  31. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.types.relay.rst +0 -0
  32. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.types.rst +0 -0
  33. {sgqlc-17 → sgqlc-18}/doc/source/sgqlc.types.uuid.rst +0 -0
  34. {sgqlc-17 → sgqlc-18}/sgqlc/codegen/__init__.py +0 -0
  35. {sgqlc-17 → sgqlc-18}/sgqlc/codegen/__main__.py +0 -0
  36. {sgqlc-17 → sgqlc-18}/sgqlc/codegen/operation.py +0 -0
  37. {sgqlc-17 → sgqlc-18}/sgqlc/codegen/schema.py +0 -0
  38. {sgqlc-17 → sgqlc-18}/sgqlc/endpoint/__init__.py +0 -0
  39. {sgqlc-17 → sgqlc-18}/sgqlc/introspection/__init__.py +0 -0
  40. {sgqlc-17 → sgqlc-18}/sgqlc/introspection/__main__.py +0 -0
  41. {sgqlc-17 → sgqlc-18}/sgqlc/operation/__init__.py +0 -0
  42. {sgqlc-17 → sgqlc-18}/sgqlc/types/__init__.py +0 -0
  43. {sgqlc-17 → sgqlc-18}/sgqlc/types/datetime.py +0 -0
  44. {sgqlc-17 → sgqlc-18}/sgqlc/types/relay.py +0 -0
  45. {sgqlc-17 → sgqlc-18}/sgqlc/types/uuid.py +0 -0
  46. {sgqlc-17 → sgqlc-18}/tests/test-introspection.py +0 -0
  47. {sgqlc-17 → sgqlc-18}/tests/test-operation-codegen.py +0 -0
@@ -1,8 +1,10 @@
1
- Metadata-Version: 2.3
1
+ Metadata-Version: 2.4
2
2
  Name: sgqlc
3
- Version: 17
3
+ Version: 18
4
4
  Summary: Simple GraphQL Client
5
5
  License: ISCL
6
+ License-File: AUTHORS
7
+ License-File: LICENSE
6
8
  Keywords: graphql,client,http,endpoint
7
9
  Author: Gustavo Sverzut Barbieri
8
10
  Author-email: barbieri@profusion.mobi
@@ -16,10 +18,12 @@ Classifier: Operating System :: OS Independent
16
18
  Classifier: Programming Language :: Python
17
19
  Classifier: Topic :: Utilities
18
20
  Provides-Extra: httpx
21
+ Provides-Extra: pytest
19
22
  Provides-Extra: requests
20
23
  Provides-Extra: websocket
21
24
  Requires-Dist: graphql-core (>=3.2.6,<3.3.0)
22
25
  Requires-Dist: httpx ; extra == "httpx"
26
+ Requires-Dist: pytest ; extra == "pytest"
23
27
  Requires-Dist: requests ; extra == "requests"
24
28
  Requires-Dist: websocket-client ; extra == "websocket"
25
29
  Project-URL: Documentation, https://sgqlc.readthedocs.io/
@@ -61,9 +61,9 @@ author = 'ProFUSION Sistemas e Solucoes LTDA'
61
61
  # built documents.
62
62
  #
63
63
  # The short X.Y version.
64
- version = '17'
64
+ version = '18'
65
65
  # The full version, including alpha/beta/rc tags.
66
- release = '17'
66
+ release = '18'
67
67
 
68
68
  # The language for content autogenerated by Sphinx. Refer to documentation
69
69
  # for a list of supported languages.
@@ -29,7 +29,7 @@ norecursedirs = [
29
29
 
30
30
  [project]
31
31
  name = 'sgqlc'
32
- version = '17'
32
+ version = '18'
33
33
  description = 'Simple GraphQL Client'
34
34
  readme = 'README.rst'
35
35
  authors = [
@@ -72,6 +72,7 @@ sgqlc-codegen = 'sgqlc.codegen:main'
72
72
  websocket = ['websocket-client']
73
73
  requests = ['requests']
74
74
  httpx = ['httpx']
75
+ pytest = ['pytest']
75
76
 
76
77
  [tool.poetry.group.dev.dependencies]
77
78
  pytest = '*'
@@ -25,4 +25,4 @@ modules:
25
25
  '''
26
26
 
27
27
  __docformat__ = 'reStructuredText en'
28
- __version__ = '17'
28
+ __version__ = '18'
@@ -29,10 +29,40 @@ __docformat__ = 'reStructuredText en'
29
29
 
30
30
  __all__ = ('BaseEndpoint',)
31
31
 
32
+ import json
32
33
  import logging
33
34
  import urllib.parse
34
35
 
35
36
 
37
+ class JSONEncoder(json.JSONEncoder):
38
+ '''JSON encoder that handles sgqlc.types.Input instances.
39
+
40
+ This encoder automatically converts :class:`sgqlc.types.Input`
41
+ instances to their JSON-serializable dictionary representation by
42
+ accessing the ``__json_data__`` attribute.
43
+
44
+ Other non-serializable types will raise :exc:`TypeError` as usual.
45
+
46
+ Example usage:
47
+
48
+ >>> from sgqlc.types import Input
49
+ >>> class MyInput(Input):
50
+ ... a_field = str
51
+ ...
52
+ >>> value = MyInput(a_field='test')
53
+ >>> json.dumps({'input': value}, cls=JSONEncoder)
54
+ '{"input": {"aField": "test"}}'
55
+ '''
56
+
57
+ def default(self, o):
58
+ # Check if it's an Input type by looking for __json_data__
59
+ # attribute. This avoids importing sgqlc.types which would
60
+ # create a circular dependency
61
+ if hasattr(o, '__json_data__'):
62
+ return o.__json_data__
63
+ return super().default(o)
64
+
65
+
36
66
  def add_query_to_url(url, extra_query):
37
67
  '''Adds an extra query to URL, returning the new URL.
38
68
 
@@ -35,7 +35,7 @@ import urllib.error
35
35
  import urllib.parse
36
36
  import urllib.request
37
37
 
38
- from .base import BaseEndpoint, add_query_to_url
38
+ from .base import BaseEndpoint, JSONEncoder, add_query_to_url
39
39
 
40
40
 
41
41
  class HTTPEndpoint(BaseEndpoint):
@@ -210,12 +210,13 @@ class HTTPEndpoint(BaseEndpoint):
210
210
  'query': query,
211
211
  'variables': variables,
212
212
  'operationName': operation_name,
213
- }
213
+ },
214
+ cls=JSONEncoder,
214
215
  ).encode('utf-8')
215
216
  headers.update(
216
217
  {
217
218
  'Content-Type': 'application/json; charset=utf-8',
218
- 'Content-Length': len(post_data),
219
+ 'Content-Length': str(len(post_data)),
219
220
  }
220
221
  )
221
222
  return urllib.request.Request(
@@ -228,7 +229,7 @@ class HTTPEndpoint(BaseEndpoint):
228
229
  params['operationName'] = operation_name
229
230
 
230
231
  if variables:
231
- params['variables'] = json.dumps(variables)
232
+ params['variables'] = json.dumps(variables, cls=JSONEncoder)
232
233
 
233
234
  url = add_query_to_url(self.url, params)
234
235
  return urllib.request.Request(url=url, headers=headers, method='GET')
@@ -37,7 +37,7 @@ __all__ = ('HTTPXEndpoint',)
37
37
  import json
38
38
  import httpx
39
39
 
40
- from .base import add_query_to_url
40
+ from .base import JSONEncoder, add_query_to_url
41
41
  from .http import HTTPEndpoint
42
42
  from typing import Optional, Union, Dict
43
43
 
@@ -61,7 +61,7 @@ class HTTPXEndpoint(HTTPEndpoint):
61
61
  :errors: list of errors, which are objects with the key "message" and
62
62
  optionally others, such as "location" (for errors matching GraphQL
63
63
  input). Instead of raising exceptions, such as
64
- :exc:`requests.exceptions.HTTPError` or
64
+ :exc:`requests.exceptions.HTTPStatusError` or
65
65
  :exc:`json.JSONDecodeError` those are stored in the
66
66
  "exception" key.
67
67
 
@@ -152,7 +152,7 @@ class HTTPXEndpoint(HTTPEndpoint):
152
152
  try:
153
153
  response = await self.client.send(req)
154
154
  return self._parse_httpx_response(query, response)
155
- except httpx.HTTPError as exc:
155
+ except httpx.HTTPStatusError as exc:
156
156
  return self._log_httpx_error(query, req, exc)
157
157
 
158
158
  return runner()
@@ -160,7 +160,7 @@ class HTTPXEndpoint(HTTPEndpoint):
160
160
  try:
161
161
  response = self.client.send(req)
162
162
  return self._parse_httpx_response(query, response)
163
- except httpx.HTTPError as exc:
163
+ except httpx.HTTPStatusError as exc:
164
164
  return self._log_httpx_error(query, req, exc)
165
165
 
166
166
  def _parse_httpx_response(self, query, response):
@@ -226,15 +226,25 @@ class HTTPXEndpoint(HTTPEndpoint):
226
226
 
227
227
  def get_http_post_request(self, query, variables, operation_name, headers):
228
228
  '''Create an HTTP POST request for the query.'''
229
- return self.client.build_request(
230
- method='POST',
231
- url=self.url,
232
- headers=headers,
233
- json={
229
+ post_data = json.dumps(
230
+ {
234
231
  'query': query,
235
232
  'variables': variables,
236
233
  'operationName': operation_name,
237
234
  },
235
+ cls=JSONEncoder,
236
+ ).encode('utf-8')
237
+ headers.update(
238
+ {
239
+ 'Content-Type': 'application/json; charset=utf-8',
240
+ 'Content-Length': str(len(post_data)),
241
+ }
242
+ )
243
+ return self.client.build_request(
244
+ method='POST',
245
+ url=self.url,
246
+ headers=headers,
247
+ content=post_data,
238
248
  )
239
249
 
240
250
  def get_http_get_request(self, query, variables, operation_name, headers):
@@ -244,7 +254,7 @@ class HTTPXEndpoint(HTTPEndpoint):
244
254
  params['operationName'] = operation_name
245
255
 
246
256
  if variables:
247
- params['variables'] = json.dumps(variables)
257
+ params['variables'] = json.dumps(variables, cls=JSONEncoder)
248
258
 
249
259
  url = add_query_to_url(self.url, params)
250
260
 
@@ -40,7 +40,7 @@ import logging
40
40
  import requests
41
41
 
42
42
 
43
- from .base import BaseEndpoint, add_query_to_url
43
+ from .base import BaseEndpoint, JSONEncoder, add_query_to_url
44
44
 
45
45
 
46
46
  class RequestsEndpoint(BaseEndpoint):
@@ -239,9 +239,15 @@ class RequestsEndpoint(BaseEndpoint):
239
239
  'query': query,
240
240
  'variables': variables,
241
241
  'operationName': operation_name,
242
- }
242
+ },
243
+ cls=JSONEncoder,
243
244
  ).encode('utf-8')
244
- headers.update({'Content-Type': 'application/json; charset=utf-8'})
245
+ headers.update(
246
+ {
247
+ 'Content-Type': 'application/json; charset=utf-8',
248
+ 'Content-Length': str(len(post_data)),
249
+ }
250
+ )
245
251
  return requests.Request(
246
252
  url=self.url,
247
253
  auth=self.auth,
@@ -256,7 +262,7 @@ class RequestsEndpoint(BaseEndpoint):
256
262
  params['operationName'] = operation_name
257
263
 
258
264
  if variables:
259
- params['variables'] = json.dumps(variables)
265
+ params['variables'] = json.dumps(variables, cls=JSONEncoder)
260
266
 
261
267
  url = add_query_to_url(self.url, params)
262
268
  return requests.Request(
@@ -1,4 +1,4 @@
1
- from sgqlc.endpoint.base import BaseEndpoint
1
+ from sgqlc.endpoint.base import BaseEndpoint, JSONEncoder
2
2
  import websocket
3
3
  import uuid
4
4
  import json
@@ -85,7 +85,7 @@ class WebSocketEndpoint(BaseEndpoint):
85
85
  connection_setup_dict = {'type': 'connection_init', 'id': init_id}
86
86
  if self.connection_payload:
87
87
  connection_setup_dict['payload'] = self.connection_payload
88
- ws.send(json.dumps(connection_setup_dict))
88
+ ws.send(json.dumps(connection_setup_dict, cls=JSONEncoder))
89
89
 
90
90
  response = self._get_response(ws)
91
91
  if response['type'] != 'connection_ack':
@@ -111,7 +111,8 @@ class WebSocketEndpoint(BaseEndpoint):
111
111
  'variables': variables,
112
112
  'operationName': operation_name,
113
113
  },
114
- }
114
+ },
115
+ cls=JSONEncoder,
115
116
  )
116
117
  )
117
118
  response = self._get_response(ws)
@@ -1,12 +1,13 @@
1
1
  import gzip
2
2
  import io
3
3
  import json
4
+ import pytest
4
5
  import urllib.error
5
6
  import urllib.request
6
7
 
7
8
  from unittest.mock import MagicMock, patch
8
9
  from sgqlc.endpoint.http import HTTPEndpoint, add_query_to_url
9
- from sgqlc.types import Schema, Type
10
+ from sgqlc.types import Schema, Type, Input
10
11
  from sgqlc.operation import Operation
11
12
 
12
13
  test_url = 'http://some-server.com/graphql'
@@ -160,7 +161,18 @@ def check_request_variables(req, variables):
160
161
  query = get_request_url_query(req)
161
162
  received = json.loads(query.get('variables', 'null'))
162
163
 
163
- assert received == variables
164
+ if not variables:
165
+ assert received == variables
166
+ return
167
+
168
+ # Convert Input types to their JSON representation for comparison
169
+ expected = {}
170
+ for k, v in variables.items():
171
+ if hasattr(v, '__json_data__'):
172
+ expected[k] = v.__json_data__
173
+ else:
174
+ expected[k] = v
175
+ assert received == expected
164
176
 
165
177
 
166
178
  def check_request_operation_name(req, operation_name):
@@ -674,6 +686,56 @@ def test_server_http_error_list_message(mock_urlopen):
674
686
  check_mock_urlopen(mock_urlopen)
675
687
 
676
688
 
689
+ @patch('urllib.request.urlopen')
690
+ def test_variables_with_input_type(mock_urlopen):
691
+ 'Test if variables with sgqlc.types.Input are properly serialized'
692
+
693
+ schema = Schema()
694
+
695
+ # MyInput may be declared if doctests were processed by pytest
696
+ if 'MyInput' in schema:
697
+ schema -= schema.MyInput
698
+
699
+ class MyInput(Input):
700
+ __schema__ = schema
701
+ a_str = str
702
+ a_int = int
703
+
704
+ configure_mock_urlopen(
705
+ mock_urlopen,
706
+ graphql_response_ok,
707
+ graphql_headers_ok,
708
+ )
709
+
710
+ variables = {'input': MyInput(a_str='hello', a_int=42)}
711
+
712
+ endpoint = HTTPEndpoint(test_url)
713
+ data = endpoint(graphql_query, variables)
714
+ assert data['data']['repository']['issues']['nodes'][0]['number'] == 1
715
+ check_mock_urlopen(mock_urlopen, variables=variables)
716
+
717
+
718
+ @patch('urllib.request.urlopen')
719
+ def test_variables_with_bogus_type(mock_urlopen):
720
+ 'Test if variables with non-serializable types raise TypeError'
721
+
722
+ class BogusType:
723
+ pass
724
+
725
+ configure_mock_urlopen(
726
+ mock_urlopen,
727
+ graphql_response_ok,
728
+ graphql_headers_ok,
729
+ )
730
+
731
+ variables = {'input': BogusType()}
732
+
733
+ endpoint = HTTPEndpoint(test_url)
734
+ with pytest.raises(TypeError):
735
+ endpoint(graphql_query, variables)
736
+ assert not mock_urlopen.called
737
+
738
+
677
739
  # add_query_to_url():
678
740
  # test paths not already tested, here just the repeated query
679
741
 
@@ -1,6 +1,7 @@
1
1
  import json
2
2
 
3
3
  import httpx
4
+ import pytest
4
5
 
5
6
  from sgqlc.endpoint.httpx import HTTPXEndpoint
6
7
  from sgqlc.types import Schema, Type
@@ -103,7 +104,7 @@ def check_request_headers(req, base_headers, extra_headers):
103
104
  accept_header = 'application/json; charset=utf-8'
104
105
  assert req.headers['Accept'] == accept_header
105
106
  if req.method == 'POST':
106
- assert req.headers['Content-type'] == 'application/json'
107
+ assert req.headers['Content-type'] == 'application/json; charset=utf-8'
107
108
  check_request_headers_(req, base_headers, 'base')
108
109
  check_request_headers_(req, extra_headers, 'extra')
109
110
 
@@ -115,7 +116,18 @@ def check_request_variables(req, variables):
115
116
  else:
116
117
  received = json.loads(req.url.params.get('variables', 'null'))
117
118
 
118
- assert received == variables
119
+ if not variables:
120
+ assert received == variables
121
+ return
122
+
123
+ # Convert Input types to their JSON representation for comparison
124
+ expected = {}
125
+ for k, v in variables.items():
126
+ if hasattr(v, '__json_data__'):
127
+ expected[k] = v.__json_data__
128
+ else:
129
+ expected[k] = v
130
+ assert received == expected
119
131
 
120
132
 
121
133
  def check_request_operation_name(req, operation_name):
@@ -551,6 +563,28 @@ def test_server_http_non_conforming_json(respx_mock):
551
563
  check_respx_route(route)
552
564
 
553
565
 
566
+ async def test_server_http_transport_error(respx_mock):
567
+ 'Test if a transport error will get passed back to the caller'
568
+
569
+ route = respx_mock.route(name='graphql', method='POST', url=test_url).mock(
570
+ side_effect=httpx.RemoteProtocolError
571
+ )
572
+
573
+ endpoint = HTTPXEndpoint(test_url)
574
+
575
+ with pytest.raises(httpx.RemoteProtocolError):
576
+ endpoint(graphql_query)
577
+
578
+ check_respx_route(route)
579
+
580
+ endpoint = HTTPXEndpoint(test_url, client=httpx.AsyncClient())
581
+
582
+ with pytest.raises(httpx.RemoteProtocolError):
583
+ await endpoint(graphql_query)
584
+
585
+ check_respx_route(route)
586
+
587
+
554
588
  def test_server_error_broken_json(respx_mock):
555
589
  'Test if HTTP error with broken JSON payload is handled'
556
590
 
@@ -699,3 +733,52 @@ def test_server_http_error_list_message(respx_mock):
699
733
 
700
734
  assert data == expected_data
701
735
  check_respx_route(route)
736
+
737
+
738
+ def test_variables_with_input_type(respx_mock):
739
+ 'Test if variables with sgqlc.types.Input are properly serialized'
740
+ from sgqlc.types import Input
741
+
742
+ schema = Schema()
743
+
744
+ # MyInput may be declared if doctests were processed by pytest
745
+ if 'MyInput' in schema:
746
+ schema -= schema.MyInput
747
+
748
+ class MyInput(Input):
749
+ __schema__ = schema
750
+ a_str = str
751
+ a_int = int
752
+
753
+ route = respx_mock.route(name='graphql', method='POST', url=test_url).mock(
754
+ return_value=httpx.Response(
755
+ 200, json=graphql_response_ok, headers=graphql_headers_ok
756
+ )
757
+ )
758
+
759
+ variables = {'input': MyInput(a_str='hello', a_int=42)}
760
+
761
+ endpoint = HTTPXEndpoint(test_url)
762
+ data = endpoint(graphql_query, variables)
763
+ assert data == graphql_response_ok
764
+ check_respx_route(route, variables=variables)
765
+
766
+
767
+ def test_variables_with_bogus_type(respx_mock):
768
+ 'Test if variables with non-serializable types raise TypeError'
769
+
770
+ class BogusType:
771
+ pass
772
+
773
+ route = respx_mock.route(name='graphql', method='POST', url=test_url).mock(
774
+ return_value=httpx.Response(
775
+ 200, json=graphql_response_ok, headers=graphql_headers_ok
776
+ )
777
+ )
778
+
779
+ variables = {'input': BogusType()}
780
+
781
+ endpoint = HTTPXEndpoint(test_url)
782
+ with pytest.raises(TypeError):
783
+ endpoint(graphql_query, variables)
784
+ assert not route.called
@@ -1,11 +1,12 @@
1
1
  import io
2
2
  import json
3
+ import pytest
3
4
  import requests
4
5
  import urllib
5
6
 
6
7
  from unittest.mock import patch
7
8
  from sgqlc.endpoint.requests import RequestsEndpoint, add_query_to_url
8
- from sgqlc.types import Schema, Type
9
+ from sgqlc.types import Schema, Type, Input
9
10
  from sgqlc.operation import Operation
10
11
 
11
12
 
@@ -168,7 +169,18 @@ def check_request_variables(req, variables):
168
169
  query = get_request_url_query(req)
169
170
  received = json.loads(query.get('variables', 'null'))
170
171
 
171
- assert received == variables
172
+ if not variables:
173
+ assert received == variables
174
+ return
175
+
176
+ # Convert Input types to their JSON representation for comparison
177
+ expected = {}
178
+ for k, v in variables.items():
179
+ if hasattr(v, '__json_data__'):
180
+ expected[k] = v.__json_data__
181
+ else:
182
+ expected[k] = v
183
+ assert received == expected
172
184
 
173
185
 
174
186
  def check_request_operation_name(req, operation_name):
@@ -690,6 +702,56 @@ def test_server_http_error_list_message(mock_requests_send):
690
702
  check_mock_requests_send(mock_requests_send)
691
703
 
692
704
 
705
+ @patch('requests.sessions.Session.send')
706
+ def test_variables_with_input_type(mock_requests_send):
707
+ '[Requests] - Test if variables with sgqlc.types.Input are serialized'
708
+ schema = Schema()
709
+
710
+ # MyInput may be declared if doctests were processed by pytest
711
+ if 'MyInput' in schema:
712
+ schema -= schema.MyInput
713
+
714
+ class MyInput(Input):
715
+ __schema__ = schema
716
+ a_str = str
717
+ a_int = int
718
+
719
+ configure_mock_requests_send(
720
+ mock_requests_send,
721
+ graphql_response_ok,
722
+ )
723
+
724
+ variables = {'input': MyInput(a_str='hello', a_int=42)}
725
+
726
+ endpoint = RequestsEndpoint(test_url)
727
+ data = endpoint(graphql_query, variables)
728
+ assert data['data']['repository']['issues']['nodes'][0]['number'] == 1
729
+ check_mock_requests_send(mock_requests_send, variables=variables)
730
+
731
+
732
+ @patch('requests.sessions.Session.send')
733
+ def test_variables_with_bogus_type(mock_requests_send):
734
+ '''
735
+ [Requests] - Test if variables with non-serializable types
736
+ raise TypeError
737
+ '''
738
+
739
+ class BogusType:
740
+ pass
741
+
742
+ configure_mock_requests_send(
743
+ mock_requests_send,
744
+ graphql_response_ok,
745
+ )
746
+
747
+ variables = {'input': BogusType()}
748
+
749
+ endpoint = RequestsEndpoint(test_url)
750
+ with pytest.raises(TypeError):
751
+ endpoint(graphql_query, variables)
752
+ assert mock_requests_send.called is False
753
+
754
+
693
755
  # add_query_to_url():
694
756
  # test paths not already tested, here just the repeated query
695
757
 
@@ -5,7 +5,7 @@ from unittest.mock import patch, Mock
5
5
  from sgqlc.endpoint.websocket import WebSocketEndpoint
6
6
 
7
7
  from sgqlc.operation import Operation
8
- from sgqlc.types import Schema, Type
8
+ from sgqlc.types import Schema, Type, Input
9
9
 
10
10
  test_url = 'ws://localhost:12345/graphql'
11
11
  endpoint = WebSocketEndpoint(test_url)
@@ -359,3 +359,59 @@ def test_query_bad_message_id(mock_create_connection):
359
359
  raise Exception('should have failed')
360
360
  except ValueError as e:
361
361
  assert e.args[0] == 'Unexpected id 321 when waiting for query results'
362
+
363
+
364
+ @patch('websocket.create_connection')
365
+ def test_variables_with_input_type(mock_create_connection):
366
+ 'Test if variables with sgqlc.types.Input are properly serialized'
367
+ schema = Schema()
368
+
369
+ # MyInput may be declared if doctests were processed by pytest
370
+ if 'MyInput' in schema:
371
+ schema -= schema.MyInput
372
+
373
+ class MyInput(Input):
374
+ __schema__ = schema
375
+ a_str = str
376
+ a_int = int
377
+
378
+ mock_connection = Mock()
379
+ mock_create_connection.return_value = mock_connection
380
+ mock_connection.recv.side_effect = [
381
+ '{"type": "connection_ack", "id": "123"}',
382
+ '{"type": "data", "id": "123", "payload": {"data": {"test": "ok"}}}',
383
+ '{"type": "complete", "id": "123"}',
384
+ ]
385
+
386
+ variables = {'input': MyInput(a_str='hello', a_int=42)}
387
+ result = list(endpoint('query {test}', variables))
388
+ assert result == [{'data': {'test': 'ok'}}]
389
+
390
+ # Verify the variables were serialized with Input.__json_data__
391
+ calls = mock_connection.send.call_args_list
392
+ query_call = calls[1][0][0] # Second call (first is connection_init)
393
+ query_data = json.loads(query_call)
394
+ assert query_data['payload']['variables'] == {
395
+ 'input': {'aStr': 'hello', 'aInt': 42}
396
+ }
397
+
398
+
399
+ @patch('websocket.create_connection')
400
+ def test_variables_with_bogus_type(mock_create_connection):
401
+ 'Test if variables with non-serializable types raise TypeError'
402
+
403
+ class BogusType:
404
+ pass
405
+
406
+ mock_connection = Mock()
407
+ mock_create_connection.return_value = mock_connection
408
+ mock_connection.recv.side_effect = [
409
+ '{"type": "connection_ack", "id": "123"}',
410
+ ]
411
+
412
+ variables = {'input': BogusType()}
413
+
414
+ import pytest
415
+
416
+ with pytest.raises(TypeError):
417
+ list(endpoint('query {test}', variables))
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes