【pytes-19】pytest-xdist分布式运行

前言

  • 生活中常见的例子:本来需要先炒西红柿,10分钟;再炒白菜10分钟,加起来需要20分钟。用了多线程之后,分别把菜放进两个锅里炒,10分钟就搞定了。
  • 同理,平常我们功能测试用例非常多时,比如有1千条用例,假设每个用例需要1分钟,如果单个测试人员执行需要1000分钟
  • 当项目非常紧急时候,就需要把任务分给10个人去执行,以前需要花1000分钟的,现在100分钟就可以了,就跟多线程的概念有点类似。
  • pytest-adist的出现就是为了节省项目组测试时间

安装

pip install pytest-xdist

使用

项目分布结构

demo_pytest
│  conftest.py
│  __init__.py
│              
├─toutiao
│  │  conftest.py
│  │  test_toutiao_1.py
│  │  __init__.py 
│          
├─vx
│  │  conftest.py
│  │  test_vx_1.py
│  │  __init__.py 

代码参考

#demo_pyetst/conftest.py
import pytest
@pytest.fixture(scope="session")
def openBroswer():
    print("打开浏览器")

#demo_pyetst/toutiao/conftest.py
import pytest
@pytest.fixture(scope="session")
def search_data():
    print("搜索今日头条")
#demo_pyetst/toutiao/test_b.py import pytest import time def test_01(openBroswer,search_data): print("toutiao用例1") time.sleep(1) def test_02(openBroswer,search_data): print("toutiao用例2") time.sleep(1) def test_03(openBroswer,search_data): print("toutiao用例3") time.sleep(1) if __name__ == '__main__': pytest.main(["-s","test_b.py"]) #demo_pytest/vx/conftest.py import pytest @pytest.fixture(scope="function") def search_vx(): print("搜索微信")
#demo_pytest/vx/test_a.py import pytest import time def test_1(openBroswer,search_vx): print("vx搜索用例1") time.sleep(1) def test_2(openBroswer,search_vx): print("vx添加用例2") time.sleep(1) if __name__ == '__main__': pytest.main(["-s","test_a.py"]) #pytest_demo/vx/test_c.py import pytest import time def test_3(openBroswer, search_vx): print("vx测试用例3") time.sleep(1) def test_4(openBroswer, search_vx): print("vx测试用例4") time.sleep(1) def test_5(openBroswer, search_vx): print("vx测试用例5") time.sleep(1) if __name__ == "__main__": pytest.main(["-s", "test_c.py"])

运行结果:

 正常运行需要消耗时间:8.14s。

从结果可以看出,执行一条用例大概1s(因为每个用例都加了 sleep(1),一共8条用例,总共运行8.14s;那么如果有1000条用例,执行时间就真的是1000s

多cpu并行执行用例

直接加个-n参数即可,后面num参数就是并行数量,比如num设置为3

pytest -n NUMCPUS

 设置并行运行数量为3,消耗时间:4.6s,大大的缩短了用例时间

pytest-xdist+pytest-html组合

pytest -n 3 --html=report.html --self-contained-html

拓展

参照官网地址 :https://github.com/pytest-dev/pytest-xdist/blob/master/README.rst

该pytest-xdist插件扩展了一些独特的测试执行模式pytest:

  • --looponfail:在子进程中重复运行测试。每次运行之后,pytest会等待,直到项目中的文件发生更改,然后重新运行以前失败的测试。重复此过程直到所有测试通过,之后再次执行完整运行。
  • 多平台覆盖:您可以指定不同的Python解释器或不同的平台,并在所有平台上并行运行测试。
  • 在远程运行测试之前,pytest有效地将您的程序源代码“rsyncs”到远程位置。报告所有测试结果并显示给您的本地终端。您可以指定不同的Python版本和解释器。

 

posted @ 2020-12-17 11:37  做一只热爱生活的小透明  阅读(99)  评论(0)    收藏  举报