Pytest学习笔记(24)-使用 pytest-xdist 如何保证 scope=session 的 fixture 在多进程运行时仍然只运行一次

本文介绍了在使用pytest-xdist进行分布式测试时,如何处理scope=session的fixture确保只运行一次。通过官方介绍、未使用文件锁及使用文件锁的示例,展示了利用文件锁实现进程间通信,保证fixture的正确执行。测试报告显示,使用文件锁后,fixture在多进程下只会执行一次,提高了测试效率。
摘要由CSDN通过智能技术生成
背景
  • 使用 pytest-xdist 分布式插件可以加快运行,充分利用机器多核 CPU 的优势,也提高了资源利用率
  • 将常用功能放到 fixture,可以提高复用性和维护性
  • 做接口自动化测试的时候,通常我们会将登录接口放到 fixture 里面,并且 scope 会设置为 session,让他全局只运行一次
  • 但是当使用 pytest-xdist 的时候,scope=session 的 fixture 无法保证只运行一次,官方也通报了这一问题
官方介绍
  • pytest-xdist 的设计使每个工作进程将执行自己的测试集合并执行所有测试子集,这意味着在不同的测试过程中,要求高级范围的 fixture(如:session)将会被多次执行,这超出了预期,在某些情况下可能是不希望的
  • 尽管 pytest-xdist 没有内置支持来确保 scope=session 的fixture 仅执行一次,但是可以通过使用 文件锁 进行进程间通信来实现
官方解决办法
import json

import pytest
from filelock import FileLock


@pytest.fixture(scope="session")
def session_data(tmp_path_factory, worker_id):
    if worker_id == "master":
        # not executing in with multiple workers, just produce the data and let
        # pytest's fixture caching do its job
        return produce_expensive_data()

    # get the temp directory shared by all workers
    root_tmp_dir = tmp_path_factory.getbasetemp().parent

    fn = root_tmp_dir / "data.json"
    with FileLock(str(fn) + ".lock"):
        if fn.is_file():
            data = json
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要实现pytest+uiautomator2多进程多设备执行,可以按照以下步骤操作: 1. 安装pytest-xdist插件,可以使用pip install pytest-xdist命令进行安装。 2. 编写pytest.ini配置文件,指定pytest-xdist插件的参数,例如: ``` [pytest] addopts = -n 3 ``` 其中,-n参数指定了使用3个进程执行测试用例。 3. 编写conftest.py配置文件,使用pytest_addoption函数添加自定义参数,例如: ``` def pytest_addoption(parser): parser.addoption('--devices', action='store', default='device1,device2', help='设备列表') ``` 其中,--devices参数指定了要执行测试用例的设备列表。 4. 编写pytest fixture,使用pytest.fixture装饰器定义uiautomator2的设备对象,例如: ``` import pytest import uiautomator2 as u2 @pytest.fixture(scope='module', params=['device1', 'device2']) def device(request): device_name = request.param d = u2.connect(device_name) return d ``` 其中,params参数指定了要执行测试用例的设备列表,fixture名称为device,作用域为module,返回uiautomator2的设备对象。 5. 编写测试用例,使用fixture名称作为参数,例如: ``` def test_example(device): assert device.app_current()['package'] == 'com.android.settings' ``` 其中,device参数为fixture名称,表示传入uiautomator2的设备对象。 6. 执行测试,使用pytest命令执行测试用例,例如: ``` pytest -s -v --devices=device1,device2 ``` 其中,--devices参数指定了要执行测试用例的设备列表。 这样,就可以实现pytest+uiautomator2多进程多设备执行测试用例了。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值