按照 Nathaniel 的建议使用 pytest-subtests 似乎是一个可行的解决方案。这是使用 trio 解决的方法,它对名称以 . 开头的每个函数运行子测试io_
。
import pytest
import sys
import trio
import inspect
import re
import time
pytestmark = pytest.mark.trio
io_test_pattern = re.compile("io_.*")
async def tests(subtests):
def find_io_tests(subtests, ignored_names):
functions = inspect.getmembers(sys.modules[__name__], inspect.isfunction)
for (f_name, function) in functions:
if f_name in ignored_names:
continue
if re.search(io_test_pattern, f_name):
yield (run, subtests, f_name, function)
async def run(subtests, test_name, test_function):
with subtests.test(msg=test_name):
await test_function()
self_name = inspect.currentframe().f_code.co_name
async with trio.open_nursery() as nursery:
for io_test in find_io_tests(subtests, {self_name}):
nursery.start_soon(*io_test)
accepted_error = 0.1
async def io_test_1():
await assert_sleep_duration_ok(1)
async def io_test_2():
await assert_sleep_duration_ok(2)
async def io_test_3():
await assert_sleep_duration_ok(3)
async def io_test_4():
await assert_sleep_duration_ok(4)
async def assert_sleep_duration_ok(duration):
start = time.time()
await trio.sleep(duration)
actual_duration = time.time() - start
assert abs(actual_duration - duration) < accepted_error
运行python -m pytest -v
输出:
============================ test session starts =============================
platform darwin -- Python 3.7.0, pytest-4.6.2, py-1.8.0, pluggy-0.12.0
plugins: asyncio-0.10.0, trio-0.5.2, subtests-0.2.1
collected 1 item
tests/stripe_test.py::tests PASSED [100%]
tests/stripe_test.py::tests PASSED [100%]
tests/stripe_test.py::tests PASSED [100%]
tests/stripe_test.py::tests PASSED [100%]
tests/stripe_test.py::tests PASSED [100%]
========================== 1 passed in 4.07 seconds ==========================
这并不完美,因为百分比仅与测试数量相关,而不与子测试数量相关(即io_*
此处标记的函数),但这似乎是一个好的开始。
另请注意,它time.time()
已被使用,因此它对 trio 和 asyncio 都有意义,但在实际用例中trio.current_time()
应改为使用。
使用 asyncio 可以实现相同的测试,您基本上必须替换三件事:
pytestmark = pytest.mark.trio
→pytestmark = pytest.mark.asyncio
yield (run, subtests, f_name, function)
→yield run(subtests, f_name, function)
- 最后,护士循环应该被替换为:
await asyncio.gather(*find_io_tests(subtests, {self_name}))