Python aiohttp.test_utils.TestServer() Examples

The following are 16 code examples of aiohttp.test_utils.TestServer(). 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: conftest.py    From gql with MIT License 6 votes vote down vote up
def aiohttp_server():
    """Factory to create a TestServer instance, given an app.

    aiohttp_server(app, **kwargs)
    """
    servers = []

    async def go(app, *, port=None, **kwargs):  # type: ignore
        server = AIOHTTPTestServer(app, port=port)
        await server.start_server(**kwargs)
        servers.append(server)
        return server

    yield go

    while servers:
        await servers.pop().close()


# Adding debug logs to websocket tests 
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_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 #4
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() 
Example #5
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 #6
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 #7
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 #8
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 #9
Source File: conftest.py    From cookiecutter-aiohttp-sqlalchemy with MIT License 5 votes vote down vote up
def server(aiohttp_server) -> TestServer:
    app = create_app()
    server = await aiohttp_server(app, port=TEST_PORT)
    return server 
Example #10
Source File: conftest.py    From cookiecutter-aiohttp-sqlalchemy with MIT License 5 votes vote down vote up
def server(aiohttp_server) -> TestServer:
    app = create_app()
    server = await aiohttp_server(app, port=TEST_PORT)
    return server 
Example #11
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 #12
Source File: conftest.py    From aiozipkin with Apache License 2.0 5 votes vote down vote up
def fake_zipkin(loop):
    zipkin = FakeZipkin(loop=loop)

    server = TestServer(zipkin.app, loop=loop)
    await server.start_server()
    zipkin.port = server.port

    await yield_(zipkin)

    await server.close() 
Example #13
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 #14
Source File: test_client.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def server(aiohttp_server: Any, db_path: Path) -> _TestServer:
    app = await init_app(db_path)
    return await aiohttp_server(app) 
Example #15
Source File: test_client.py    From us-pycon-2019-tutorial with Apache License 2.0 5 votes vote down vote up
def client(server: _TestServer) -> AsyncIterator[Client]:
    async with Client(server.make_url("/"), "test_user") as client:
        yield client 
Example #16
Source File: conftest.py    From homematicip-rest-api with GNU General Public License v3.0 5 votes vote down vote up
def fake_cloud(aiohttp_server, ssl_ctx):
    """Defines the testserver funcarg"""

    loop = asyncio.new_event_loop()
    stop_threads = False
    t = Thread(
        name="aio_fake_cloud",
        target=start_background_loop,
        args=(lambda: stop_threads, loop),
    )
    t.setDaemon(True)
    t.start()

    aio_server = AsyncFakeCloudServer()
    app = web.Application()
    app.router.add_route("GET", "/{tail:.*}", aio_server)
    app.router.add_route("POST", "/{tail:.*}", aio_server)

    server = TestServer(app)
    asyncio.run_coroutine_threadsafe(
        server.start_server(loop=loop, ssl=ssl_ctx), loop
    ).result()
    aio_server.url = str(server._root)
    server.url = aio_server.url

    yield server

    asyncio.run_coroutine_threadsafe(server.close(), loop).result()
    stop_threads = True