pytest文档51-内置fixture之cache使用

2022-11-17,,,

前言

pytest 运行完用例之后会生成一个 .pytest_cache 的缓存文件夹,用于记录用例的ids和上一次失败的用例。

方便我们在运行用例的时候加上--lf 和 --ff 参数,快速运行上一次失败的用例。

--lf, --last-failed 只重新运行上次运行失败的用例(或如果没有失败的话会全部跑)

--ff, --failed-first 运行所有测试,但首先运行上次运行失败的测试(这可能会重新测试,从而导致重复的fixture setup/teardown)

--lf 和 --ff 相关介绍查看之前的这篇https://www.cnblogs.com/yoyoketang/p/9769559.html

cache

pytest -h 查看命令行参数,关于 cache 参数的使用方式

>pytest -h

--lf, --last-failed   rerun only the tests that failed at the last run (or
all if none failed)
--ff, --failed-first run all tests but run the last failures first. This
may re-order tests and thus lead to repeated fixture
--nf, --new-first run tests from new files first, then the rest of the
tests sorted by file mtime
--cache-show=[CACHESHOW]
show cache contents, don't perform collection or
tests. Optional argument: glob (default: '*').
--cache-clear remove all cache contents at start of test run.

参数说明:

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

--cache-show

测试案例代码test_x.py

# test_x.py
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/ 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

命令行输入 运行完成后,会有2个用例失败,2个用例成功

>pytest test_x.py --tb=no
============================= test session starts =============================
collected 4 items test_x.py .F.F [100%] ===================== 2 failed, 2 passed in 0.11 seconds ======================

运行完成后,会在当前的目录生成一个 .pytest_cache 的缓存文件夹,层级结构如下

lastfailed 文件记录上一次运行失败的用例

{
"test_x.py::test_02": true,
"test_x.py::test_04": true
}

nodeids 文件记录所有用例的节点

[
"test_x.py::test_01",
"test_x.py::test_02",
"test_x.py::test_03",
"test_x.py::test_04"
]

于是可以通过 pytest --cache-show 命令查看cache目录

D:\soft\kecheng202004\xuexi>pytest --cache-show
============================= test session starts =============================
cachedir: \.pytest_cache
---------------------------- cache values for '*' -----------------------------
cache\lastfailed contains:
{'test_x.py::test_02': True, 'test_x.py::test_04': True}
cache\nodeids contains:
['test_x.py::test_01',
'test_x.py::test_02',
'test_x.py::test_03',
'test_x.py::test_04']
cache\stepwise contains:
[] ======================== no tests ran in 0.02 seconds =========================

--cache-clear

--cache-clear 用于在测试用例开始之前清空cache的内容

pytest --cache-clear

查看pytest关于cache的更多文档 https://docs.pytest.org/en/latest/cache.html

pytest文档51-内置fixture之cache使用的相关教程结束。

《pytest文档51-内置fixture之cache使用.doc》

下载本文的Word格式文档,以方便收藏与打印。