使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次

发布时间:2021-12-04 09:13:25 作者:柒染
来源:亿速云 阅读:298

这篇文章给大家介绍使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

背景

官方描述

官方解决办法(直接套用就行)

import jsonimport pytestfrom 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 jobreturn produce_expensive_data()# get the temp directory shared by all workersroot_tmp_dir = tmp_path_factory.getbasetemp().parent

    fn = root_tmp_dir / "data.json"with FileLock(str(fn) + ".lock"):if fn.is_file():
            data = json.loads(fn.read_text())else:
            data = produce_expensive_data()
            fn.write_text(json.dumps(data))return data

后续栗子的代码

项目结构
xdist+fixture(文件夹)
│  tmp(存放 allure 数据文件夹)
│  conftest.py
│  test_1.py
│  test_2.py
│  test_3.py
│ __init__.py │
test_1.py 代码
import osdef test_1(test):print("os 环境变量",os.environ['token'])print("test1 测试用例", test)
test_2.py 代码
import osdef test_2(test):print("os 环境变量",os.environ['token'])print("test2 测试用例", test)
test_3.py 代码
import osdef test_3(test):print("os 环境变量",os.environ['token'])print("test3 测试用例", test)

未解决情况下的栗子

conftest.py 代码
import osimport pytestfrom random import random


@pytest.fixture(scope="session")def test():
    token = str(random())print("fixture:请求登录接口,获取token", token)
    os.environ['token'] = tokenreturn token
运行命令
pytest -n 3 --alluredir=tmp
运行结果

使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次

使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次

使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次

scope=session 的 fixture 很明显执行了三次,三个进程下的三个测试用例得到的数据不一样,明显不会是我们想要的结果

使用官方解决方法的栗子rt 

#!/usr/bin/env python# -*- coding: utf-8 -*-"""__title__  = 
__Time__   = 2021/4/27 11:28
__Author__ = 小菠萝测试笔记
__Blog__   = https://www.cnblogs.com/poloyy/"""import jsonimport osimport pytestfrom random import randomfrom filelock import FileLock

@pytest.fixture(scope="session")def test(tmp_path_factory, worker_id):# 如果是单机运行 则运行这里的代码块【不可删除、修改】if worker_id == "master":"""【自定义代码块】
        这里就写你要本身应该要做的操作,比如:登录请求、新增数据、清空数据库历史数据等等"""token = str(random())print("fixture:请求登录接口,获取token", token)
        os.environ['token'] = token# 如果测试用例有需要,可以返回对应的数据,比如 tokenreturn token# 如果是分布式运行# 获取所有子节点共享的临时目录,无需修改【不可删除、修改】root_tmp_dir = tmp_path_factory.getbasetemp().parent# 【不可删除、修改】fn = root_tmp_dir / "data.json"# 【不可删除、修改】with FileLock(str(fn) + ".lock"):# 【不可删除、修改】if fn.is_file():# 缓存文件中读取数据,像登录操作的话就是 token 【不可删除、修改】token = json.loads(fn.read_text())print(f"读取缓存文件,token 是{token} ")else:"""【自定义代码块】
            跟上面 if 的代码块一样就行"""token = str(random())print("fixture:请求登录接口,获取token", token)# 【不可删除、修改】            fn.write_text(json.dumps(token))print(f"首次执行,token 是{token} ")# 最好将后续需要保留的数据存在某个地方,比如这里是 os 的环境变量os.environ['token'] = tokenreturn token
运行命令
pytest -n 3 --alluredir=tmp
运行结果

使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次

使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次

使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次

可以看到 fixture 只执行了一次,不同进程下的测试用例共享一个数据 token

重点

两个进程跑三个测试用例文件

还是上面栗子的代码

运行命令
pytest -n 2 --alluredir=tmp
运行结果

使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次

使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次

使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次

可以看到 test_3 的测试用例就没有读缓存文件了,每个进程只会读一次缓存文件,记住哦!

关于使用pytest-xdist分布式插件如何保证scope=session 的fixture在多进程运行情况下仍然能只运行一次就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. Fitnesse使用系列八
  2. test client怎么在Django中使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

fixture

上一篇:Windows 10更新修复了什么

下一篇:网页里段落的html标签是哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》