前言
- 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