pytest入门

本文介绍了pytest的官网、安装方法和测试用例规则。通过`pytest --help`查看帮助文档,测试文件命名需以test_开头或_test结尾。文章还详细阐述了pytest的命令行参数,如`-v`用于增加详细信息,`-k`和`-m`用于选择特定测试用例,以及`-x`、`--maxfail`等用于控制测试执行流程。同时,还讨论了错误回溯和捕获输出的选项。
摘要由CSDN通过智能技术生成

pytest官网

参考:link

pytest安装

pip install pytest

pytest案例规则

pytest --help 可以查看pytest的帮助文档

C:\Users\Administrator>pytest --help
usage: pytest [options] [file_or_dir] [file_or_dir] […]
运行pytest时可以指定目录和文件,如果不指定,pytest会搜索配置文件testpaths 定义的目录或者当前目录及其子目录中以test_开头或以_test结尾的py文件
[file_or_dir]可以指定文件或者目录

我们把pytest搜索测试文件和测试用例的过程称为测试搜索(test discovery),只要遵守pytest的命名规则,pytest就能自动搜索所有待执行的测试用例,规则如下:
(1)测试文件应当命名为test_.py或者test.py,一定要以test_开头或者结尾,下划线不能省略
(2) 测试函数、测试类方法应当命名为test

(3)测试类应当命名为Test,并且不能有__init__方法

如何运行pytest—pytest命令行参数

-v : --verbose increase verbosity 显示详细信息
使用这个参数,就可以详细展示出每个测试用例的运行结果

collected 2 items                                                                                                                                                                                                         

test_simpleexample.py::test_inc PASSED                                                                                                                                                                              [ 50%]
test_simpleexample.py::test_inc2 FAILED    

–collect-only : 展示哪些用例会被运行,只展示案例不运行

collected 2 items                                                                                                                                                                                                         
<Package pytestlearn>
  <Module test_simpleexample.py>
    <Function test_inc>
    <Function test_inc2>

-k: 使用表达式指定需要运行的案例 ,可以使用 or and等
比如:两条测试用例的名字时test_asdict()和test_defaults(),使用–k这参数时

pytest -k "asdict or defaults"

-m: 指定标记来运行
测试用例可以使用pytest.mark.mock或者pytest.mark,regression这样的装饰器来标记分组测试用例,使用参数-m就可以选择标记来运行
如,需要运行标记为冒烟阶段的测试用例 pytest -m “mock”
-m后面跟一个字符串,字符串可以使用and or not等
如下是一个简单的测试用例,使用pytest.mark.mock和pytest.mark.regression来标记哪些是冒烟测试用例,哪些是regression的测试用例

import pytest

def inc(x):
    return x+1

def test_inc():
    assert inc(5)==6

def test_inc2():
    assert inc(3)==7

@pytest.mark.mock
def test_mock_01():
    assert inc(1)==2

@pytest.mark.mock
def test_mock_02():
    assert inc(3)==4

@pytest.mark.regression
def test_regression_01():
    assert inc(3)==4
  1. 如果想要只运行冒烟测试用例
sh-3.2$ pytest -m "mock"
========================================================
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值