pytest测试框架

本文详细介绍了 pytest 测试框架的使用,包括如何从 Python 代码调用 pytest、测试查找策略、跳过测试、参数化测试、fixture 的使用及其作用域、内置固件如 tmpdir 和 pytestconfig 的应用。通过实例解析了 monkeypatch 对系统进行动态修改的功能,以及 capsys 和 recwarn 用于捕获输出和警告。这些内容将帮助你深入理解和高效运用 pytest 进行测试工作。
摘要由CSDN通过智能技术生成

调用

在模块中运行测试

pytest test_mod.py

在目录中运行测试

pytest testing/

通过关键字表达式运行测试

pytest -k "MyClass and not method"

按节点 ID 运行测试

每个收集到的测试都被分配了一个唯一的nodeid,它由模块文件名后跟类名、函数名和参数化参数等说明::符组成,用字符分隔。

要在模块中运行特定测试:

pytest test_mod.py::test_func
pytest test_mod.py::TestClass::test_method

通过标记表达式运行测试

pytest -m slow

将运行所有用@pytest.mark.slow装饰器装饰的测试。

从 Python 代码调用 pytest
pytest.main()

pytest 使用 . 标识测试成功(PASSED)

Pytest 查找测试策略

默认情况下,pytest 会递归查找当前目录下所有以 test 开始或结尾的 Python 脚本,并执行文件内的所有以 test 开始或结束的函数和方法。

第一种:指定函数名

pytest 	/test_no_mark.py::test_func1

第二种:模糊匹配

pytest -k raise test_sample.py 

第三种,使用 pytest.mark 在函数上进行标记。

@pytest.mark.finished
def test_func1():
    assert 1 == 1

@pytest.mark.unfinished
def test_func2():
    assert 1 != 1
pytest -m finished test_sample.py 
跳过测试
@pytest.mark.skip()
def test_connect():
    pass
pytest 使用 s 表示测试被跳过(SKIPPED)。

Pytest 使用 pytest.mark.xfail 实现预见错误功能

@pytest.mark.xfail(gen.__version__ < '0.2.0',
                   reason='not supported until v0.2.0')
def test_api():
    id_1 = gen.unique_id()
    id_2 = gen.unique_id()
    assert id_1 != id_2

pytest 使用 x 表示预见的失败(XFAIL)。

创建第一个测试用例
def func(x):
    return x + 1


def test_answer():
    assert func(3) == 5

命令行输入pytest运行,[100%]指运行所有测试案例的全面进步。完成后, pytest 会显示失败报告,因为func(3)不返回5.

Python 测试发现的约定

pytestrootdir为每个测试运行确定一个,这取决于命令行参数(指定的测试文件、路径)和配置文件的存在

--rootdir=path命令行选项可以用来强制一个特定的目录。请注意,与其他命令行选项相反,--rootdir不能与addoptsinside一起使用, pytest.ini因为rootdir已经用于查找 pytest.ini

断言某个异常被引发
import pytest
def f():
    raise SyntaxError(1)


def test_raise():
    with pytest.raises(SyntaxError):
        f()	
        
def test_raises():
    with pytest.raises(TypeError) as e:
        connect('localhost', '6379')
    exec_msg = e.value.args[0]
    assert exec_msg == 'port type must be int'

以“安静”报告模式执行测试功能 pytest -q test_sample.py

可以使用 -v 选项,显示测试的详细信息。

使用 pytest -h 查看 pytest 的所有选项。

pytest 使用 F 标识测试失败(FAILED)。

在类中分组多个测试
class TestClass
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值