def test_server_http_error_string_list(mock_requests_send): '[Requests] - Test if HTTP error that a JSON error string list is handled' res = requests.Response() res.status_code = 500 res.url = test_url res.reason = 'Some Error' res.headers = {'Content-Type': 'application/json'} res.raw = io.BytesIO(b'{"errors": ["a", "b"]}') err = requests.exceptions.HTTPError(response=res) configure_mock_requests_send(mock_requests_send, err) endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query) expected_data = {'errors': [{'message': 'a'}, {'message': 'b'}]} expected_data.update({ 'exception': err, 'status': 500, 'headers': { 'Content-Type': 'application/json' }, }) eq_(data, expected_data) check_mock_requests_send(mock_requests_send)
def test_server_http_error(mock_requests_send): '[Requests] - Test if HTTP error without JSON payload is handled' res = requests.Response() res.status_code = 500 res.url = test_url res.reason = 'Some Error' res.headers = {'Xpto': 'abc'} res.raw = io.BytesIO(b'xpto') err = requests.exceptions.HTTPError(response=res) configure_mock_requests_send(mock_requests_send, err) endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query) eq_( data, { 'errors': [{ 'message': str(err), 'exception': err, 'status': 500, 'headers': { 'Xpto': 'abc' }, 'body': 'xpto', }], 'data': None, }) check_mock_requests_send(mock_requests_send)
def test_basic_operation_query(mock_requests_send): '[Requests] - Test if query with type sgqlc.operation.Operation() works' configure_mock_requests_send(mock_requests_send, graphql_response_ok) schema = Schema() # MyType and Query may be declared if doctests were processed by nose if 'MyType' in schema: schema -= schema.MyType if 'Query' in schema: schema -= schema.Query class MyType(Type): __schema__ = schema i = int class Query(Type): __schema__ = schema my_type = MyType op = Operation(Query) op.my_type.i() endpoint = RequestsEndpoint(test_url) data = endpoint(op) eq_(data, json.loads(graphql_response_ok)) check_mock_requests_send(mock_requests_send, query=bytes(op))
def test_server_http_non_conforming_json(mock_requests_send): '[Requests] - Test HTTP error that is NOT conforming to GraphQL payload' res = requests.Response() res.status_code = 500 res.url = test_url res.reason = 'Some Error' res.headers = {'Content-Type': 'application/json'} res.raw = io.BytesIO(b'{"message": "xpto"}') err = requests.exceptions.HTTPError(response=res) configure_mock_requests_send(mock_requests_send, err) endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query) eq_( data, { 'errors': [{ 'message': str(err), 'exception': err, 'status': 500, 'headers': { 'Content-Type': 'application/json' }, 'body': '{"message": "xpto"}', }], 'data': None, }) check_mock_requests_send(mock_requests_send)
def test_server_error_broken_json(mock_requests_send): '[Requests] - Test if HTTP error with broken JSON payload is handled' res = requests.Response() res.status_code = 500 res.url = test_url res.reason = 'Some Error' res.headers = {'Content-Type': 'application/json'} res.raw = io.BytesIO(b'xpto') err = requests.exceptions.HTTPError(response=res) configure_mock_requests_send(mock_requests_send, err) endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query) got_exc = data['errors'][0].pop('exception') assert isinstance(got_exc, json.JSONDecodeError), \ '{} is not json.JSONDecodeError'.format(type(got_exc)) eq_(data, { 'errors': [{ 'message': str(got_exc), 'body': 'xpto', }], 'data': None, }) check_mock_requests_send(mock_requests_send)
def test_server_http_error_list_message(mock_requests_send): '[Requests] - Test HTTP JSON error with messages being a list' res = requests.Response() res.status_code = 500 res.url = test_url res.reason = 'Some Error' res.headers = {'Content-Type': 'application/json'} res.raw = io.BytesIO(b'{"errors": [{"message": [1, 2]}]}') err = requests.exceptions.HTTPError(response=res) configure_mock_requests_send(mock_requests_send, err) endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query) expected_data = {'errors': [{'message': '[1, 2]'}]} expected_data.update({ 'exception': err, 'status': 500, 'headers': { 'Content-Type': 'application/json' }, }) eq_(data, expected_data) check_mock_requests_send(mock_requests_send)
def test_server_http_graphql_error(mock_requests_send): '[Requests] - Test HTTP error that IS conforming to GraphQL payload' res = requests.Response() res.status_code = 500 res.url = test_url res.reason = 'Some Error' res.headers = {'Content-Type': 'application/json'} res.raw = io.BytesIO(graphql_response_error.encode()) err = requests.exceptions.HTTPError(response=res) configure_mock_requests_send(mock_requests_send, err) endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query) expected_data = json.loads(graphql_response_error) expected_data.update({ 'exception': err, 'status': 500, 'headers': { 'Content-Type': 'application/json' }, }) eq_(data, expected_data) check_mock_requests_send(mock_requests_send)
def test_server_reported_error(mock_requests_send): '[Requests] - Test if GraphQL errors reported with HTTP 200 is handled' configure_mock_requests_send(mock_requests_send, graphql_response_error) endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query) eq_(data, json.loads(graphql_response_error)) check_mock_requests_send(mock_requests_send)
def test_basic_bytes_query(mock_requests_send): '[Requests] - Test if query with type bytes works' configure_mock_requests_send(mock_requests_send, graphql_response_ok) endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query.encode('utf-8')) eq_(data, json.loads(graphql_response_ok)) check_mock_requests_send(mock_requests_send)
def test_operation_name(mock_requests_send): '[Requests] - Test if operation name is passed to server' configure_mock_requests_send(mock_requests_send, graphql_response_ok) operation_name = 'xpto' endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query, operation_name=operation_name) eq_(data, json.loads(graphql_response_ok)) check_mock_requests_send(mock_requests_send, operation_name=operation_name)
def test_variables(mock_requests_send): '[Requests] - Test if variables are passed to server' configure_mock_requests_send(mock_requests_send, graphql_response_ok) variables = {'repoOwner': 'owner', 'repoName': 'name'} endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query, variables) eq_(data, json.loads(graphql_response_ok)) check_mock_requests_send(mock_requests_send, variables=variables)
def test_default_timeout(mock_requests_send): '[Requests] - Test if default timeout is respected' configure_mock_requests_send(mock_requests_send, graphql_response_ok) timeout = 123 endpoint = RequestsEndpoint(test_url, timeout=timeout) data = endpoint(graphql_query) eq_(data, json.loads(graphql_response_ok)) check_mock_requests_send(mock_requests_send, timeout=timeout)
def test_call_timeout(mock_requests_send): '[Requests] - Test if call timeout takes precedence over default' configure_mock_requests_send(mock_requests_send, graphql_response_ok) timeout = 123 endpoint = RequestsEndpoint(test_url, timeout=1) data = endpoint(graphql_query, timeout=timeout) eq_(data, json.loads(graphql_response_ok)) check_mock_requests_send(mock_requests_send, timeout=timeout)
def __init__(self, auth: Auth, org_id: str, env: str = "production", **kwargs) -> None: super().__init__(env=env, auth=auth, **kwargs) slug = self.org_id_slugs.get(org_id) or org_id self.base_url = self.base_url.replace("<tenant>", slug) self.endpoint = RequestsEndpoint(self.base_url.rstrip("/") + "/graphql", session=self.session)
def test_basic(mock_requests_send): '[Requests] - Test if basic usage with only essential parameters works' configure_mock_requests_send(mock_requests_send, graphql_response_ok) endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query) eq_(data, json.loads(graphql_response_ok)) check_mock_requests_send(mock_requests_send) eq_( str(endpoint), 'RequestsEndpoint(' + 'url={}, '.format(test_url) + 'base_headers={}, timeout=None, method=POST, auth=None)')
def test_basic_session(mock_requests_send): '[Requests] - Test if basic usage with session works' configure_mock_requests_send(mock_requests_send, graphql_response_ok) endpoint = RequestsEndpoint(test_url, session=requests.Session()) data = endpoint(graphql_query) eq_(data, json.loads(graphql_response_ok)) check_mock_requests_send(mock_requests_send) eq_( str(endpoint), 'RequestsEndpoint(' + 'url={}, '.format(test_url) + 'base_headers={}, timeout=None, method=POST, auth=None, ' + 'session=<class \'requests.sessions.Session\'>)')
def test_basic_auth(mock_requests_send): '[Requests] - Test if basic usage with only auth works' configure_mock_requests_send(mock_requests_send, graphql_response_ok) endpoint = RequestsEndpoint(test_url, auth=requests.auth.HTTPBasicAuth( "user", "password")) data = endpoint(graphql_query) eq_(data, json.loads(graphql_response_ok)) check_mock_requests_send(mock_requests_send) eq_( str(endpoint), 'RequestsEndpoint(' + 'url={}, '.format(test_url) + 'base_headers={}, timeout=None, method=POST, ' + 'auth=<class \'requests.auth.HTTPBasicAuth\'>)')
def test_headers(mock_requests_send): '[Requests] - Test if all headers are passed' configure_mock_requests_send(mock_requests_send, graphql_response_ok) base_headers = { 'Xpto': 'abc', } extra_headers = { 'Extra': '123', 'Accept': extra_accept_header, } endpoint = RequestsEndpoint(test_url, base_headers=base_headers) data = endpoint(graphql_query, extra_headers=extra_headers) eq_(data, json.loads(graphql_response_ok)) check_mock_requests_send(mock_requests_send, base_headers=base_headers, extra_headers=extra_headers)
def __init__(self, ua: str, auth: requests.auth.AuthBase = False): self.__version__ = __version__ self.ua = ua base_headers = { 'X-Domain-Id': '100', 'User-Agent': self.ua, } if auth is False: auth = NFLClientCredentials('nflapi') self.endpoint = RequestsEndpoint(API_HOST + ENDPOINT_V3, base_headers=base_headers, auth=auth) self.team = TeamHelper(self) self.schedule = ScheduleHelper(self) self.standings = StandingsHelper(self) self.game = GameHelper(self) self.game_detail = GameDetailHelper(self) self.roster = RosterHelper(self) self.player = PlayerHelper(self)
def test_get(mock_requests_send): '[Requests] - Test if HTTP method GET request works' configure_mock_requests_send(mock_requests_send, graphql_response_ok) base_headers = { 'Xpto': 'abc', } extra_headers = { 'Extra': '123', 'Accept': extra_accept_header, } variables = {'repoOwner': 'owner', 'repoName': 'name'} operation_name = 'xpto' endpoint = RequestsEndpoint(test_url, base_headers=base_headers, method='GET') data = endpoint( graphql_query, extra_headers=extra_headers, variables=variables, operation_name=operation_name, ) eq_(data, json.loads(graphql_response_ok)) check_mock_requests_send( mock_requests_send, method='GET', base_headers=base_headers, extra_headers=extra_headers, variables=variables, operation_name=operation_name, ) eq_( str(endpoint), 'RequestsEndpoint(' + 'url={}, '.format(test_url) + 'base_headers={}, '.format(base_headers) + 'timeout=None, method=GET, auth=None)', )
def test_json_error(mock_requests_send): '[Requests] - Test if broken server responses (invalid JSON) is handled' configure_mock_requests_send(mock_requests_send, graphql_response_json_error) endpoint = RequestsEndpoint(test_url) data = endpoint(graphql_query) exc = get_json_exception(graphql_response_json_error) got_exc = data['errors'][0].pop('exception') assert isinstance(got_exc, json.JSONDecodeError), \ '{} is not json.JSONDecodeError'.format(type(got_exc)) eq_( data, { 'errors': [{ 'message': str(exc), 'body': graphql_response_json_error, }], 'data': None, }) check_mock_requests_send(mock_requests_send)
def __init__(self, auth: Auth, env: str, **kwargs) -> None: super().__init__(env, auth, **kwargs) self.endpoint = RequestsEndpoint(f"{self.base_url}/graphql", session=self.session)
def __init__(self, oauth_token): headers = {"Authorization": f"Bearer {GITHUB_TOKEN}"} self.endpoint = RequestsEndpoint("https://api.github.com/graphql", headers)
def __init__(self, client: Client) -> None: self._hq = client self.endpoint = RequestsEndpoint(client.baseurl + '/graphql', session=client.session)
raise SystemExit('Usage: <token> <team/repo>') query = ''' query GitHubRepoIssues($repoOwner: String!, $repoName: String!) { repository(owner: $repoOwner, name: $repoName) { issues(first: 100) { nodes { number title } } } } ''' owner, name = repo.split('/', 1) variables = { 'repoOwner': owner, 'repoName': name, } url = 'https://api.github.com/graphql' headers = { 'Authorization': 'bearer ' + token, } endpoint = RequestsEndpoint(url, headers) data = endpoint(query, variables) json.dump(data, sys.stdout, sort_keys=True, indent=2, default=str)
def __init__(self, auth, base_headers): self.__mangle_datetime() self.endpoint = RequestsEndpoint(API_HOST + ENDPOINT_SHIELD_V3, base_headers=base_headers, auth=auth)