打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
pytest文档79 - 内置 fixtures 之 cache 写入和读取缓存数据

前言

pytest测试用例之间的参数如何传递?如在前置操作中生成了一个数据id,在测试用例需要引用,或者用例执行完成后需要在后置操作中删除。
还有很多同学经常问到的case1 生成了数据a,在case2 中引用这个值。这些在用例执行过程中生成的数据可以用cache缓存来解决。

内置cache fixture

cache 是一个可以在测试会话之间保持状态的缓存对象。

@pytest.fixture
def cache(request):
"""
Return a cache object that can persist state between testing sessions.
cache.get(key, default)
cache.set(key, value)
Keys must be a ``/`` separated value, where the first part is usually the
name of your plugin or application to avoid clashes with other cache users.
Values can be any object handled by the json stdlib module.
"""
return request.config.cache

cache是Cache类的一个实例对象

  • mkdir 创建一个文件夹

  • set(key: str, value: object)  设置一个cache值

  • get(key: str, default)   得到key对应的值

cache的使用场景

场景1:当前置操作生成一个id值,在用例中获取这个id

import pytest

@pytest.fixture()
def create_id(cache):
"""取值生成一个id"""
id = "yoyo_10086"
cache.set("id", id)
yield id

def test_1(cache, create_id):
# 方式1:cache获取
get_id = cache.get("id", None)
print("获取到的id: {}".format(get_id))
# 方式2:直接通过create_id 获取返回值
print("create_id fixture return: {}".format(create_id))

场景2:执行用例后生成一个sp_id,后置操作需要清理数据

import pytest

@pytest.fixture()
def delete_sp(cache):
"""后置处理"""
yield
# 先获取用例执行后得到的sp_id
sp_id = cache.get("sp_id", None)
print("后置处理得到值: {}".format(sp_id))

def test_2(cache, delete_sp):
# 执行用例后生成sp_id
sp_id = "yy_10086"
cache.set("sp_id", sp_id)

用例之间的数据关联

很多同学喜欢把用例当步骤去执行,执行a用例得到id参数,后面的用例需要前面得到的值,用cache也可以实现

import pytest

def test_1(cache):
x = "yoyo_123"
cache.set("id", x)
print("case 1 create id : {}".format(x))

def test_2(cache):
a = cache.get("id", None)
print("case2 get id: {}".format(a))

这种用例之间存在依赖的,必须要保证用例1在用例2前面先执行

.pytest_cache 缓存文件

在pycharm中右键执行,不会生成.pytest_cache 缓存文件。
使用 pytest 命令行执行,会在项目目录生成.pytest_cache 缓存文件

> pytest

v目录下的id文件就是cache设置的缓存文件,里面写的对应的value值


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
pytestx容器化执行引擎
超详细的 pytest 教程 (二) 之前后置方法和 fixture 机制
pytest---fixture中conftest.py文件
pytest系列(三) - fixture 的多样玩法
pytest文档17-fixture之autouse=True
Python 单元测试框架:Pytest
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服