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
"""
作者:上海-悠悠
python QQ交流群:730246532
联系微信/QQ: 283340479
"""

@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值

网易云完整视频课程《pytest+yaml 框架使用与开发》https://study.163.com/course/courseMain.htm?courseId=1213419817&share=2&shareId=480000002230338
报名咨询wx:283340479 (已报名的同学学习过程中有问题,都可以协助解决)

posted @ 2021-12-29 22:57  上海-悠悠  阅读(1190)  评论(0编辑  收藏  举报