def test_auth(self): client = MockClient(snug.Response(204)) result = snug.execute(myquery(), auth=('user', 'pw'), client=client) assert result == snug.Response(204) assert client.request == snug.GET( 'my/url', headers={'Authorization': 'Basic dXNlcjpwdw=='})
def test_auth_callable(self): client = MockClient(snug.Response(204)) auther = methodcaller('with_headers', {'X-My-Auth': 'letmein'}) result = snug.execute(myquery(), auth=auther, client=client) assert result == snug.Response(204) assert client.request == snug.GET('my/url', headers={'X-My-Auth': 'letmein'})
def test_none_auth(self, loop): from .py3_only import MockAsyncClient client = MockAsyncClient(snug.Response(204)) future = snug.execute_async(myquery(), auth=None, client=client) result = loop.run_until_complete(future) assert result == snug.Response(204) assert client.request == snug.GET('my/url')
def test_auth_callable(self, loop): from .py3_only import MockAsyncClient client = MockAsyncClient(snug.Response(204)) auther = methodcaller('with_headers', {'X-My-Auth': 'letmein'}) future = snug.execute_async(myquery(), auth=auther, client=client) result = loop.run_until_complete(future) assert result == snug.Response(204) assert client.request == snug.GET('my/url', headers={'X-My-Auth': 'letmein'})
def test_custom_execute(self): client = MockClient(snug.Response(204)) class MyQuery(object): def __execute__(self, client, auth): return client.send(snug.GET('my/url')) result = snug.execute(MyQuery(), client=client) assert result == snug.Response(204) assert client.request == snug.GET('my/url')
def test_auth(self, loop): from .py3_only import MockAsyncClient client = MockAsyncClient(snug.Response(204)) future = snug.execute_async(myquery(), auth=('user', 'pw'), client=client) result = loop.run_until_complete(future) assert result == snug.Response(204) assert client.request == snug.GET( 'my/url', headers={'Authorization': 'Basic dXNlcjpwdw=='})
def test_custom_execute(self, loop): from .py3_only import MockAsyncClient client = MockAsyncClient(snug.Response(204)) class MyQuery: def __execute_async__(self, client, auth): return client.send(snug.GET('my/url')) future = snug.execute_async(MyQuery(), client=client) result = loop.run_until_complete(future) assert result == snug.Response(204) assert client.request == snug.GET('my/url')
def test_defaults(self, loop, mocker): import asyncio from .py3_only import awaitable send = mocker.patch('snug._async.send_async', return_value=awaitable(snug.Response(204))) future = snug.execute_async(myquery()) result = loop.run_until_complete(future) assert result == snug.Response(204) client, req = send.call_args[0] assert isinstance(client, asyncio.AbstractEventLoop) assert req == snug.GET('my/url')
def test_query(self): query = quiz.Query(DogQuery, _.dog[_.name.bark_volume]) response = snug.Response( 200, json.dumps({ "data": { "dog": { "name": "Fred", "bark_volume": 8 } } }).encode(), ) client = MockClient(response) result = quiz.execute(query, url="https://my.url/api", client=client) assert result == DogQuery(dog=Dog(name="Fred", bark_volume=8)) request = client.request assert result.__metadata__ == quiz.QueryMetadata(response=response, request=request) assert request.url == "https://my.url/api" assert request.method == "POST" assert json.loads(request.content.decode()) == { "query": quiz.gql(query) } assert request.headers == {"Content-Type": "application/json"}
def test_errors(self, event_loop): client = MockAsyncClient( snug.Response( 200, json.dumps({ "data": { "foo": 4 }, "errors": [{ "message": "foo" }] }).encode(), )) future = quiz.execute_async( "my query", url="https://my.url/api", client=client, auth=token_auth("foo"), ) with pytest.raises(quiz.ErrorResponse) as exc: event_loop.run_until_complete(future) assert exc.value == quiz.ErrorResponse({"foo": 4}, [{ "message": "foo" }])
def test_query(self): query = quiz.Query(DogQuery, _.dog[_.name.bark_volume]) client = MockClient( snug.Response( 200, json.dumps({ 'data': { 'dog': { 'name': 'Fred', 'bark_volume': 8, } } }).encode())) result = quiz.execute(query, url='https://my.url/api', client=client) assert result == DogQuery(dog=Dog( name='Fred', bark_volume=8, )) request = client.request assert request.url == 'https://my.url/api' assert request.method == 'POST' assert json.loads(request.content.decode()) == { 'query': quiz.gql(query) } assert request.headers == {'Content-Type': 'application/json'}
def test_non_string(self, event_loop): query = quiz.Query(DogQuery, _.dog[_.name.bark_volume]) client = MockAsyncClient( snug.Response( 200, json.dumps({ "data": { "dog": { "name": "Fred", "bark_volume": 8 } } }).encode(), )) future = quiz.execute_async(query, url="https://my.url/api", client=client) result = event_loop.run_until_complete(future) assert result == DogQuery(dog=Dog(name="Fred", bark_volume=8)) request = client.request assert request.url == "https://my.url/api" assert request.method == "POST" assert json.loads(request.content.decode()) == { "query": quiz.gql(query) } assert request.headers == {"Content-Type": "application/json"}
def test_success(self, event_loop): response = snug.Response(200, b'{"data": {"foo": 4, "bar": ""}}') client = MockAsyncClient(response) future = quiz.execute_async( "my query", url="https://my.url/api", auth=token_auth("foo"), client=client, ) result = event_loop.run_until_complete(future) assert isinstance(result, quiz.RawResult) assert result == {"foo": 4, "bar": ""} assert len(result) == 2 assert result["foo"] == 4 assert set(result) == {"foo", "bar"} assert isinstance(result, Mapping) assert result.__metadata__ == quiz.QueryMetadata( response=response, request=snug.POST( "https://my.url/api", headers={"Content-Type": "application/json"}, content=b'{"query": "my query"}', ), ) request = client.request assert request.url == "https://my.url/api" assert request.method == "POST" assert json.loads(request.content.decode()) == {"query": "my query"} assert request.headers == { "Authorization": "token foo", "Content-Type": "application/json", }
def test_resolve(): loaders = {Post: lambda data: Post(**data)}.__getitem__ @snug.Query(Post) def post(id: int): """a post by its ID""" return snug.Request(f'posts/{id}/') query = post(id=4) api = snug.Api( prepare=methodcaller('add_prefix', 'mysite.com/api/'), parse=compose( json.loads, methodcaller('decode'), attrgetter('content')), add_auth=lambda req, auth: req.add_headers({'Authorization': 'me'}), ) sender = MockSender([ (snug.Request('mysite.com/api/posts/4/', headers={'Authorization': 'me'}), snug.Response(200, b'{"id": 4, "title": "my post!"}', headers={})) ]) response = snug.resolve(query, api=api, sender=sender, auth='me', loaders=loaders) assert isinstance(response, Post) assert response == Post(id=4, title='my post!')
def test_http_error(): err = quiz.HTTPError( snug.Response(404, content=b"not found!\x00"), snug.Request("POST", "https://my.url/api"), ) assert "not found!\\x00" in str(err) assert "404" in str(err) assert "my.url" in str(err)
def test_http_error(self): err_response = snug.Response(403, b'this is an error!') client = MockClient(err_response) with pytest.raises(quiz.HTTPError) as exc: quiz.execute('my query', url='https://my.url/api', client=client, auth=token_auth('foo')) assert exc.value == quiz.HTTPError(err_response)
def test_wrong_type(self): client = MockClient(snug.Response(200, b'{"data": {"foo": 4}}')) with pytest.raises(NotImplementedError, match="not executable: 17"): quiz.execute( 17, url="https://my.url/api", client=client, auth=token_auth("foo"), )
def test_equality(self): rsp = snug.Response(204) other = rsp.replace() assert rsp == other assert not rsp != other assert not rsp == rsp.replace(headers={'foo': 'bar'}) assert rsp != rsp.replace(headers={'foo': 'bar'}) assert not rsp == object() assert rsp != object()
def test_http_error(self, mocker): err_response = snug.Response(403, b"this is an error!") client = MockClient(err_response) with pytest.raises(quiz.HTTPError) as exc: quiz.execute( "my query", url="https://my.url/api", client=client, auth=token_auth("foo"), ) assert exc.value == quiz.HTTPError( err_response, client.request.replace(headers=mocker.ANY))
def test_fails(self, raw_schema): client = MockClient( snug.Response( 200, json.dumps({ 'data': { '__schema': None }, 'errors': 'foo' }).encode())) with pytest.raises(quiz.ErrorResponse): quiz.Schema.from_url('https://my.url/graphql', client=client)
def test_fails(self, raw_schema): client = MockClient( snug.Response( 200, json.dumps({ "data": { "__schema": None }, "errors": "foo" }).encode(), )) with pytest.raises(quiz.ErrorResponse): quiz.Schema.from_url("https://my.url/graphql", client=client)
def test_success(self, raw_schema): client = MockClient( snug.Response( 200, json.dumps({ 'data': { '__schema': raw_schema } }).encode())) result = quiz.Schema.from_url('https://my.url/graphql', client=client) assert client.request.url == 'https://my.url/graphql' assert isinstance(result, quiz.Schema) assert result.raw == raw_schema
async def test_channel_create(exec): create = slack.channels.create('test channel') query = iter(create) req = next(query) assert req.method == 'POST' assert req.url.endswith('channels.create') assert req.headers['Content-Type'] == 'application/json' assert json.loads(req.content) == { 'name': 'test channel' } channel = sendreturn(query, snug.Response(200, CREATE_CHANNEL_RESPONSE)) assert isinstance(channel, slack.Channel) assert channel.id == 'C0DEL09A5'
def test_errors_without_data(self): client = MockClient( snug.Response( 200, json.dumps({ 'errors': [{ 'message': 'foo' }] }).encode())) with pytest.raises(quiz.ErrorResponse) as exc: quiz.execute('my query', url='https://my.url/api', client=client, auth=token_auth('foo')) assert exc.value == quiz.ErrorResponse({}, [{'message': 'foo'}])
async def test_post_chat_message(exec): post = slack.chat.post_message('#python', 'test message') query = iter(post) req = next(query) assert req.method == 'POST' assert req.url.endswith('chat.postMessage') assert req.headers['Content-Type'] == 'application/json' assert json.loads(req.content) == { 'channel': '#python', 'text': 'test message' } msg = sendreturn(query, snug.Response(200, POST_MESSAGE_RESPONSE)) assert isinstance(msg, slack.Message) assert msg.text == 'Here\'s a message for you'
def test_simple_string(self): client = MockClient(snug.Response(200, b'{"data": {"foo": 4}}')) result = quiz.execute('my query', url='https://my.url/api', client=client, auth=token_auth('foo')) assert result == {'foo': 4} request = client.request assert request.url == 'https://my.url/api' assert request.method == 'POST' assert json.loads(request.content.decode()) == {'query': 'my query'} assert request.headers == { 'Authorization': 'token foo', 'Content-Type': 'application/json' }
def test_success(self, event_loop): client = MockClient(snug.Response(200, b'{"data": {"foo": 4}}')) future = quiz.execute_async('my query', url='https://my.url/api', auth=token_auth('foo'), client=client) result = event_loop.run_until_complete(future) assert result == {'foo': 4} request = client.request assert request.url == 'https://my.url/api' assert request.method == 'POST' assert json.loads(request.content.decode()) == {'query': 'my query'} assert request.headers == { 'Authorization': 'token foo', 'Content-Type': 'application/json' }
def test_errors_without_data(self): client = MockClient( snug.Response( 200, json.dumps({ "errors": [{ "message": "foo" }] }).encode())) with pytest.raises(quiz.ErrorResponse) as exc: quiz.execute( "my query", url="https://my.url/api", client=client, auth=token_auth("foo"), ) assert exc.value == quiz.ErrorResponse({}, [{"message": "foo"}])
async def test_channel_list(exec): lookup = slack.channels.list_(exclude_archived=True) if live: result = await exec(lookup) assert isinstance(result.content[0], slack.Channel) query = iter(lookup) req = next(query) assert req.url.endswith('channels.list') assert req.params['exclude_archived'] == 'true' outcome = sendreturn(query, snug.Response(200, CHANNEL_LIST_RESULT)) assert isinstance(outcome[0], slack.Channel) assert len(outcome[0].members) == 2 assert outcome.next_query.cursor == "dGVhbTpDMUg5UkVTR0w="
def test_simple_string(self): client = MockClient(snug.Response(200, b'{"data": {"foo": 4}}')) result = quiz.execute( "my query", url="https://my.url/api", client=client, auth=token_auth("foo"), ) assert result == {"foo": 4} request = client.request assert request.url == "https://my.url/api" assert request.method == "POST" assert json.loads(request.content.decode()) == {"query": "my query"} assert request.headers == { "Authorization": "token foo", "Content-Type": "application/json", }