12、pytest -- 缓存:记录执行的状态

本文介绍了pytest的缓存功能,包括插件的作用,如仅执行失败用例、按顺序执行用例等。详细解析了不同命令如何影响测试执行顺序,并通过实例展示了如何利用缓存数据操作测试流程。
摘要由CSDN通过智能技术生成

往期索引:https://www.cnblogs.com/luizyao/p/11771740.html

pytest会将本轮测试的执行状态写入到.pytest_cache文件夹,这个行为是由自带的cacheprovider插件来实现的;

注意:

pytest默认将测试执行的状态写入到根目录中的.pytest_cache文件夹,我们也可以通过在pytest.ini中配置cache_dir选项来自定义缓存的目录,它可以是相对路径,也可以是绝对路径;

相对路径指的是相对于pytest.ini文件所在的目录;例如,我们把这一章的缓存和源码放在一起:

src/chapter-12/pytest.ini中添加如下配置:

[pytest]
cache_dir = .pytest-cache

这样,即使我们在项目的根目录下执行src/chapter-12/中的用例,也只会在pytest-chinese-doc/src/chapter-12/.pytest_cache中生成缓存,而不再是pytest-chinese-doc/.pytest_cache中;

pytest-chinese-doc (5.1.3) 
λ pipenv run pytest src/chapter-12

1. cacheprovider插件

在介绍这个插件之前,我们先看一个简单例子:

# src/chapter-12/test_failed.py

import pytest


@pytest.mark.parametrize('num', [1, 2])
def test_failed(num):
    assert num == 1


# src\chapter-12\test_pass.py

def test_pass():
    assert 1

我们有两个简单的测试模块,首先我们来执行一下它们:

λ pipenv run pytest -q src/chapter-12/
.F.                                                                [100%] 
=============================== FAILURES ================================ 
____________________________ test_failed[2] _____________________________

num = 2

    @pytest.mark.parametrize('num', [1, 2])
    def test_failed(num):
>       assert num == 1
E       assert 2 == 1

src\chapter-12\test_failed.py:27: AssertionError
1 failed, 2 passed in 0.08s

可以看到一共收集到三个测试用例,其中有一个失败,另外两个成功的,并且两个执行成功的用例分属不同的测试模块;

同时,pytest也在src/chapter-12/的目录下生成缓存文件夹(.pytest_cache),具体的目录结构如下所示:

src
├───chapter-12
│   │   pytest.ini  # 配置了 cache_dir = .pytest-cache
│   │   test_failed.py
│   │   test_pass.py
│   │
│   └───.pytest-cache
│       │   .gitignore
│       │   CACHEDIR.TAG
│       │   README.md
│       │
│       └───v
│           └───cache
│                   lastfailed
│                   nodeids
│                   stepwise

现在,我们就结合上面的组织结构,具体介绍一下cacheprovider插件的功能;

1.1. --lf, --last-failed:只执行上一轮失败的用例

缓存中的lastfailed文件记录了上次失败的用例ID,我们可以通过一下--cache-show命令查看它的内容:

--cache-show命令也是cacheprovider提供的新功能,它不会导致任何用例的执行;

λ pipenv run pytest src/chapter-12/ -q --cache-show 'lastfailed'
cachedir: D:\Personal Files\Projects\pytest-chinese-doc\src\chapter-12\.pytest-cache
--------------------- cache values for 'lastfailed' --------------------- 
cache\lastfailed contains:
  {'test_failed.py::test_failed[2]': True}

no tests ran in 0.01s
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值