Python aiohttp.test_utils.TestClient() Examples

The following are 22 code examples of aiohttp.test_utils.TestClient(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aiohttp.test_utils , or try the search function .
Example #1
Source File: test_rest.py    From us-pycon-2019-tutorial with Apache License 2.0 6 votes vote down vote up
def test_get_post(client: _TestClient, db: aiosqlite.Connection) -> None:
    async with db.execute(
        "INSERT INTO posts (title, text, owner, editor) VALUES (?, ?, ?, ?)",
        ["title", "text", "user", "user"],
    ) as cursor:
        post_id = cursor.lastrowid
    await db.commit()

    resp = await client.get(f"/api/{post_id}")
    assert resp.status == 200
    data = await resp.json()
    assert data == {
        "data": {
            "editor": "user",
            "id": "1",
            "owner": "user",
            "text": "text",
            "title": "title",
        },
        "status": "ok",
    } 
Example #2
Source File: tests.py    From dvhb-hybrid with MIT License 6 votes vote down vote up
def test_client(loop, client_class):
    """Factory to create a TestClient instance.
    test_client(app, **kwargs)
    """
    clients = []

    async def go(app, server_kwargs=None, **kwargs):
        if isinstance(app, web.Application):
            server_kwargs = server_kwargs or {}
            server = test_utils.TestServer(app, loop=loop, **server_kwargs)
        else:
            server = app
        client = client_class(server, loop=loop, **kwargs)
        await client.start_server()
        clients.append(client)
        return client

    yield go

    async def finalize():
        while clients:
            await clients.pop().close()

    loop.run_until_complete(finalize()) 
Example #3
Source File: test_api_server.py    From trinity with MIT License 5 votes vote down vote up
def http_client(http_server):
    client = TestClient(http_server)
    asyncio.ensure_future(client.start_server())
    await asyncio.sleep(0.01)
    return client 
Example #4
Source File: mock_api_order_book_data_source.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def __init__(self, client: TestClient, order_book_class: OrderBook, trading_pairs: Optional[List[str]] = None):
        super().__init__()
        self._client: TestClient = client
        self._order_book_class = order_book_class
        self._trading_pairs: Optional[List[str]] = trading_pairs
        self._diff_messages: asyncio.Queue = asyncio.Queue()
        self._snapshot_messages: asyncio.Queue = asyncio.Queue() 
Example #5
Source File: test_rest.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def test_add_post(client: _TestClient) -> None:
    POST_REQ = {"title": "test title", "text": "test text", "owner": "test user"}
    POST = {"id": 1, "editor": POST_REQ["owner"], **POST_REQ}
    resp = await client.post("/api", json=POST_REQ)
    assert resp.status == 200, await resp.text()
    data = await resp.json()
    assert data == {"data": POST, "status": "ok"}

    POST_WITHOUT_TEXT = POST.copy()
    del POST_WITHOUT_TEXT["text"]
    resp = await client.get("/api")
    assert resp.status == 200, await resp.text()
    data = await resp.json()
    assert data == {"data": [POST_WITHOUT_TEXT], "status": "ok"} 
Example #6
Source File: test_rest.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def test_list_empty(client: _TestClient) -> None:
    resp = await client.get("/api")
    assert resp.status == 200, await resp.text()
    data = await resp.json()
    assert data == {"data": [], "status": "ok"} 
Example #7
Source File: test_rest.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def client(aiohttp_client: Any, db_path: Path) -> _TestClient:
    app = await init_app(db_path)
    return await aiohttp_client(app) 
Example #8
Source File: __init__.py    From async-worker with MIT License 5 votes vote down vote up
def __aenter__(self) -> TestClient:
        self.client, self.server = await _get_client_and_server(self.app)
        return self.client 
Example #9
Source File: __init__.py    From async-worker with MIT License 5 votes vote down vote up
def _get_client_and_server(app: App) -> Tuple[TestClient, TestServer]:
    routes = app.routes_registry.http_routes
    http_app = web.Application()

    for route in routes:
        for route_def in route.aiohttp_routes():
            route_def.register(http_app.router)

    port = int(os.getenv("TEST_ASYNCWORKER_HTTP_PORT") or 0)
    server = TestServer(http_app, port=port)
    client = TestClient(server)
    await server.start_server()
    return (client, server) 
Example #10
Source File: test_test_utils.py    From async-worker with MIT License 5 votes vote down vote up
def test_decorated_method_can_have_its_own_params(self):
        @http_client(self.app)
        async def my_method(a, b, http_client):
            return (http_client, a, b)

        rv = await my_method(42, 10)

        self.assertTrue(isinstance(rv[0], TestClient))
        self.assertEqual([42, 10], [rv[1], rv[2]]) 
Example #11
Source File: test_test_utils.py    From async-worker with MIT License 5 votes vote down vote up
def test_client_is_passed_to_test(self):
        @http_client(self.app)
        async def my_test_case(client):
            return client

        client = await my_test_case()
        self.assertTrue(isinstance(client, TestClient)) 
Example #12
Source File: test_graphiqlview.py    From graphql-server-core with MIT License 5 votes vote down vote up
def client(app):
    client = TestClient(TestServer(app))
    await client.start_server()
    yield client
    await client.close() 
Example #13
Source File: util.py    From asgard-api with MIT License 5 votes vote down vote up
def aiohttp_client(self, app: asyncworker.App) -> TestClient:
        routes = app.routes_registry.http_routes
        http_app = web.Application()

        for route in routes:
            for route_def in route.aiohttp_routes():
                route_def.register(http_app.router)

        self.server = TestServer(
            http_app, port=int(os.getenv("TEST_ASYNCWORKER_HTTP_PORT") or 0)
        )
        client = TestClient(self.server)
        await self.server.start_server()

        return client 
Example #14
Source File: test_chromewhip.py    From chromewhip with MIT License 5 votes vote down vote up
def xtest_render_html_with_js_profile(event_loop):
    expected = BS(open(os.path.join(RESPONSES_DIR, 'httpbin.org.html.after_profile.txt')).read()).prettify()
    profile_name = 'httpbin-org-html'
    profile_path = os.path.join(PROJECT_ROOT, 'tests/resources/js/profiles/{}'.format(profile_name))
    client = tc(setup_app(loop=event_loop, js_profiles_path=profile_path), loop=event_loop)
    await client.start_server()
    resp = await client.get('/render.html?url={}&js={}'.format(
        quote('{}/html'.format(HTTPBIN_HOST)),
        profile_name))
    assert resp.status == 200
    text = await resp.text()
    assert expected == text 
Example #15
Source File: test_chromewhip.py    From chromewhip with MIT License 5 votes vote down vote up
def xtest_render_html_basic(event_loop):
    expected = BS(open(os.path.join(RESPONSES_DIR, 'httpbin.org.html.txt')).read()).prettify()
    client = tc(setup_app(loop=event_loop), loop=event_loop)
    await client.start_server()
    resp = await client.get('/render.html?url={}'.format(quote('{}/html'.format(HTTPBIN_HOST))))
    assert resp.status == 200
    text = await resp.text()
    assert expected == text 
Example #16
Source File: conftest.py    From cookiecutter-aiohttp-sqlalchemy with MIT License 5 votes vote down vote up
def client(aiohttp_client, server) -> TestClient:
    return await aiohttp_client(server) 
Example #17
Source File: conftest.py    From cookiecutter-aiohttp-sqlalchemy with MIT License 5 votes vote down vote up
def client(aiohttp_client, server) -> TestClient:
    return await aiohttp_client(server) 
Example #18
Source File: pytest_plugin.py    From aiohttp-xmlrpc with MIT License 5 votes vote down vote up
def test_rpc_client(loop):
    test_client = None
    rpc_client = None

    async def _create_from_app_factory(app_factory, *args, **kwargs):
        nonlocal test_client, rpc_client
        app = app_factory(loop, *args, **kwargs)
        test_client = TestClient(TestServer(app), loop=loop)
        await test_client.start_server()

        rpc_client = ServerProxy(
            '',
            loop=loop,
            client=test_client
        )
        return rpc_client

    yield _create_from_app_factory

    if rpc_client:
        loop.run_until_complete(rpc_client.close())
        rpc_client = None

    if test_client:
        loop.run_until_complete(test_client.close())
        test_client = None 
Example #19
Source File: openid_test.py    From kubernetes_asyncio with Apache License 2.0 5 votes vote down vote up
def fail_token_request_client():
    loop = asyncio.get_event_loop()
    app = web.Application()

    app.router.add_get('/.well-known/openid-configuration', respond_json({'token_endpoint': '/token'}))
    app.router.add_post('/token', make_responder(web.Response(status=500)))

    with patch('kubernetes_asyncio.config.openid.aiohttp.ClientSession') as _client_session:
        client = _TestClient(_TestServer(app, loop=loop), loop=loop)
        _client_session.return_value = client

        yield client 
Example #20
Source File: openid_test.py    From kubernetes_asyncio with Apache License 2.0 5 votes vote down vote up
def fail_well_known_client():
    loop = asyncio.get_event_loop()
    app = web.Application()

    app.router.add_get('/.well-known/openid-configuration', make_responder(web.Response(status=500)))

    with patch('kubernetes_asyncio.config.openid.aiohttp.ClientSession') as _client_session:
        client = _TestClient(_TestServer(app, loop=loop), loop=loop)
        _client_session.return_value = client
        yield client 
Example #21
Source File: openid_test.py    From kubernetes_asyncio with Apache License 2.0 5 votes vote down vote up
def working_client():
    loop = asyncio.get_event_loop()

    app = web.Application()

    app.router.add_get('/.well-known/openid-configuration', respond_json({'token_endpoint': '/token'}))
    app.router.add_post('/token', respond_json({'id-token': 'id-token-data', 'refresh-token': 'refresh-token-data'}))

    with patch('kubernetes_asyncio.config.openid.aiohttp.ClientSession') as _client_session:
        client = _TestClient(_TestServer(app, loop=loop), loop=loop)
        _client_session.return_value = client

        yield client 
Example #22
Source File: test_graphqlview.py    From graphql-server-core with MIT License 5 votes vote down vote up
def client(app):
    client = TestClient(TestServer(app))
    await client.start_server()
    yield client
    await client.close()