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

时间:2022-07-24
本文章向大家介绍pytest文档51-内置fixture之cache使用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

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 == bdef test_02():
a = "hello"
b = "hello world"
assert a == bdef test_03():
a = "hello"
b = "hello world"
assert a in bdef 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 itemstest_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:softkecheng202004xuexi>pytest --cache-show
============================= test session starts =============================
cachedir: .pytest_cache
---------------------------- cache values for '*' -----------------------------
cachelastfailed contains:
{'test_x.py::test_02': True, 'test_x.py::test_04': True}
cachenodeids contains:
['test_x.py::test_01',
'test_x.py::test_02',
'test_x.py::test_03',
'test_x.py::test_04']
cachestepwise 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