关于python:与pytest并行运行单元测试?

Running unit tests in parallel with pytest?

本问题已经有最佳答案,请猛点这里访问。

如何并行化用pytest编写的单元测试的执行?我可以选择哪些并行策略?


为了并行运行pytests,您将需要安装pytest-xdist。请查看下面列出的不同并行策略,您可以使用其中任何一种(但是我敢打赌,其中一种最适合您的特定情况):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
pip install pytest-xdist

# The most primitive case, sending tests to multiple CPUs:
pytest -n NUM

# Execute tests within 3 subprocesses.
pytest --dist=each --tx 3*popen//python=python3.6

# Execute tests in 3 forked subprocess. Won't work on windows.
pytest --dist=each --tx 3*popen//python=python3.6 --boxed

# Sending tests to the ssh slaves
pytest --dist=each --tx ssh=first_slave --tx ssh=seconds_slave --rsyncdir package package

# Sending tests to the socket server, link is available below.
python socketserver.py :8889 &
python socketserver.py :8890 &
pytest --dist=each --tx socket=localhost:8889 --tx socket=localhost:8890

您可以为--dist(-d)参数提供不同的值,该参数处理测试在各个工作程序之间的分配方式,有关--dist.pb用法的更多信息,请参见文档。

注意:一旦执行了测试,socket_server.py就会关闭。我建议您从单独的终端窗口运行套接字服务器以进行调试

您可以引入更复杂的流程,例如,在已启动套接字服务器的" pytest worker"和另一个与之通信并充当" pytestRunner"的docker容器内,在docker容器中运行测试。