3

我正在尝试使用pytest-aiohttp来测试我aiohttp的基于 REST API。有一个/authenticate端点,它返回一个身份验证令牌,基本上所有其他端点都需要授权标头中的令牌。我有以下完美运行的测试:

from pytest import fixture

from agora_backend.server import get_app

NAME, PASSWORD = "clin123", "password123"


@fixture
def client(loop, aiohttp_client):
    return loop.run_until_complete(aiohttp_client(get_app))


async def test_patient_success(client):
    auth_response = await client.post("/authenticate",
        json={"user_name": NAME, "user_pass": PASSWORD})

    auth_token =  await auth_response.text()

    response = await client.get("/clinician/patients",
        headers={"Authorization": f"Bearer {auth_token}"})

    assert response.status == 200


async def test_session_id_success(client):
    auth_response = await client.post("/authenticate",
        json={"user_name": NAME, "user_pass": PASSWORD})

    auth_token =  await auth_response.text()

    response = await client.get("/clinician/session/1",
        headers={"Authorization": f"Bearer {auth_token}"})

    assert response.status == 200

然而,这不是很干燥。我想对所有测试使用相同的授权令牌,因此我认为夹具是一个不错的选择。所以我尝试了以下代码:

from pytest import fixture

from agora_backend.server import get_app

NAME, PASSWORD = "clin123", "password123"


@fixture
def client(loop, aiohttp_client):
    return loop.run_until_complete(aiohttp_client(get_app))


@fixture
async def auth_token(client):
    auth_response = await client.post("/authenticate",
        json={"user_name": NAME, "user_pass": PASSWORD})

    return await auth_response.text()


async def test_patient_success(client, auth_token):
    response = await client.get("/clinician/patients",
        headers={"Authorization": f"Bearer {auth_token}"})

    assert response.status == 200


async def test_session_id_success(client, auth_token):
    response = await client.get("/clinician/session/1",
        headers={"Authorization": f"Bearer {auth_token}"})

    assert response.status == 200

但是,这会导致异常RuntimeError: Timeout context manager should be used inside a task。我曾尝试查看这个看似相关的答案,但我不确定它是否完全适用于我的情况。如果是的话,我不太明白如何将它应用到我的代码中。任何帮助,将不胜感激!

4

0 回答 0