我会结合 pytest 和 trio(或 curio,如果这更容易的话),即将我的测试用例编写为协程函数。通过在以下位置声明自定义测试运行器,这相对容易实现conftest.py
:
@pytest.mark.tryfirst
def pytest_pyfunc_call(pyfuncitem):
'''If item is a coroutine function, run it under trio'''
if not inspect.iscoroutinefunction(pyfuncitem.obj):
return
kernel = trio.Kernel()
funcargs = pyfuncitem.funcargs
testargs = {arg: funcargs[arg]
for arg in pyfuncitem._fixtureinfo.argnames}
try:
kernel.run(functools.partial(pyfuncitem.obj, **testargs))
finally:
kernel.run(shutdown=True)
return True
这允许我编写这样的测试用例:
async def test_something():
server = MockServer()
server_task = await trio.run(server.serve)
try:
# test the server
finally:
server.please_terminate()
try:
with trio.fail_after(30):
server_task.join()
except TooSlowError:
server_task.cancel()
但这是很多样板文件。在非异步代码中,我会将其分解为一个夹具:
@pytest.yield_fixture()
def mock_server():
server = MockServer()
thread = threading.Thread(server.serve)
thread.start()
try:
yield server
finally:
server.please_terminate()
thread.join()
server.server_close()
def test_something(mock_server):
# do the test..
有没有办法在三重奏中做同样的事情,即实现异步固定装置?理想情况下,我会写:
async def test_something(mock_server):
# do the test..