若分布式執行用例,用例設計必須遵循以下原則:
1.用例之間都是獨立的(不存在依賴關系);
2.用例執行無先后順序要求;
一、 pytest-xdist多進程
pytest-xdist僅支持多進程,不支持多線程。
安裝:pip install pytest-xdist
常用參數解析:
-n:進程數,也就是cpu個數。可以指定個數,最大值為當前機器cpu個數,也可以設置為auto,自動識別cpu個數。
如cmd命令行下執行:
pytest -s test_multiProcess.py -n=2 # 使用2個進程運行該py文件 pytest -s test_multiProcess.py -n=auto # 自動使用cpu個數運行該py文件
在PyCharm下執行:
# get_multithread.py import pytest from time import sleep def test_01(): sleep(2) # 通過延時,直觀比較運行耗時 print("testcase_01.") def test_02(): sleep(3) print("testcase_02.") def test_03(): sleep(4) print("testcase_03.") if __name__ == "__main__": # pytest.main(['-s', __file__]) # 默認使用單進程執行;耗時9.01s # pytest.main(['-s', '-n=auto', __file__]) # 自動使用所有進程執行,耗時4.59s pytest.main(['-s', '-n=3', __file__]) # 使用3個進程執行,耗時4.44s
二、pytest-parallel
pytest-parallel使用多線程后,則最后執行時間是運行時間最長的線程的時間。
(注意:pytest-parallel目前暫不能和allure報告使用)
安裝:
pip install pytest-parallel
常用參數解析:
–workers (optional) n:多進程運行, n是進程數。默認為1。
(注意:若為window平台,則該workers永遠=1,在linux和mac下可以取不同值。)
–tests-per-worker (optional) n:多線程運行, n是每個worker運行的最大並發線程數。默認為1(該參數不受運行平台限制)。
(如果兩個參數都配置了,就是進程並行,每個進程最多n個線程,總線程數:進程數 * 線程數)
在window下的cmd命令行執行:
pytest -s get_multithread.py --workers=2 --tests-per-worker=4 輸出: pytest-parallel: 1 worker (process), 3 tests per worker (threads) testcase_01. .testcase_02. .testcase_03 . ================================================== 3 passed in 4.02s ==================================================
在PyCharm下執行:
if __name__ == "__main__": pytest.main(['-s', '--workers=2', '--tests-per-worker=3', __file__]) # 設定2個進程,每個進程3個線程,耗時4.02s
遇到的問題:
pytest-parallel在windows下執行失敗及解決辦法AttributeError: Can‘t pickle local object ‘pytest_addoption.<locals?
解決方法:
將pytest-parallel版本回退到0.0.10,參考:https://blog.csdn.net/qq_39214101/article/details/107914869
cmd命令行下卸載package包:
pip uninstall packageName
cmd命令行下安裝特定版本的package包:
pip install packageName==version(如0.0.10)
附:
1、報錯:E: Unable to locate package XXX ?
(1)首先update再upgrade: sudo apt-get update sudo apt-get upgrade 然后再試試:sudo apt-get install xxxxx (2)若以上都不行則嘗試:sudo apt-get install aptitude 且成功以后使用:sudo aptitude install xxxxx
2、手動安裝package包:python setup.py install
3、手動安裝.whl包:pip3 install xxx.whl
4、pip install默認的安裝包路徑:xxx\Lib\site-packages