一个简单的pytest插件,用于并行运行测试
项目描述
一个简单的pytest插件,用于并行运行测试
这个pytest插件将一组通常按顺序运行的测试转换为并行执行。
pytest-run-parallel的主要目标是发现在使用C库时可能存在的线程安全问题,这对于PEP703至关重要,它为不依赖于全局解释器锁(GIL)的CPython实现提供了一条路径,从而允许在利用CPython解释器的程序中实现正确的并行性。
有关C线程安全问题的更多信息,请访问https://py-free-threading.github.io/上的免费线程社区指南
功能
一个全局CLI标志--parallel-threads,用于并行运行测试套件
一个标记pytest.mark.parallel_threads,用于标记单个测试以并行运行
要求
pytest-run-parallel仅依赖于pytest。
安装
您可以通过从PyPI使用pip安装“pytest-run-parallel”
$ pip install pytest-run-parallel
用法
此插件有两种工作模式,一种是通过 --parallel-threads pytest CLI 标志,允许整个测试套件并行运行
pytest --parallel-threads=10 tests
默认情况下,parallel-threads 的值将为 1,因此除非设置了标志,否则不会修改 pytest 的常规行为。
另一种工作模式发生在单个测试级别,通过 pytest.mark.parallel_threads 标记。
# test_file.py
import pytest
@pytest.fixture
def my_fixture():
...
@pytest.mark.parallel_threads(2)
def test_something_1():
# This test will be run in parallel using two concurrent threads
...
@pytest.mark.parametrize('arg', [1, 2, 3])
@pytest.mark.parallel_threads(3)
def test_fixutre(my_fixture, arg):
# pytest markers and fixtures are supported as well
...
同时支持两种工作模式,即
# test_something_1 and test_fixutre will be run using their set number of
# threads; other tests will be run using 5 threads.
pytest -x -v --parallel-threads=5 test_file.py
此外,pytest-run-parallel 提供了 num_parallel_threads .fixture,它使测试能够知道正在生成的线程数。
# test_file.py
import pytest
def test_skip_if_parallel(num_parallel_threads):
if num_parallel_threads > 1:
pytest.skip(reason='does not work in parallel')
...
最后,thread_comp fixture 允许并行测试调试,通过提供 ThreadComparator 的实例,其 __call__ 方法允许检查在特定执行步骤期间所有线程产生的值是否相同。
# test_file.py
def test_same_execution_values(thread_comp):
a = 2
b = [3, 4, 5]
c = None
# Check that the values for a, b, c are the same across tests
thread_comp(a=a, b=b, c=c)
贡献
非常欢迎贡献。可以在 tox 中运行测试,请在提交拉取请求之前确保覆盖率至少保持不变。
许可证
根据 MIT 许可证分发,“pytest-run-parallel” 是免费和开源软件。
问题
如果您遇到任何问题,请提交问题,并附上详细描述。