Pytest系列 - config.cache 使用

865 篇文章 2 订阅
805 篇文章 0 订阅

2024软件测试面试刷题,这个小程序(永久刷题),靠它快速找到工作了!(刷题APP的天花板)_软件测试刷题小程序-CSDN博客文章浏览阅读3k次,点赞86次,收藏13次。你知不知道有这么一个软件测试面试的刷题小程序。里面包含了面试常问的软件测试基础题,web自动化测试、app自动化测试、接口测试、性能测试、自动化测试、安全测试及一些常问到的人力资源题目。最主要的是他还收集了像阿里、华为这样的大厂面试真题,还有互动交流板块……_软件测试刷题小程序https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5502基础介绍

官方地址:https://docs.pytest.org/en/8.0.x/reference/reference.html#config-cache

  • 在 pytest 中,cache 是一个非常有用的功能,它允许测试会话之间持久化状态

  • 这意味着可以在一次测试运行中存储一些值,并在后续的测试运行中访问这些值

如何使用 cache

cache 对象通过 pytest 的 FixtureRequest 对象提供,通常在一个 fixture 中获取并返回它

@fixture
def cache(request: FixtureRequest) -> Cache:
    """Return a cache object that can persist state between testing sessions.

    cache.get(key, default)
    cache.set(key, value)

    Keys must be ``/`` separated strings, 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.
    """
    assert request.config.cache is not None
    return request.config.cache

图片

  • pytest 的缓存机制是通过一个名为 .pytest_cache 的目录实现的,该目录位于项目的根目录下

  • config.cache 对象提供了一个简单的键值存储接口,允许测试代码读取和写入缓存数据

  • 一个 key 一个文件

存储和检索数据

cache 对象提供了两个主要方法:get 和 set

  • get(key, default=None) 方法用于检索之前存储的值。如果指定的 key 不存在,则返回 default 值。

  • set(key, value) 方法用于存储值。key 应该是一个字符串,而 value 可以是任何可以被 json 标准库模块处理的对象。

# 设置缓存值
config.cache.set("key", "value")

# 获取缓存值
value = config.cache.get("key", None)  # 如果键不存在,返回 None

键建议使用 / 分隔的字符串,其中第一部分通常是你的插件或应用程序的名称,以避免与其他使用 cache 的代码冲突

示例

假设有一个测试,需要从外部API获取数据,但这个操作很耗时,可以在第一次运行测试时从API获取数据,并将其存储在 cache 中。在后续的测试运行中,可以直接从 cache 中检索数据,避免重复的API调用

def test_external_api(cache):
    # 尝试从缓存中获取数据
    data = cache.get('external_api/data', default=None)
    if data is None:
        # 如果缓存中没有数据,则从API获取并存储到缓存中
        data = fetch_data_from_external_api()  # 假设这是一个函数来获取数据
        cache.set('external_api/data', data)
    
    # 使用数据进行测试
    assert data is not None

源码解析

pytest 的缓存机制是在 _pytest/cacheprovider.py 文件中实现的

def get(self, key: str, default):
    """Return the cached value for the given key.

    If no value was yet cached or the value cannot be read, the specified
    default is returned.

    :param key:
        Must be a ``/`` separated value. Usually the first
        name is the name of your plugin or your application.
    :param default:
        The value to return in case of a cache-miss or invalid cache value.
    """
    path = self._getvaluepath(key)
    try:
        with path.open("r") as f:
            return json.load(f)
    except (ValueError, OSError):
        return default

def set(self, key: str, value: object) -> None:
    """Save value for the given key.

    :param key:
        Must be a ``/`` separated value. Usually the first
        name is the name of your plugin or your application.
    :param value:
        Must be of any combination of basic python types,
        including nested types like lists of dictionaries.
    """
    path = self._getvaluepath(key)
    try:
        if path.parent.is_dir():
            cache_dir_exists_already = True
        else:
            cache_dir_exists_already = self._cachedir.exists()
            path.parent.mkdir(exist_ok=True, parents=True)
    except OSError:
        self.warn("could not create cache path {path}", path=path, _ispytest=True)
        return
    if not cache_dir_exists_already:
        self._ensure_supporting_files()
    data = json.dumps(value, indent=2)
    try:
        f = path.open("w")
    except OSError:
        self.warn("cache could not write path {path}", path=path, _ispytest=True)
    else:
        with f:
            f.write(data)
  • 代码还是比较简单的,key 就是一个文件路径,不存在则创建,然后写入数据

  • 这些方法最终会将数据序列化为 JSON 格式

行动吧,在路上总比一直观望的要好,未来的你肯定会感谢现在拼搏的自己!如果想学习提升找不到资料,没人答疑解惑时,请及时加入群: 759968159,里面有各种测试开发资料和技术可以一起交流哦。

最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】

软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

  • 29
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值