Pytest断言:在测试过程中验证预期结果
    Pytest是一种流行的Python测试框架,它提供了一系列强大的功能,包括断言,以确保代码正确地执行。
    断言(Assertions)
    Pytest断言是一种用于验证程序结果是否符合预期的方法。它通过比较实际结果和预期结果来确定测试是否通过。
    如果实际结果和预期结果不相符,则Pytest将抛出一个断言错误,并详细说明失败的原因。
    语法
    Pytest断言使用Python内置的assert语句实现。语法如下:

    1. pythonCopy code
    2. assert expression, message
    3. # expression是要验证的表达式
    4. # message是可选的错误消息,当表达式为假时将被显示。

    Pytest断言的名称和说明:

    1. assert:这是Pytest中最基本的断言方法,它用于验证一个条件是否为真。如果条件为假,则会抛出AssertionError异常。
    2. assert almost_equal:用于比较两个浮点数是否相等,默认精度为7位小数。
    3. assert_raises:用于测试一个代码块是否引发指定的异常。
    4. assert_warns:用于测试一个代码块是否引发指定的警告。
    5. assert_logs:用于测试一个代码块是否记录了指定的日志。 ```python import pytest

    def test_assertion():

    1. # 测试assert断言
    2. a = 5
    3. b = 6
    4. assert a + 1 == b, "assertion error: a + 1 != b"
    5. # 测试assert_almost_equal断言
    6. c = 0.1 + 0.1 + 0.1
    7. assert pytest.approx(c) == 0.3, "assertion error: c != 0.3"
    8. # 测试assert_raises断言
    9. def divide_by_zero():
    10. 1 / 0
    11. with pytest.raises(ZeroDivisionError):
    12. divide_by_zero()
    13. # 测试assert_warns断言
    14. import warnings
    15. def raise_warning():
    16. warnings.warn("This is a warning.")
    17. with pytest.warns(UserWarning):
    18. raise_warning()
    19. # 测试assert_logs断言
    20. import logging
    21. def log_message():
    22. logging.warning("This is a log message.")
    23. with pytest.log

    ```