gpt4 book ai didi

pytest - 同时运行测试

转载 作者:行者123 更新时间:2023-12-05 00:10:49 24 4
gpt4 key购买 nike

我想使用 asyncio (/curio/trio) 和 pytest 同时运行多个测试,但我找不到任何相关信息。我需要自己安排吗?如果我这样做了,有没有办法有一个很好的输出来分离(子)测试用例?

这是我正在尝试的一个小玩具示例:

import pytest
import time
import asyncio

pytestmark = pytest.mark.asyncio
expected_duration = 1
accepted_error = 0.1

async def test_sleep():
start = time.time()
time.sleep(expected_duration)
duration = time.time() - start
assert abs(duration-expected_duration) < accepted_error

async def test_async_sleep():
start = time.time()
await asyncio.sleep(expected_duration)
duration = time.time() - start
assert abs(duration-expected_duration) < accepted_error

最佳答案

不幸的是,pytest 在内部工作的方式,你不能真正在同一时间在对 trio.run 的同一个调用下运行多个测试。/asyncio.run/curio.run . (这在某些方面也很好 - 它可以防止状态在测试之间泄漏,并且至少使用 trio 可以让您针对不同的测试以不同的方式配置 trio,例如,将一个测试设置为使用 autojump clock 而另一个测试则没有。)

绝对最简单的选择是使用 pytest-xdist 在单独的线程中运行测试。你仍然可以在每个测试内部使用异步——所有这些异步库都支持在不同线程中运行不同的循环。

如果您真的需要使用异步并发,那么我认为您必须编写一个 pytest 测试函数,然后在该函数中执行您自己的调度和并发。如果您这样做,那么从 pytest 的角度来看,只有一个测试,因此获得良好的每个测试输出并不容易。我想你可以尝试使用 pytest-subtests ?

关于pytest - 同时运行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56448398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com