31-pytest-内置fixture之cache使用

简介: 31-pytest-内置fixture之cache使用

前言

  • pytest 运行完用例之后会生成一个 .pytest_cache 的缓存文件夹,用于记录用例的ids和上一次失败的用例。方便我们在运行用例的时候加上–lf 和 --ff 参数,快速运行上一次失败的用例。本篇来学习cache使用的使用

catch使用

参数说明

  • pytest -h 查看cache使用参数
  • –lf 也可以使用 --last-failed 仅运行上一次失败的用例
  • –ff 也可以使用 --failed-first 运行全部的用例,但是上一次失败的用例先运行
  • –nf 也可以使用 --new-first 根据文件插件的时间,新的测试用例会先运行
  • –cache-show=[CACHESHOW] 显示.pytest_cache文件内容,不会收集用例也不会测试用例,选项参数: glob (默认: ‘*’)
  • –cache-clear 测试之前先清空.pytest_cache文件

示例代码

# -*- coding: utf-8 -*-
# @Time    : 2022/3/26
# @Author  : 大海
import os
def test_01():
    a = "hello"
    b = "hello"
    assert a == b
def test_02():
    a = "hello"
    b = "hello world"
    assert a == b
def test_03():
    a = "hello"
    b = "hello world"
    assert a in b
def test_04():
    a = "hello"
    b = "hello world"
    assert a not in b
if __name__ == '__main__':
    os.system('pytest -s -v test_57.py --tb=line')
  • 运行后生成cache 文件
  • lastfailed 文件记录上一次运行失败的用例
    {
    “test_57.py::test_02”: true,
    “test_57.py::test_04”: true
    }
  • nodeids 文件记录所有用例的节点
    [
    “test_57.py::test_01”,
    “test_57.py::test_02”,
    “test_57.py::test_03”,
    “test_57.py::test_04”
    ]

cache-show

  • pytest --cache-show 查看cache

cache-clear

  • –cache-clear 用于在测试用例开始之前清空cache的内容
# -*- coding: utf-8 -*-
# @Time    : 2022/3/26
# @Author  : 大海
import os
def test_01():
    a = "hello"
    b = "hello"
    assert a == b
def test_02():
    a = "hello"
    b = "hello world"
    assert a == b
def test_03():
    a = "hello"
    b = "hello world"
    assert a in b
def test_04():
    a = "hello"
    b = "hello world"
    assert a not in b
if __name__ == '__main__':
  # --cache-clear 运行用例前清空之前catche
    os.system('pytest -s -v test_57.py --tb=line --cache-clear')

写入/读取cache

  • 前置处理
# -*- coding: utf-8 -*-
# @Time    : 2022/3/26
# @Author  : 大海
import os
import pytest
@pytest.fixture()
def get_token(cache):
    """获取token"""
    token = "token12345678"
    # 写入cache
    cache.set("token", token)
    yield token
# 两种方式获取cache中的token值
def test_1(cache,get_token):
    # 方式1: 通过cache获取
    token= cache.get("token", None)
    print("获取到的token: {}".format(token))
def test_2(get_token):
    # 方式2:直接 通过get_token 获取返回值
    print("get_token fixture return: {}".format(get_token))
if __name__ == '__main__':
    os.system('pytest -s -v test_58.py')

  • 后置处理
# -*- coding: utf-8 -*-
# @Time    : 2022/3/26
# @Author  : 大海
import os
import pytest
@pytest.fixture()
def delete_token(cache):
    """后置处理"""
    yield
    # 获取cache
    token = cache.get("token", None)
    print("后置处理得到值: {}".format(token))
    # token 置空
    cache.set("token", None)
def test_1(cache, delete_token):
    # 执行用例后生成token
    token = "token12345678"
    # 写入cache
    cache.set("token", token)
if __name__ == '__main__':
    os.system('pytest -s -v test_59.py')

解决写入中文cache问题

*写入中文cache

# -*- coding: utf-8 -*-
# @Time    : 2022/3/26
# @Author  : 大海
import os
import pytest
@pytest.fixture()
def get_token(cache):
    """获取token"""
    token = "测试小白"
    cache.set("token", token)
    yield token
def test_1(cache, get_token):
    # 方式1: 通过cache获取
    token = cache.get("token", None)
    print("获取到的token: {}".format(token))
if __name__ == '__main__':
    os.system('pytest -s -v test_60.py')

  • 解决中文显示:在项目根目录conftest.py中,添加如下代码
from _pytest.cacheprovider import Cache
import json
def new_set(self, key: str, value: object) -> None:
    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()
    # ensure_ascii 置为False
    data = json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True)
    try: 
        # 使用utf-8编码
        f = path.open("w", encoding='utf-8')
    except OSError:
        self.warn("cache could not write path {path}", path=path, _ispytest=True)
    else:
        with f:
            f.write(data)
Cache.set = new_set

解决读取中文cache问题

  • 中文正常写入后,读取会显示乱码,下面解决读取乱码的问题
  • 解决控制台显示乱码: 在项目根目录conftest.py中,添加如下代码
def new_get(self, key, default):
    path = self._getvaluepath(key)
    try: 
      # 设置 encoding='utf-8'
        with path.open("r", encoding='utf-8') as f:
            return json.load(f)
    except (ValueError, IOError, OSError):
        return default
Cache.get = new_get

相关文章
|
自然语言处理 JavaScript 前端开发
使用Pagefind为VitePress文档添加离线全文搜索能力
前言 VitePress 相信大家都或多或少听说过或者用过了 默认 UI相比 VuePress2.x 好看,启动速度也快(由Vite驱动,当然VuePress也可以切换构建引擎至Vite) 做内容定制也相对简单,笔者的很多静态文档站点(使用VuePress1.x),文章内容多的时候启动非常的慢,于是就从之前的 VuePress 迁移到了 VitePress,并做了一个博客主题 @sugarat/theme => 之前也有过介绍一个简约风的VitePress博客主题 但是 VitePress 官方目前还没有内置开箱即用的搜索能力(相关PR还在施工中)
1461 0
|
Java 调度 Spring
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
1710 0
|
6月前
|
运维 API 数据库
哪个IP查询工具更新更及时?实测对比:日更库 vs周更/月更库
IP归属地动态变化,周/月更库易过时,导致广告错投、风控失效。本文实测对比发现:日更商业库新IP段24小时内精准入库,而月更纯真库等严重滞后。附三大验证方法——跟踪新IP段、多工具交叉比对、WHOIS事实核查。(239字)
1213 1
|
6月前
|
自然语言处理 API 开发工具
阿里云自然语言处理全栈对接指南:从入门到企业级集成实战
阿里云自然语言处理依托通义千问大模型,支持100+语言,提供情感分析、NER、对话分析等全栈API;兼容Java/Python/Node.js/PHP/C++/Go多语言SDK,并集成百炼平台OpenAI兼容接口,助力企业快速构建智能客服、舆情分析等AI应用。(239字)
|
10月前
|
数据采集 自然语言处理 搜索推荐
电商行业有哪些agent应用:从 Quick Service 到 Dataphin 的智能革命
本文探讨Agent(智能体)如何驱动电商从“经验驱动”迈向“智能驱动”,聚焦Quick Service(全链路智能客服)、Quick BI“智能小Q”(对话式数据分析)、Data Agent(智能数据管家)与Dataphin(智能数据底座)四大技术实践,重塑运营、决策、履约与服务全链路。(239字)
电商行业有哪些agent应用:从 Quick Service 到 Dataphin 的智能革命
|
自然语言处理 数据采集 运维
高质量行业大模型数据集构建的实战路径
一文讲透高质量行业大模型数据集从预训练、指令微调到合成数据的全流程实战构建路径。
|
3月前
|
存储 数据采集 算法
数据架构到底是什么?一篇讲清数据库、数仓、数据湖和数据中台
企业系统林立导致数据孤岛丛生:系统连不通、口径不统一、历史难追溯。本文深入解析数据架构本质——不是技术选型,而是构建“产生→采集→存储→加工→服务→应用”的全链路数据体系,并厘清数据库(记准业务)、数仓(统一分析)、数据湖(存原始多样数据)、数据中台(复用数据能力)的定位与协同关系。(239字)
|
4月前
|
人工智能 数据可视化 Linux
桌面办公agent选型方法:个人办公如何选择一款好用的agent工具?
本文探讨如何理性选择办公AI Agent:核心在于“适配而非最优”。先明确需求——要“会说”(出主意)还是“会做”(自动执行任务);再匹配场景——个人高频琐事、长文档分析、流程固化、企业级协同或开源定制;最后真试真用,以实际任务效果为准。避坑关键:不混淆能力类型、不盲目追大厂、不忽视数据归属与系统兼容性。(239字)
338 0
|
6月前
|
安全 固态存储 Linux
Windows无法启动了怎么办?引导修复、UEFI与Legacy转换指南
电脑开机黑屏报英文错误?别慌!多为引导故障(如BOOTMGR丢失、BCD损坏或UEFI/Legacy模式不匹配)。本文详解启动原理,手把手教你用PE+DiskGenius一键修复引导、重建ESP/MBR,或无损转换启动模式,安全高效,小白也能操作。