Example #1
0
async def test_api_append_slash():
    api = aionap.API("http://localhost")
    # default
    assert not api._store['append_slash']
    await api.close()
    #
    api = aionap.API("http://localhost", append_slash=True)
    assert api._store['append_slash']
    await api.close()
Example #2
0
async def test_api_session_kwargs():
    api = aionap.API("http://localhost")
    # default
    assert not api._store['session']._conn_timeout
    await api.close()
    # set
    api = aionap.API("http://localhost", session_kwargs=dict(conn_timeout=5))
    assert api._store['session']._conn_timeout == 5
    await api.close()
Example #3
0
async def test_api_auth():
    api = aionap.API("http://localhost")
    # default
    assert not api._store['session']._default_auth
    await api.close()
    #
    api = aionap.API("http://localhost", auth=('user', 'password'))
    assert isinstance(api._store['session']._default_auth, aiohttp.BasicAuth)
    await api.close()
Example #4
0
async def test_api_format():
    api = aionap.API("http://localhost")
    # default json
    assert api._store['format'] == "json"
    await api.close()
    # yaml
    api = aionap.API("http://localhost", format='yaml')
    assert api._store['format'] == "yaml"
    await api.close()
Example #5
0
async def test_request_kwargs(httpbin):
    # be sure default user-agent is set
    async with aionap.API(httpbin.url) as api:
        resource = getattr(api, "user-agent")
        resp = await resource.get()
        assert resp["user-agent"]

    async with aionap.API(httpbin.url,
                          request_kwargs={"skip_auto_headers":
                                          ["user-agent"]}) as api:
        resource = getattr(api, "user-agent")
        resp = await resource.get()
        assert not resp["user-agent"]
Example #6
0
async def test_params(httpbin, http_method):
    """Just the plain http methods without data, params etc."""
    api = aionap.API(httpbin.url, append_slash=False)
    params = {'key': 'value', 'key2': 'value2'}
    async with api.anything as resource:
        resp = await getattr(resource, http_method)(**params)
        assert resp['args'] == params
Example #7
0
async def test_list_user(demo_url):
    async with aionap.API(demo_url) as demo:
        users = await demo.users.get()

    user = users[0]
    assert user['name'] == 'Leanne Graham'
    assert user['username'] == 'Bret'
Example #8
0
async def test_plain_methods(httpbin, http_method):
    """Just the plain http methods without data, params etc."""
    async with aionap.API(httpbin.url, append_slash=False) as api:
        resource = api.anything
        # resource.get()
        resp = await getattr(resource, http_method)()
        assert resp["method"] == http_method.upper()
Example #9
0
async def test_params(httpbin, http_method):
    """Just the plain http methods without data, params etc."""
    async with aionap.API(httpbin.url, append_slash=False) as api:
        params = {"key": "value", "key2": "value2"}
        resource = api.anything
        resp = await getattr(resource, http_method)(**params)
        assert resp["args"] == params
Example #10
0
async def test_deep_nested_resource_urls(httpbin):
    """Test _get_resource and __call__."""
    async with aionap.API(httpbin.url) as api:
        resource = api.anything.deep.nested.resource.urls
        resp = await resource.get()
        assert resp["method"] == "GET"
        assert resp["url"].endswith("deep/nested/resource/urls")
Example #11
0
async def test_all_http_status_codes(httpbin, code):
    """Just the plain http methods without data, params etc."""
    async with aionap.API(httpbin.url) as api:
        resource = api.status(code)
        if 300 <= code <= 399:
            resp = await resource.get()
            if code not in [300, 304]:
                # it's real location: XXX response, therefor test redirection
                code = 200
                # httpbin std redirect is to /get
                assert resp["url"].endswith("/get")
        elif 400 <= code <= 499:
            with pytest.raises(
                (aionap.exceptions.HttpClientError,
                 aionap.exceptions.HttpNotFoundError)) as excinfo:
                await resource.get()
            if code == 402:
                assert len(excinfo.value.content) > 0
            else:
                assert excinfo.value.content == b""
        elif 500 <= code <= 599:
            with pytest.raises(aionap.exceptions.HttpServerError) as excinfo:
                await resource.get()
            assert excinfo.value.content == b""
        else:
            await resource.get()
        assert resource._.status == code
Example #12
0
async def test_deep_nested_resource_urls(httpbin):
    """Test _get_resource and __call__."""
    async with aionap.API(httpbin.url) as api:
        resource = api.anything.deep.nested.resource.urls
        resp = await resource.get()
        assert resp['method'] == 'GET'
        assert resp['url'].endswith('deep/nested/resource/urls')
Example #13
0
async def test_list_user(demo_url):
    demo = aionap.API(demo_url)
    async with demo.users as resource:
        users = await resource.get()

    user = users[0]
    assert user['name'] == 'Leanne Graham'
    assert user['username'] == 'Bret'
Example #14
0
async def test_custom_content_type(httpbin, http_method):
    async with aionap.API(httpbin.url) as api:
        resource = getattr(api, http_method)
        resp = await getattr(resource,
                             http_method)(headers={
                                 "content-type": "application/foobar"
                             })
        assert resp["headers"]["Content-Type"] == "application/foobar"
Example #15
0
async def test_deep_nested_resource_urls_with_name(httpbin):
    """Test _get_resource and __call__."""
    async with aionap.API(httpbin.url) as api:
        resource = api.anything.deep("name").nested("name").resource(
            "name").urls("name")
        resp = await resource.get()
        assert resp["url"].endswith(
            "/deep/name/nested/name/resource/name/urls/name")
Example #16
0
async def main():
    demo = aionap.API('https://jsonplaceholder.typicode.com')
    async with demo.users as resource:
        users = await resource.get()

    print(f"In total {len(users)} users:")
    for user in users:
        print(f"Name: {user['name']} Company: {user['company']['name']}")
Example #17
0
async def test_custom_content_type(httpbin, http_method):
    async with aionap.API(httpbin.url) as api:
        resource = getattr(api, http_method)
        resp = await getattr(resource,
                             http_method)(headers={
                                 'content-type': 'application/foobar'
                             })
        assert resp['headers']['Content-Type'] == 'application/foobar'
Example #18
0
async def test_close(httpbin):
    api = aionap.API(httpbin.url)
    await api.close()
    # should raise closed exception
    with pytest.raises(RuntimeError):
        await api.anything.resource.get()
    with pytest.raises(RuntimeError):
        async with api.anything as resource:
            await resource.get()
Example #19
0
async def test_update_post(demo_url):
    async with aionap.API(demo_url) as demo:
        post = await demo.posts(1).get()
        assert post['title']

        # update post
        details = {'title': post['title'] * 2}
        post = await demo.posts(1).put(data=details)
        assert post['title'] == details['title']
Example #20
0
async def test_send_data(httpbin, format, http_send_method):
    data = {'foo': 'bar'}
    serializer = aionap.serialize.Serializer().get_serializer(name=format)
    async with aionap.API(httpbin.url, format=format) as api:
        resource = getattr(api, http_send_method)
        resp = await getattr(resource, http_send_method)(data=data)
        assert format in resp['headers'].get('Accept')
        assert format in resp['headers'].get('Content-Type')
        assert serializer.dumps(data) == resp['data']
Example #21
0
async def main():
    # Create a resource for the API
    async with aionap.API('https://jsonplaceholder.typicode.com') as demo:
        # Send a GET request to https://jsonplaceholder.typicode.com/users
        users = await demo.users.get()

    print(f"In total {len(users)} users:")
    for user in users:
        print(f"Name: {user['name']} Company: {user['company']['name']}")
Example #22
0
async def test_send_data(httpbin, format, http_send_method):
    data = {"foo": "bar"}
    serializer = aionap.serialize.Serializer().get_serializer(name=format)
    async with aionap.API(httpbin.url, format=format) as api:
        resource = getattr(api, http_send_method)
        resp = await getattr(resource, http_send_method)(data=data)
        assert format in resp["headers"].get("Accept")
        assert format in resp["headers"].get("Content-Type")
        assert serializer.dumps(data) == resp["data"]
Example #23
0
async def test_send_files(httpbin, tmpdir, http_send_method):
    """POST and PUT files."""
    TEST_STR = "TEST TEST TEST"
    tmpfile = tmpdir.join("tmp.txt")
    tmpfile.write(TEST_STR)
    api = aionap.API(httpbin.url)
    async with getattr(api, http_send_method) as resource:
        resp = await getattr(resource,
                             http_send_method)(file=open(tmpfile, 'rb'))
        assert TEST_STR == resp['files']['file']
Example #24
0
async def test_new_post(demo_url):
    details = {
        'title': 'A post entry about the life',
        'body': 'Hi. I want to talk about the life and the universe ...',
        'userId': 1
    }
    async with aionap.API(demo_url) as demo:
        post = await demo.posts.post(data=details)
    assert post['id']
    assert post['userId'] == 1
Example #25
0
async def test_update_post(demo_url):
    demo = aionap.API(demo_url)
    async with demo.posts(1) as resource:
        post = await resource.get()
        assert post['title']

        # update post
        details = {'title': post['title'] * 2}
        post = await resource.put(data=details)
        assert post['title'] == details['title']
Example #26
0
async def test_send_files(httpbin, tmpdir, http_send_method):
    """POST and PUT files."""
    TEST_STR = "TEST TEST TEST"
    tmpfile = tmpdir.join("tmp.txt")
    tmpfile.write(TEST_STR)
    async with aionap.API(httpbin.url) as api:
        resource = getattr(api, http_send_method)
        resp = await getattr(resource,
                             http_send_method)(file=open(tmpfile, "rb"))
        assert TEST_STR == resp["files"]["file"]
Example #27
0
async def test_all_http_status_codes(httpbin, code):
    """Just the plain http methods without data, params etc."""
    api = aionap.API(httpbin.url)
    async with api.status(code) as resource:
        if 300 <= code <= 399:
            resp = await resource.get()
            if code not in [300, 304]:
                # it's real location: XXX response, therefor test redirection
                code = 200
                # httpbin std redirect is to /get
                assert resp['url'].endswith('/get')
        elif 400 <= code <= 499:
            with pytest.raises((aionap.exceptions.HttpClientError,
                                aionap.exceptions.HttpNotFoundError)):
                await resource.get()
        elif 500 <= code <= 599:
            with pytest.raises(aionap.exceptions.HttpServerError):
                await resource.get()
        else:
            await resource.get()
        assert resource._.status == code
Example #28
0
async def test_api_base_url():
    api = aionap.API("http://localhost")
    assert api._store['base_url'] == "http://localhost"
    await api.close()
Example #29
0
async def test_default_no_append_slash(httpbin):
    async with aionap.API(httpbin.url) as api:
        resource = api.anything.whatever
        resp = await resource.get()
        assert not resp["url"].endswith("/")
Example #30
0
async def test_deep_nested_resource_urls_with_ids(httpbin):
    """Test _get_resource and __call__."""
    async with aionap.API(httpbin.url) as api:
        resource = api.anything.deep(1).nested(1).resource(1).urls(1)
        resp = await resource.get()
        assert resp["url"].endswith("/deep/1/nested/1/resource/1/urls/1")