Ejemplo n.º 1
0
    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=='})
Ejemplo n.º 2
0
    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'})
Ejemplo n.º 3
0
    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')
Ejemplo n.º 4
0
    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'})
Ejemplo n.º 5
0
    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')
Ejemplo n.º 6
0
    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=='})
Ejemplo n.º 7
0
    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')
Ejemplo n.º 8
0
    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')
Ejemplo n.º 9
0
    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"}
Ejemplo n.º 10
0
    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"
        }])
Ejemplo n.º 11
0
    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'}
Ejemplo n.º 12
0
    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"}
Ejemplo n.º 13
0
    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",
        }
Ejemplo n.º 14
0
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!')
Ejemplo n.º 15
0
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)
Ejemplo n.º 16
0
 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)
Ejemplo n.º 17
0
 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"),
         )
Ejemplo n.º 18
0
    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()
Ejemplo n.º 19
0
 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))
Ejemplo n.º 20
0
    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)
Ejemplo n.º 21
0
    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)
Ejemplo n.º 22
0
    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
Ejemplo n.º 23
0
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'
Ejemplo n.º 24
0
 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'}])
Ejemplo n.º 25
0
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'
Ejemplo n.º 26
0
    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'
        }
Ejemplo n.º 27
0
    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'
        }
Ejemplo n.º 28
0
 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"}])
Ejemplo n.º 29
0
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="
Ejemplo n.º 30
0
    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",
        }