我正在使用 aiohttp 发出异步请求,我想测试我的代码。我想模拟 aiohttp.ClientSession 发送的请求。我正在寻找类似于响应处理requestslib模拟的方式。
我如何模拟aiohttp.ClientSession?
# sample method
async def get_resource(self, session):
async with aiohttp.ClientSession() as session:
response = await self.session.get("some-external-api.com/resource")
if response.status == 200:
result = await response.json()
return result
return {...}
# I want to do something like ...
aiohttp_responses.add(
method='GET',
url="some-external-api.com/resource",
status=200,
json={"message": "this worked"}
)
async def test_get_resource(self):
result = await get_resource()
assert result == {"message": "this worked"}
Run Code Online (Sandbox Code Playgroud)
编辑
我在几个项目中使用了https://github.com/pnuckowski/aioresponses,它非常适合我的需求。
如何定义异步装置并在异步测试中使用它们?
以下代码全部在同一个文件中,失败了.是否由测试跑者明确地称之为夹具并且没有等待?
@pytest.fixture
async def create_x(api_client):
x_id = await add_x(api_client)
return api_client, x_id
async def test_app(create_x, auth):
api_client, x_id = create_x
resp = await api_client.get(f'my_res/{x_id}', headers=auth)
assert resp.status == web.HTTPOk.status_code
Run Code Online (Sandbox Code Playgroud)
生产
==================================== ERRORS ====================================
_____________ ERROR at setup of test_app[pyloop] ______________
api_client = <aiohttp.test_utils.TestClient object at 0x7f27ec954f60>
@pytest.fixture
async def create_x(api_client):
> x_id = await add_x(api_client)
...
... cannot show the full trace and pathnames sorry
...
in __await__
ret = yield from self._coro /home/mbb/.pyenv/versions/3.6.3/envs/mr/lib/python3.6/site-packages/aiohttp/test_utils.py:245: in request
method, self.make_url(path), *args, …Run Code Online (Sandbox Code Playgroud) pytest python-3.x python-asyncio pytest-aiohttp pytest-asyncio
我在做什么
我正在通过构建一个 REST api 来学习 aiohttp,我正在使用 Pytest(及其 async 和 aiohttp 插件)进行测试。
对于我的第一次测试(我从一开始就使用 TDD)我有以下代码:
@pytest.mark.asyncio
async def test_handle_user_create(
aiohttp_client, init_test_app, create_test_user_table
):
payload = {
"email": "tintin@gmail.com",
"username": "Tintin",
"password": "y0u != n00b1e",
}
client = await aiohttp_client(init_test_app)
resp = await client.post("/users/", json=payload)
...
Run Code Online (Sandbox Code Playgroud)
aiohttp_client 是客户端装置来自 pytest-aiohttpinit_test_app 是一个固定装置,它基本上反映了我将要构建的应用程序create_test_user_table 是我在测试数据库中为用户创建表的夹具它有什么问题
我的第一个测试是在上面代码块的最后一行抛出以下运行时错误:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ …Run Code Online (Sandbox Code Playgroud)