文档章节

Pytest03-pytest命令行参数

o
 osc_4ox4jhek
发布于 07/06 08:31
字数 3154
阅读 19
收藏 0

「深度学习福利」大神带你进阶工程师,立即查看>>>

3.pytest命令行参数

3.1 pytest控制台信息详解

    通常在运行pytest之后,会出现如下所示的控制台信息:

C:\Users\Surpass\Documents\PycharmProjects\PytestStudy\Lesson01>pytest test_01.py
==================test session starts =======================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\Users\Surpass\Documents\PycharmProjects\PytestStudy\Lesson01
collected 2 items

test_01.py .F                                    [100%]

===================FAILURES =================================
__________________ test_add_02 ______________________________

    def test_add_02():
>       assert Add(3,4)==6
E       assert 7 == 6
E        +  where 7 = Add(3, 4)

test_01.py:12: AssertionError
================ short test summary info ====================
FAILED test_01.py::test_add_02 - assert 7 == 6
=============== 1 failed, 1 passed in 0.56s ==================
  • ===== test session starts =====

测试会话分隔符,代表启动了一个新的调用

  • platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1

当前运行的平台,Python、pytest、pytest包的版本等信息

  • rootdir

当前起始目录,pytest搜索测试代码时使用的目录

  • collected 2 items

在搜索的目录中找到的测试函数个数

  • test_01.py .F

test_01.py代表测试文件

  • FAILED

未通过的测试函数的失败原因

  • 1 failed, 1 passed in 0.14s

统计测试函数通过和未通过的数量及运行时间

3.2 Pytest运行结果类型

    在Pytest中,测试函数可能会返回多种结果,不像传统的单元测试框架,仅显示通过和失败。以下是可能返回的结果:

  • PASSED(.)

测试通过。预期成功,实际成功

  • F(FAILED)

表示测试未通过,也可能是XPASS状态与strict选项造成的冲突。预期成功,实际失败

  • SKIPPED(s)

测试函数未执行,即该运行测试时跳过该测试函数,常用测试标记@pytest.mark.skip()@pytest.mark.skipif()指定跳过测试的条件

  • xfail(x)

期望测试失败,而且确实失败。常用测试标记@pytest.mark.xfail()来指定认为会失败的测试函数。预期失败,实际失败

  • XPASS(X)

期望测试失败,但实际结果却是运行通过,即不符合预期。预期失败,实际成功

  • ERROR(E)

运行测试函数时,出现异常或错误,可能由fixture引起

3.3 Pytest命令行参数

    很多时候,运行单元测试框架并不需要界面,更多的时候采用命令行的形式执行,pytest也提供很多的命令行参数,获取命令行参数帮助如下所示:

pytest --help


usage: pytest [options] [file_or_dir] [file_or_dir] [...]

positional arguments:
  file_or_dir
general:
 -x, --exitfirst       exit instantly on first error or failed test.

    下面来学习一些常用的命令行参数

3.3.1 --collect-only

    该参数仅收集测试函数,但并不执行运行操作。如下所示:

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest --collect-only
============================= test session starts ================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 3 items
<Module test_01.py>
  <Function test_add_01>
  <Function test_add_02>
<Module test_02.py>
  <Function test_requestBaidu>

3.3.2 -k Expression

    -k选项允许使用表达式来指定期望运行的测试函数。常用于筛选要进行运行的测试函数。在以下示例中,仅运行当前及其子目录中测试函数名含request或temp的测试函数,源代码如下所示:

  • test_01.py
import pytest

# First of sample function
def Add(x:int,y:int)->int:
    return x+y

# First of test function
def test_add_01():
    assert Add(2,3)==5

def test_add_02():
    assert Add(3,4)==6

def test_request_01():
    assert Add(4,3)==7

def test_temp_01():
    assert Add(8,3)==11
  • test_02.py
import requests

import  pytest

url = "http://www.baidu.com"
port = 80

def test_requestBaidu():
    testUrl=f"{url}:{port}"
    r=requests.get(url=testUrl,timeout=10)
    content=r.content.decode("utf8")
    print(content)
    assert "bai" in content
以下先验证筛选的结果是否正确:

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest -k "request or temp" --collect-only
============================== test session starts =======================================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 5 items / 2 deselected / 3 selected
<Module test_01.py>
  <Function test_request_01>
  <Function test_temp_01>
<Module test_02.py>
  <Function test_requestBaidu>
=========================== 2 deselected in 2.36s =================================

实际运行结果:

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest -k "request or temp" -v
======================== test session starts ======================================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1 -- d:\program files\python\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 5 items / 2 deselected / 3 selected
test_01.py::test_request_01 PASSED                                            [ 33%]
test_01.py::test_temp_01 PASSED                                               [ 66%]
test_02.py::test_requestBaidu PASSED                                          [100%]
====================== 3 passed, 2 deselected in 0.52s ==============================

3.3.3 -m MarkExpr

    该选项常用于标记测试并分组,方便快速运行选中的测试函数,具体的标记可以自定义,可以使用装饰器@pytest.mark。示例如下:

  • test_01.py
import pytest

# First of sample function
def Add(x:int,y:int)->int:
    return x+y

@pytest.mark.TestMark
# First of test function
def test_add_01():
    assert Add(2,3)==5

def test_add_02():
    assert Add(3,4)==6

@pytest.mark.RunThisTestFunc
def test_request_01():
    assert Add(4,3)==7

def test_temp_01():
    assert Add(8,3)==11
  • test_01.py
import requests
import  pytest

url = "http://www.baidu.com"
port = 80

@pytest.mark.RunThisTestFunc
def test_requestBaidu():
    testUrl=f"{url}:{port}"
    r=requests.get(url=testUrl,timeout=10)
    content=r.content.decode("utf8")
    print(content)
    assert "bai" in content

运行结果如下所示:

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest -m "RunThisTestFunc or not TestMark" --collect-only
=========================== test session starts ====================================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 5 items / 1 deselected / 4 selected
<Module test_01.py>
  <Function test_add_02>
  <Function test_request_01>
  <Function test_temp_01>
<Module test_02.py>
  <Function test_requestBaidu>  
C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest -m "RunThisTestFunc or not TestMark" -v
========================== test session starts =======================================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1 -- d:\program files\python\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 5 items / 1 deselected / 4 selected
test_01.py::test_add_02 FAILED                                                                   [ 25%]
test_01.py::test_request_01 PASSED                                                               [ 50%]
test_01.py::test_temp_01 PASSED                                                                  [ 75%]
test_02.py::test_requestBaidu PASSED                                                             [100%]

3.3.4 -x, --exitfirst

    正常情况下,pytest会运行每一个搜索到的测试函数,如果某个测试函数断言失败或触发了异常,则该测试函数的运行就停止了,此时pytest会将其标记为失败,然后继续运行后续的测试函数,这也是我们期望的运行模式。那如果我们希望在某一个测试函数在运行失败,则中断不再运行后续的测试函数,此时就可以使用-x选项。

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest -x
========================== test session starts =========================================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 6 items
test_01.py .F
=============================== FAILURES ==========================================
_____________________________________________________ test_add_02 _____________________________________________________
    def test_add_02():
>       assert Add(3,4)==6
E       assert 7 == 6
E        +  where 7 = Add(3, 4)
test_01.py:13: AssertionError
==================== 1 failed, 1 passed, 3 warnings in 0.32s =========================

从输出的信息可以看出,总共有6个测试函数,而在运行第2个测试函数,断言失败,则停止整个运行过程,因此,仅运行了2个测试函数,一个测试通过,一个测试失败。

3.3.5 --maxfail=num

    -x选项的特点是一遇到失败,就会直接全部停止。而如果想要pytest在失败n次后再停止,则可通过选项-maxfail指定允许失败的次数。

import pytest

# First of sample function
def Add(x:int,y:int)->int:
    return x+y

@pytest.mark.TestMark
# First of test function
def test_add_01():
    assert Add(2,3)==5

def test_add_02():
    assert Add(3,4)==6

@pytest.mark.RunThisTestFunc
def test_request_01():
    assert Add(4,3)==7

def test_temp_01():
    assert Add(8,3)==12

运行结果如下所示:

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest --maxfail=2
=============================== test session starts =====================================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 6 items
test_01.py .F.F
================================= FAILURES ==========================================
_________________________________ test_add_02 __________________________________________
    def test_add_02():
>       assert Add(3,4)==6
E       assert 7 == 6
E        +  where 7 = Add(3, 4)
test_01.py:13: AssertionError
________________________________ test_temp_01 _________________________________________
    def test_temp_01():
>       assert Add(8,3)==12
E       assert 11 == 12
E        +  where 11 = Add(8, 3)
test_01.py:20: AssertionError
====================== 2 failed, 2 passed, 3 warnings in 0.35s =========================

如果--maxfail=1,则功能与-x一样

3.3.6 --lf --last-failed

    当一个或多个测试函数运行失败后,我们常常希望能够定位到最后一个运行失败的测试函数,并且希望能重新运行,这时则可以使用--lf选项

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest --lf
============================== test session starts ====================================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 4 items / 2 deselected / 2 selected
run-last-failure: rerun previous 2 failures (skipped 3 files)
test_01.py FF                                                                                        [100%]

=================================== FAILURES ==========================================
____________________________ test_add_02 ________________________________________
    def test_add_02():
>       assert Add(3,4)==6
E       assert 7 == 6
E        +  where 7 = Add(3, 4)
test_01.py:13: AssertionError
_____________________________________test_temp_01 _________________________________________
    def test_temp_01():
>       assert Add(8,3)==12
E       assert 11 == 12
E        +  where 11 = Add(8, 3)
test_01.py:20: AssertionError
==================== 2 failed, 2 deselected, 2 warnings in 0.13s =============================

3.3.7 --ff --failed-first

    --ff选项与--lf选项功能基本相同,不同之处如下所示:

--ff 先运行上次失败的测试函数再运行完剩余的测试函数
--lf 仅运行上次失败的测试函数

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest --ff
=============================== test session starts =======================================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 6 items
run-last-failure: rerun previous 2 failures first
test_01.py FF..                                                                           [ 66%]
test_02.py .                                                                              [ 83%]
test_03.py .                                                                              [100%]
================================= FAILURES ======================================
______________________________________test_add_02 ____________________________________________
    def test_add_02():
>       assert Add(3,4)==6
E       assert 7 == 6
E        +  where 7 = Add(3, 4)
test_01.py:13: AssertionError
_______________________________________ test_temp_01 _________________________________________
    def test_temp_01():
>       assert Add(8,3)==12
E       assert 11 == 12
E        +  where 11 = Add(8, 3)
test_01.py:20: AssertionError
======================== 2 failed, 4 passed, 3 warnings in 1.88s ======================

3.3.8 -v --verbose

    使用-v/--verbose,常用于输出详细的运行信息。最主要的区别是每个文件中的每个测试函数都占用一行(之前是每一个文件占用一行),测试的结果和名字都会显示出来,而不再在是一个点或字符,如下所示:

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest --ff --tb=no -v
======================== test session starts =====================================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1 -- d:\program files\python\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 6 items
run-last-failure: rerun previous 2 failures first
test_01.py::test_add_02 FAILED                                                                [ 16%]
test_01.py::test_temp_01 FAILED                                                               [ 33%]
test_01.py::test_add_01 PASSED                                                                [ 50%]
test_01.py::test_request_01 PASSED                                                            [ 66%]
test_02.py::test_requestBaidu PASSED                                                          [ 83%]
test_03.py::test_request PASSED                                                               [100%]
====================== 2 failed, 4 passed, 3 warnings in 0.93s =============================

如果运行是彩色终端,则FAILED为红色字体,PASS为绿色字体。

3.3.9 -q --quiet

    该选项与-v功能相反,该选项会输出简化信息,只保留核心信息。如下所示:

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest --ff --tb=line -q
FF....                                                                                        [100%]
======================================== FAILURES ====================================
C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01\test_01.py:13: assert 7 == 6
C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01\test_01.py:20: assert 11 == 12
2 failed, 4 passed, 3 warnings in 1.34s

3.3.10 --tb=style

    --tb参数主要决定捕捉到失败后的输出信息的显示方式。其可选值为 auto/long/short/line/native/no,其常用模式解释如下:

  • auto模式:默认值,如果有多个测试函数失败,仅打印第一个和最后一个用例的回溯信息
  • long模式:输出的信息最详细
  • short模式:仅输出assert的一行及系统判定内容,不显示上下文
  • line模式:只使用一行输出显示所有的错误信息
  • native模式:只输出Python标准库的回溯信息,不显示额外信息
  • no模式:直接屏蔽全部回溯信息

    以上模式常用模式为:short/line/no

某个测试函数运行失败后,pytest会列举出失败信息,包括失败出现在哪一行,什么原因导致的失败,该过程称之为信息回溯

示例如下所示:

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest -v --tb=line
============================ test session starts ================================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1 -- d:\program files\python\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 6 items
test_01.py::test_add_01 PASSED                                                              [ 16%]
test_01.py::test_add_02 FAILED                                                              [ 33%]
test_01.py::test_request_01 PASSED                                                          [ 50%]
test_01.py::test_temp_01 FAILED                                                             [ 66%]
test_02.py::test_requestBaidu PASSED                                                        [ 83%]
test_03.py::test_request PASSED                                                             [100%]
==================================== FAILURES ==========================================
C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01\test_01.py:13: assert 7 == 6
C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01\test_01.py:20: assert 11 == 12
========================= 2 failed, 4 passed, 3 warnings in 2.10s ===========================

3.3.11 --durations=N

    --durations=N 该选项不关注测试具体的运行过程,只统计测试过程中哪向个阶段最慢,因此使用该选项可以加快测试分节奏,显示运行最慢的N个阶段,耗时越长越靠前,如果--durations=0,则将所有阶段的耗时从长到短排序后显示。示例如下所示:

C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01>pytest  --durations=3  --tb=line -v
============================test session starts ==========================================
platform win32 -- Python 3.7.6, pytest-5.4.2, py-1.8.1, pluggy-0.13.1 -- d:\program files\python\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01
collected 6 items
test_01.py::test_add_01 PASSED                                                              [ 16%]
test_01.py::test_add_02 FAILED                                                              [ 33%]
test_01.py::test_request_01 PASSED                                                          [ 50%]
test_01.py::test_temp_01 FAILED                                                             [ 66%]
test_02.py::test_requestBaidu PASSED                                                        [ 83%]
test_03.py::test_request PASSED                                                             [100%]
=============================== FAILURES =========================================
C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01\test_01.py:13: assert 7 == 6
C:\Users\Surpass\PycharmProjects\PytestStudy\Lesson01\test_01.py:20: assert 11 == 12
=============================== warnings summary ======================================
================================ slowest 3 test durations =================================
0.50s call     test_03.py::test_request
0.06s call     test_02.py::test_requestBaidu
(0.00 durations hidden.  Use -vv to show these durations.)
======================= 2 failed, 4 passed, 3 warnings in 0.93s ===========================

3.3.12 -h --help

    以上仅仅是常用的一些选项,更多选项可通过-h或--help来进行查看,通过该选项不但能展示原生pytest的用法,还能展示新添加插件的选项和用法。

原文地址:https://www.cnblogs.com/surpassme/p/13252310.html

本文同步在微信订阅号上发布,如各位小伙伴们喜欢我的文章,也可以关注我的微信订阅号:woaitest,或扫描下面的二维码添加关注:
MyQRCode.jpg

o
粉丝 0
博文 79
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。
5分钟 maven3 快速入门指南

前提条件 你首先需要了解如何在电脑上安装软件。如果你不知道如何做到这一点,请询问你办公室,学校里的人,或花钱找人来解释这个给你。 不建议给Maven的服务邮箱来发邮件寻求支持。 安装Mav...

fanl1982
2014/01/23
1.2W
7
开源渲染器--LuxRender

LuxRender 是一款物理真实的、无偏差的开源渲染器。 LuxRender渲染是根据渲染方程来模拟光的传输,生成物理真实的图像。但LuxRender 只是一款渲染程序而不是3D建模程序,它需要其它3D程序来创...

匿名
2013/03/03
1W
0
Base 参数解析库--bash argsparse

bash argsparse 是一个 Bash 的高级参数解析库。 Its purpose is to replace the option parsing and usage describing functions commonly rewritten in all scripts. Its features includ......

匿名
2013/03/27
381
0
Linux 多屏幕管理软件--XRandR

XRandR是X Rotate and Reflect Extension(改变大小与旋转扩充)的缩写,用来在命令行界面中对linux系统中的 X窗口系统的多屏幕做出一些设定的软件,能更改外接屏幕的大小、分辨率等...

匿名
2012/10/22
3.1K
0
Redis 分片实现--Redis Shard

redis-shard 是 Redis 分区的 Python API ,基于对 key 和 key tag 进行 CRC32 checksum 计算,可参考文章 http://antirez.com/post/redis-presharding.html . 该项目由知乎网开发。 使用限制...

匿名
2012/10/24
5.6K
0

没有更多内容

加载失败,请刷新页面

加载更多

处理“ java.lang.OutOfMemoryError:PermGen空间”错误

问题: Recently I ran into this error in my web application: 最近,我在Web应用程序中遇到此错误: java.lang.OutOfMemoryError: PermGen space java.lang.OutOfMemoryError:PermGen空间......

技术盛宴
43分钟前
7
0
从JS数组中删除重复的值[duplicate] - Remove duplicate values from JS array [duplicate]

问题: This question already has answers here : 这个问题已经在这里有了答案 : Get all unique values in a JavaScript array (remove duplicates) (79 answers) 获取JavaScript数组中的......

法国红酒甜
今天
11
0
如何使用AngularJS在浏览器的控制台中访问$ scope变量?

问题: I would like to access my $scope variable in Chrome's JavaScript console. 我想在Chrome的JavaScript控制台中访问$scope变量。 How do I do that? 我怎么做? I can neither see ......

fyin1314
今天
18
0
ImageMagick - 添加水印

背景 最近制作思维导图想添加自己的水印,网上很多例子都是使用ImageMagick来完成。但是不少代码在本地并不可行。经过一番试验,找到两个方法。 方法一 代码 stackoverflow方法改良: conver...

wffger
今天
11
0
OSChina 周四乱弹 —— 到底是怎样的饕餮盛宴在等待着我!

Osc乱弹歌单(2020)请戳(这里) 【今日歌曲】 小小编辑推荐 :《你 能 來 保 護 我 的 世 界 嘛》- 歪门 《你 能 來 保 護 我 的 世 界 嘛》- 歪门 手机党少年们想听歌,请使劲儿戳(这里)...

小小编辑
今天
79
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部