百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

pytest框架进阶自学系列 | 运行的失败管理

haoteby 2025-05-09 18:44 57 浏览

书籍来源:房荔枝 梁丽丽《pytest框架与自动化测试应用》

一边学习一边整理老师的课程内容及实验笔记,并与大家分享,侵权即删,谢谢支持!

附上汇总贴:pytest框架进阶自学系列 | 汇总_热爱编程的通信人的博客-CSDN博客


最多允许失败的测试用例数

当达到最大上限时,退出执行。如未配置,则没有上限。

命令pytest -x遇到第一个失败时,退出执行。

PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-2> pytest -x
========================================================================================================= test session starts =========================================================================================================
platform win32 -- Python 3.7.7, pytest-5.4.1, py-1.11.0, pluggy-0.13.1
rootdir: D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-2, inifile: pytest.ini
plugins: allure-pytest-2.13.2
collected 32 items                                                                                                                                                                                                                     

test_assert_1.py F

============================================================================================================== FAILURES =============================================================================================================== 
______________________________________________________________________________________________________ test_long_str_comparison _______________________________________________________________________________________________________ 

    def test_long_str_comparison():
        str3 = 'abcdef'
        str4 = 'adcdef'
>       assert str3 == str4
E       AssertionError: assert 'abcdef' == 'adcdef'
E         - adcdef
E         ?  ^
E         + abcdef
E         ?  ^

test_assert_1.py:4: AssertionError
========================================================================================================== warnings summary =========================================================================================================== 
c:\users\guoliang\appdata\local\programs\python\python37\lib\site-packages\_pytest\terminal.py:289
  c:\users\guoliang\appdata\local\programs\python\python37\lib\site-packages\_pytest\terminal.py:289: PytestDeprecationWarning: TerminalReporter.writer attribute is deprecated, use TerminalReporter._tw instead at your own risk.     
  See https://docs.pytest.org/en/latest/deprecations.html#terminalreporter-writer for more information.
    "TerminalReporter.writer attribute is deprecated, use TerminalReporter._tw instead at your own risk.\n"

-- Docs: https://docs.pytest.org/en/latest/warnings.html
======================================================================================================= short test summary info ======================================================================================================= 
FAILED test_assert_1.py::test_long_str_comparison - AssertionError: assert 'abcdef' == 'adcdef'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
==================================================================================================== 1 failed, 1 warning in 10.42s ==================================================================================================== 
PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-2> 

命令pytest --maxfail=2遇到第2个失败时,退出执行。同理,命令pytest --maxfail=3遇到第3个失败时退出执行。

执行结果如下:

PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-2> pytest -x
========================================================================================================= test session starts =========================================================================================================
platform win32 -- Python 3.7.7, pytest-5.4.1, py-1.11.0, pluggy-0.13.1
rootdir: D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-2, inifile: pytest.ini
plugins: allure-pytest-2.13.2
collected 32 items                                                                                                                                                                                                                     

test_assert_1.py F

============================================================================================================== FAILURES =============================================================================================================== 
______________________________________________________________________________________________________ test_long_str_comparison _______________________________________________________________________________________________________ 

    def test_long_str_comparison():
        str3 = 'abcdef'
        str4 = 'adcdef'
>       assert str3 == str4
E       AssertionError: assert 'abcdef' == 'adcdef'
E         - adcdef
E         ?  ^
E         + abcdef
E         ?  ^

test_assert_1.py:4: AssertionError
========================================================================================================== warnings summary =========================================================================================================== 
c:\users\guoliang\appdata\local\programs\python\python37\lib\site-packages\_pytest\terminal.py:289
  c:\users\guoliang\appdata\local\programs\python\python37\lib\site-packages\_pytest\terminal.py:289: PytestDeprecationWarning: TerminalReporter.writer attribute is deprecated, use TerminalReporter._tw instead at your own risk.     
  See https://docs.pytest.org/en/latest/deprecations.html#terminalreporter-writer for more information.
    "TerminalReporter.writer attribute is deprecated, use TerminalReporter._tw instead at your own risk.\n"

-- Docs: https://docs.pytest.org/en/latest/warnings.html
======================================================================================================= short test summary info ======================================================================================================= 
FAILED test_assert_1.py::test_long_str_comparison - AssertionError: assert 'abcdef' == 'adcdef'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
==================================================================================================== 1 failed, 1 warning in 10.42s ==================================================================================================== 
PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-2> 

失败运行管理的原理

用例运行失败后,通常希望再次执行失败的用例,看是环境问题还是脚本问题,因此测试方法运行失败需被记录。

这部分内容与第12章缓存目录设置配置内容相一致。cacheprovider插件将执行状态写入缓存文件夹,pytest会将本轮测试的执行状态写入.pytest_cache文件夹,这个行为是由自带的cacheprovider插件实现的。

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

例如,我们想把第12章执行的状态的缓存和源码放在一起,该如何实现呢?实现步骤如下。

在src/chapter12/pytest.ini中添加如下配置:

[pytest]
cache_dir = .pytest-cache

这样,即使在项目的根目录下执行src/chapter12/中的用例,也只会在
pytest_book/src/chapter12/.pytest_cache中生成缓存,而不是pytest_book/.pytest_cache中。

(1)在chapter12中复制chapter-2中的test_assert_2.py并改名为test_assert_12.py,需要将内容进行适当修改。

(2)在src路径下执行pytest src/chapter12。

(3)执行状态未写在根目录下,而是写在测试文件所在的目录中(.pytest_cache)。

执行结果如图所示。

cacheprovider插件实现失败管理的准备:

(1)在chapter12下创建pytest.ini文件,代码如下:

[pytest]
cache_dir = .pytest-cache

(2)在chapter12下创建test_failed.py文件,代码如下:

import pytest

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

(3)在chapter12下创建test_pass.py文件,代码如下:

def test_pass():
    assert 1

(4)如果大家是从前到后进行实践,则需要删除test_assert_12.py和.pytest_cache。

(5)再在根目录下执行pytest src/chapter12。

(6)chapter12下会自动创建缓存文件夹及文件.pytest_cache。

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

执行结果如下:

PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> pytest .\chapter-12\
========================================================================================================= test session starts =========================================================================================================
platform win32 -- Python 3.7.7, pytest-5.4.1, py-1.11.0, pluggy-0.13.1
cachedir: .pytest-cache
rootdir: D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-12, inifile: pytest.ini
plugins: allure-pytest-2.13.2
collected 3 items                                                                                                                                                                                                                      

chapter-12\test_failed.py .F                                                                                                                                                                                                     [ 66%]
chapter-12\test_pass.py .                                                                                                                                                                                                        [100%] 

============================================================================================================== FAILURES =============================================================================================================== 
___________________________________________________________________________________________________________ test_failed[2] ____________________________________________________________________________________________________________ 

num = 2

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

chapter-12\test_failed.py:5: AssertionError
======================================================================================================= short test summary info =======================================================================================================
FAILED chapter-12\test_failed.py::test_failed[2] - assert 2 == 1
===================================================================================================== 1 failed, 2 passed in 0.30s ===================================================================================================== 
PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> 

同时,pytest也在src/chapter12/目录下生成缓存文件夹(.pytest_cache)。

具体介绍一下cacheprovider插件的功能。

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

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

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

执行结果如下:

PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> pytest .\chapter-12\ -q --cache-show 'lastfailed'
cachedir: D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-12\.pytest-cache
---------------------------------------------------------------------------------------------------- cache values for 'lastfailed' ---------------------------------------------------------------------------------------------------- 
cache\lastfailed contains:
  {'test_failed.py::test_failed[2]': True}

no tests ran in 0.00s
PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> 

可以看到,它记录了一个用例,此用例为上次失败的测试用例的ID:test_failed.py::test_failed[2]。

下次执行,当使用--lf选项时,pytest在收集阶段只会选择这个失败的用例,而忽略其他的用例。命令pytest --lf --collect-only src/chapter12/中的collect-only选项只收集用例而不执行。

执行结果如下:

PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> pytest --lf --collect-only .\chapter-12\
========================================================================================================= test session starts =========================================================================================================
platform win32 -- Python 3.7.7, pytest-5.4.1, py-1.11.0, pluggy-0.13.1
cachedir: .pytest-cache
rootdir: D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-12, inifile: pytest.ini
plugins: allure-pytest-2.13.2
collected 1 item                                                                                                                                                                                                                        
<Module test_failed.py>
  <Function test_failed[2]>
run-last-failure: rerun previous 1 failure (skipped 1 file)

======================================================================================================== no tests ran in 0.02s ========================================================================================================
PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> 

仔细观察一下上面的回显,collecting...<Module test_failed.py>只收集到test_fail.py文件中<Function test_failed[2]>,表示第二个执行用例失败了,需要重新执行(跳过5个文件)。1deselected(没有选择),此处的“没有选择”是<Module test_failed.py>中执行通过的第一个用例。跳过5个文件包括pytest.ini和test_pass.py在内的5个文件。

实际上,--lf复写了用例收集阶段的两个钩子方法:pytest_ignore_collect(path,config)和
pytest_collection_modifyitems(session,config,items)。

--ff,--failed-first:先执行上一轮失败的用例,再执行其他的用例。

先通过实践看一看这个命令的效果,再去分析它的实现,命令如下:

执行结果如下:

PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> pytest --collect-only -s --ff .\chapter-12\
========================================================================================================= test session starts =========================================================================================================
platform win32 -- Python 3.7.7, pytest-5.4.1, py-1.11.0, pluggy-0.13.1
cachedir: .pytest-cache
rootdir: D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-12, inifile: pytest.ini
plugins: allure-pytest-2.13.2
collected 3 items                                                                                                                                                                                                                       
<Module test_failed.py>
  <Function test_failed[2]>
  <Function test_failed[1]>
<Module test_pass.py>
  <Function test_pass>
run-last-failure: rerun previous 1 failure first

======================================================================================================== no tests ran in 0.02s ======================================================================================================== 
PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> 

可以看到一共收集到3个测试用例,和正常所收集到的测试用例的顺序相比,上一轮失败的test_failed.py::test_failed[2]用例在最前面,将优先执行。

实际上,-ff只复写了钩子方法:
pytest_collection_modifyitems(session,config,items),它可以过滤或者重新排序所收集到的用例。

--nf,--new-first:先执行新加的或修改的用例,再执行其他的用例。

缓存中的nodeids文件记录了上一轮执行的所有用例,命令如下:

执行结果如下:

PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> pytest .\chapter-12\ --cache-show 'nodeids'
========================================================================================================= test session starts =========================================================================================================
platform win32 -- Python 3.7.7, pytest-5.4.1, py-1.11.0, pluggy-0.13.1
cachedir: .pytest-cache
rootdir: D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-12, inifile: pytest.ini
plugins: allure-pytest-2.13.2
cachedir: D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-12\.pytest-cache
----------------------------------------------------------------------------------------------------- cache values for 'nodeids' ------------------------------------------------------------------------------------------------------ 
cache\nodeids contains:
  ['test_failed.py::test_failed[1]',
   'test_failed.py::test_failed[2]',
   'test_pass.py::test_pass']

======================================================================================================== no tests ran in 0.01s ======================================================================================================== 
PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> 

从执行结果可以看到上一轮共执行了3个测试用例。

现在可以在test_pass.py中新加一个用例,并修改一下test_failed.py文件中的用例(但是不添加新用例)。

代码如下:

def test_pass():
    assert 1
    
def test_new_pass():
    assert 1

再来执行一下收集命令,命令如下:

执行结果如下:

PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> pytest --collect-only -s --nf .\chapter-12\
========================================================================================================= test session starts =========================================================================================================
platform win32 -- Python 3.7.7, pytest-5.4.1, py-1.11.0, pluggy-0.13.1
cachedir: .pytest-cache
rootdir: D:\SynologyDrive\CodeLearning\WIN\pytest-book\src\chapter-12, inifile: pytest.ini
plugins: allure-pytest-2.13.2
collected 4 items                                                                                                                                                                                                                      
<Module test_pass.py>
  <Function test_new_pass>
  <Function test_pass>
<Module test_failed.py>
  <Function test_failed[1]>
  <Function test_failed[2]>

======================================================================================================== no tests ran in 0.48s ======================================================================================================== 
PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> 

可以看到,新加的用例排在最前面,其次修改过的测试用例紧接其后,最后才是旧的用例,这个行为在源码中有所体现。

--cache-clear:先清除所有缓存,再执行用例。

如果上一轮没有失败的用例,则需要先清除缓存,再执行test_pass.py模块(它的用例都是能测试成功的)。

执行及结果如下:

======================================================================================================== no tests ran in 0.48s ======================================================================================================== 
PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> pytest --cache-clear -q -s .\chapter-12\test_pass.py
..
2 passed in 0.01s
PS D:\SynologyDrive\CodeLearning\WIN\pytest-book\src> 

其结果是不是少了点什么呢?对!因为没有失败的用例,所以不会生成lastfailed文件,那么这个时候再使用--lf和--ff会发生什么呢?我们来试试。

注意:如果我们观察得足够仔细,就会发现现在的缓存目录和之前相比不仅少了lastfailed文件,还少了CACHEDIR.TAG、.gitignore和README.md这3个文件。这是一个Bug,现在pytest的版本是5.2.1,预计会在之后的版本得到修复。

相关推荐

二次面试终拿到offer,百度Android面试真题解析我整理出来了

找工作的大潮来临了,这边给大家分享一下面试会遇到的问题。Android开发了5年,之前一直都是在小公司码着代码,对大厂一直有着憧憬,我是在去年年初的时候通过朋友的内推面试了百度,结果被怼的没话说,那叫...

Android 开发中文引导-应用小部件

应用小部件是可以嵌入其它应用(例如主屏幕)并收到定期更新的微型应用视图。这些视图在用户界面中被叫做小部件,并可以用应用小部件提供者发布。可以容纳其他应用部件的应用组件叫做应用部件的宿主(1)。下面的截...

Win10桌面/手机版最深层次开发功能挖掘

IT之家讯Win10开发者预览版为我们提供了一个Win10大框架的早期概览,使开发者与热心用户都可以提前感受Win10带来的新特性,尝试新工具,而作为开发者,最关心的莫过于Windows多平台通用应...

Android TabLayout + ViewPager2使用

1、xml文件<!--明细列表--><com.google.android.material.tabs.TabLayoutandroid:id="@+id/ty_...

android培训学习的大纲_android软件开发培训

第一阶段android基础:1.基础javaJava概述,进制,数据类型,常量变量,运算符,表达式关系运算符,逻辑运算符,if语句,switch语句while循环,do...while循环,for循环...

背了几十份面经还是连挂6个面试,最终拿下腾讯后总结了这些坑点

刚开始面试的时候我真的是处处碰壁,面一家挂一家,面完之后怀疑自我,是不是自己真的太菜了找不到工作。工作本身就是双向选择,一家不行再换一家,总有合适的,千万不要因为别人的一句话就全盘否定自己,一定要自信...

webview 渲染机制:硬件加速方式渲染的Android Web

webview渲染是什么?webview渲染是用于展现web页面的控件;webview可以内嵌在移动端,实现前端的混合式开发,大多数混合式开发框架都是基于webview模式进行二次开发的...

ExpandListView 的一种巧妙写法_仿写丁香结的写法写一种花梅花

ExpandListView大家估计也用的不少了,一般有需要展开的需求的时候,大家不约而同的都想到了它然后以前自己留过记录的一般都会找找以前自己的代码,没有记录习惯的就会百度、谷歌,这里吐槽一下,好几...

Android监听滚动视图_滚动监听代码

AndroidUILibs之Android-ObservableScrollView1.说明Android-ObservableScrollView,顾名思义,Android上观察滚动的视图,可...

Flutter 之 ListView_flutter开发

在Flutter中,ListView可以沿一个方向(垂直或水平方向)来排列其所有子Widget,常被用于需要展示一组连续视图元素的场景ListView构造方法ListView:仅适用于列表中...

Android之自定义ListView(一)_android 自定义listview

PS:自定义View是Android中高手进阶的路线.因此我也打算一步一步的学习.看了鸿洋和郭霖这两位大牛的博客,决定一步一步的学习,循序渐进.学习内容:1.自定义View实现ListView的Ite...

ListView 使用详解_listview在哪里

阅读五分钟,每日十点,和您一起终身学习,这里是程序员Android本篇文章主要介绍Android开发中的部分知识点,通过阅读本篇文章,您将收获以下内容:ListView主要使用方法使用androi...

穿裙子的李宇春,需要向谁解释吗?

...

明星们“不想占用”的公共资源,到底是个啥?

近日,社交媒体上可谓“一瓜未平一瓜又起”,明星们隔三差五地在热搜上道歉、澄清,好不热闹。道歉原因千万种,道歉话术却雷同——通常都以“无意占用公共资源”开头,不管是澄清、官宣,还是回应、声明,都会带上这...

选择女人的模板,模板不同,生活方式不同

文/高阳人生在世,选择伴侣成了头等大事。尤其是对于男人来说,“选择女人的模板”直接决定了你未来几十年的生活方式,有时简直像组装拼图,每一块都有代价。莫言曾说过:“你选择能干的女人,就得接受她的强势;你...