`from ... import fastapp
import pytest
from async_asgi_testclient import TestClient as AsyncClient
from fastapi.testclient import TestClient
client = TestClient(fastapp)
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_something():
async def fetch_stream():
async with AsyncClient(fastapp) as ac:
url = f"/api/..."
response = await ac.post(
url,
json={...},
stream=True,
)
result = ""
async for line in response.iter_content(2):
line = line.decode("utf-8").strip()
result += line
if (
len(result) > 0
and "failed" not in result
):
print("success!")
assert True
else:
print("false!")
assert False
await fetch_stream()`
以上是我的代码。 我使用 docker 执行 fastapi 服务器。 测试命令是“docker exec container_name pytest /app/tests/ -Wignore -s --capture=no” 此命令测试成功后。但 Pytest 不会退出。
终端日志如下。
...something test print
============================== 1 passed in 36.76s ==============================
规格
async-asgi-testclient==1.4.11
pytest-asyncio==0.14.0
pytest-timeout==2.3.1
pytest==7.4.3`
我将@pytest.mark.timeout(60)应用于test_something。 它限制测试代码的执行时间。不过,并不影响pytest的终止。
docker 执行超时适用。它影响 pytest 的终止。但退出代码不为零。我使用退出代码进行 github 操作测试。详细命令如下
docker exec container_name timeout 60 pytest /app/tests/ -W ignore -s --capture=no
=========================== short test summary info ============================
FAILED tests/api/test_something.py::test_something - SystemExit: 0
FAILED tests/api/test_something2.py::test_something2 - SystemExit: 0
============================== 2 failed in 42.55s ==============================
这是因为无限不间断的事件。
我的asgi.py代码如下。
@fastapp.on_event("startup")
def startup_event():
start_memory_monitoring()
start_memory_monitoring函数是不间断的内存监控函数。
删除此代码后,pytest执行测试完成后正常退出。