pytest断言总结

pytest 中,可以使用多种方式进行断言,以验证测试用例的预期结果。以下是一些常见的断言方法:

1. 基本的断言

使用 Python 的内置 assert 语句进行断言。

python 复制代码
def test_example():
    assert 1 == 1

2. 断言相等

使用 pytest 提供的 pytest 对象进行更详细的断言。

python 复制代码
def test_equality():
    assert 1 == 1
    assert 1 != 2

3. 断言包含

检查一个对象是否包含另一个对象。

python 复制代码
def test_inclusion():
    assert 'hello' in 'hello world'
    assert 'goodbye' not in 'hello world'

4. 断言真假

检查表达式的真值。

python 复制代码
def test_truthiness():
    assert True
    assert not False

5. 断言异常

使用 pytest.raises 作为上下文管理器来断言代码块是否抛出异常。

python 复制代码
def test_exception():
    with pytest.raises(ZeroDivisionError):
        1 / 0

6. 断言警告

使用 pytest.warns 来断言代码块是否发出特定的警告。

python 复制代码
import warnings
def test_warning():
    with pytest.warns(UserWarning):
        warnings.warn("This is a warning", UserWarning)

7. 断言近似相等

对于浮点数,可以使用 pytest.approx 来断言两个数值近似相等。

python 复制代码
def test_approx():
    assert 2.2 == pytest.approx(2.3)
    assert 2.0 == pytest.approx(2.0)

8. 断言集合

检查集合是否相等。

python 复制代码
def test_set_equality():
    assert set([1, 2, 3]) == set([3, 2, 1])

9. 断言字典

检查字典是否相等。

python 复制代码
def test_dict_equality():
    assert {'a': 1, 'b': 2} == {'b': 2, 'a': 1}

10. 断言回调函数

使用 pytest 提供的 pytest_assertrepr_comparepytest.register_assert_rewrite 进行更复杂的断言。

python 复制代码
def test_callback():
    assert some_custom_condition(value)

11. 断言响应结构

对于更复杂的数据结构,可以使用 pytest 提供的 pytest 对象的内置方法,如 pytest.raisespytest.warns 等。

12. 断言字符串匹配

使用 pytestre 模块进行正则表达式匹配。

python 复制代码
import re
def test_regex_match():
    assert re.search(r"foo", "foobar")

13. 断言列表长度

验证列表或集合的长度是否符合预期。

python 复制代码
def test_list_length():
    assert len([1, 2, 3]) == 3

14. 断言多值

使用 pytest.mark.parametrize 进行参数化测试,并在每个参数组合中应用断言。

python 复制代码
@pytest.mark.parametrize("a,b,expected", [(1, 2, 3), (2, 3, 5)])
def test_addition(a, b, expected):
    assert a + b == expected

15. 断言调用

使用 pytestmock 对象来断言某个对象的方法是否被调用。

python 复制代码
from unittest.mock import Mock
def test_mock_call():
    mock_obj = Mock()
    mock_obj.some_method()
    mock_obj.some_method.assert_called_once()

16. 断言属性

检查对象的属性值。

python 复制代码
def test_attribute():
    class MyClass:
        def __init__(self):
            self.my_attr = 42
    obj = MyClass()
    assert obj.my_attr == 42

17. 断言文件内容

验证文件内容是否符合预期。

python 复制代码
def test_file_content():
    with open("test_file.txt", "r") as f:
        content = f.read()
    assert "expected content" in content

18. 断言异常消息

验证异常消息是否符合预期。

python 复制代码
def test_exception_message():
    try:
        1 / 0
    except ZeroDivisionError as e:
        assert str(e) == "division by zero"

19. 断言浮点数精度

使用 pytest.approx 并指定精度。

python 复制代码
def test_float_precision():
    assert 1.1 == pytest.approx(1.10001, abs=1e-5)

20. 断言迭代器

检查迭代器是否产生预期的元素。

python 复制代码
def test_iterator():
    assert list(iter([1, 2, 3])) == [1, 2, 3]

21. 断言多态性

验证对象是否是特定类型或是否实现了特定的接口。

python 复制代码
def test_type():
    assert isinstance(1, int)
相关推荐
寻道模式2 小时前
【运维心得】三步10分钟拆装笔记本键盘
运维·计算机外设·笔记本
元清加油2 小时前
【Golang】:函数和包
服务器·开发语言·网络·后端·网络协议·golang
5:002 小时前
pytest框架-详解
pytest
炫友呀3 小时前
Centos 更新/修改宝塔版本
linux·运维·centos
闻道且行之3 小时前
嵌入式|VNC实现开发板远程Debian桌面
运维·debian·嵌入式
向日葵.4 小时前
fastdds.ignore_local_endpoints 属性
服务器·网络·php
IT成长日记4 小时前
【自动化运维神器Ansible】Playbook中的when条件判断:精细化控制任务执行
运维·自动化·ansible·playbook·when·条件判断
昵称为空C6 小时前
SpringBoot接口限流的常用方案
服务器·spring boot
Peter_Deng.6 小时前
Linux 下基于 TCP 的 C 语言客户端/服务器通信详解(三个示例逐步进阶)
服务器·c语言·网络
杭州泽沃电子科技有限公司8 小时前
告别翻山越岭!智能监拍远程守护输电线路安全
运维·人工智能·科技·安全