如果你还想从头学起Pytest,可以看看这个系列的文章哦!
https://www.cnblogs.com/poloyy/category/1690628.html
pip3 install pytest-xdist -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
这是运行代码的包结构
14xdist是项目文件夹名称 │ conftest.py │ test_1.py │ __init__.py │ ├─test_51job │ │ conftest.py │ │ test_case1.py │ │ __init__.py │ ├─test_toutiao │ │ test_case2.py │ ├─test_weibo │ │ conftest.py │ │ test_case3.py │ │ __init__.py │
# 外层conftest.py @pytest.fixture(scope="session") def login(): print("====登录功能,返回账号,token===") name = "testyy" token = "npoi213bn4" yield name, token print("====退出登录!!!====")
import pytest @pytest.mark.parametrize("n", list(range(5))) def test_get_info(login, n): sleep(1) name, token = login print("***基础用例:获取用户个人信息***", n) print(f"用户名:{name}, token:{token}")
import pytest @pytest.fixture(scope="module") def open_51(login): name, token = login print(f"###用户 {name} 打开51job网站###")
from time import sleep import pytest @pytest.mark.parametrize("n", list(range(5))) def test_case2_01(open_51, n): sleep(1) print("51job,列出所有职位用例", n) @pytest.mark.parametrize("n", list(range(5))) def test_case2_02(open_51, n): sleep(1) print("51job,找出所有python岗位", n)
from time import sleep import pytest @pytest.mark.parametrize("n", list(range(5))) def test_no_fixture(login, n): sleep(1) print("==没有__init__测试用例,我进入头条了==", login)
import pytest @pytest.fixture(scope="function") def open_weibo(login): name, token = login print(f"&&& 用户 {name} 返回微博首页 &&&")
from time import sleep import pytest @pytest.mark.parametrize("n", list(range(5))) class TestWeibo: def test_case1_01(self, open_weibo, n): sleep(1) print("查看微博热搜", n) def test_case1_02(self, open_weibo, n): sleep(1) print("查看微博范冰冰", n)
pytest -s
可以看到,执行一条用例大概1s(因为每个用例都加了 sleep(1) ),一共30条用例,总共运行30s;那么如果有1000条用例,执行时间就真的是1000s
pytest -s -n auto
pytest -s -n 2
pytest -s -n auto --html=report.html --self-contained-html
pytest-xdist默认是无序执行的,可以通过 --dist 参数来控制顺序
--dist=loadscope
--dist=loadfile
按照同一个文件名来分组,然后将每个测试组发给可以执行的worker,确保同一个组的测试用例在同一个进程中执行
pytest-xdist是让每个worker进程执行属于自己的测试用例集下的所有测试用例
这意味着在不同进程中,不同的测试用例可能会调用同一个scope范围级别较高(例如session)的fixture,该fixture则会被执行多次,这不符合scope=session的预期
虽然pytest-xdist没有内置的支持来确保会话范围的夹具仅执行一次,但是可以通过使用锁定文件进行进程间通信来实现。
import pytest from filelock import FileLock @pytest.fixture(scope="session") def login(): print("====登录功能,返回账号,token===") with FileLock("session.lock"): name = "testyy" token = "npoi213bn4" # web ui自动化 # 声明一个driver,再返回 # 接口自动化 # 发起一个登录请求,将token返回都可以这样写 yield name, token print("====退出登录!!!====")
Pytest系列(16)- 分布式测试插件之pytest-xdist的详细使用
原文:https://www.cnblogs.com/poloyy/p/12694861.html