常用的pytest的assert断言操作(个人笔记)
pytest 提供了一系列常用的断言函数,用于在测试中进行各种断言操作。以下是一些常用的 pytest 断言操作的示例:
-
相等性断言:
assert result == expected
-
不相等性断言:
assert result != unexpected
-
包含性断言:
assert item in collection
-
不包含性断言:
assert item not in collection
-
真值断言:
assert condition
-
假值断言:
assert not condition
-
异常断言:
with pytest.raises(ExpectedException): # 执行可能引发异常的代码
-
比较断言:
assert x > y assert x < y assert x >= y assert x <= y
-
类型断言:
assert isinstance(obj, expected_type)
-
属性断言:
assert hasattr(obj, 'attribute') assert not hasattr(obj, 'attribute')
这些是一些常见的 pytest 断言操作,您可以根据具体的测试需求选择适当的断言函数进行使用。断言操作可以帮助您验证测试的预期结果,确保代码的正确性和可靠性。
除了上面提到的常用断言操作外,还有一些其他功能和技巧可以在 pytest 中使用:
-
自定义断言函数:您可以编写自己的自定义断言函数,以便在测试中重复使用。这样可以提高测试代码的可重用性和可维护性。
def assert_custom(condition, message=None): assert condition, message or '自定义断言失败' def test_custom_assert(): assert_custom(2 + 2 == 4)
-
断言消息:在断言语句中添加可选的消息参数,以便在断言失败时提供更详细的错误信息。
assert result == expected, '结果与预期不符'
-
多重断言:使用 pytest 提供的
pytest.assume()
函数可以在一个测试用例中进行多个断言,即使前面的断言失败,也会继续执行后面的断言。def test_multiple_assertions(): pytest.assume(2 + 2 == 4) pytest.assume(3 * 3 == 9) pytest.assume('hello'.startswith('h'))
-
参数化测试断言:结合 pytest 的参数化功能,可以在单个测试函数中执行多组输入和预期输出的断言。
import pytest @pytest.mark.parametrize('input, expected', [ (2 + 2, 4), (3 * 3, 9), ('hello', 'hello') ]) def test_parameterized_assertions(input, expected): assert input == expected
这些技巧和功能可以帮助您更灵活和高效地编写测试用例,并提供更丰富的断言操作和错误信息。根据具体的测试需求,您可以选择适当的断言方式和技巧来优化您的测试代码。
还有一些其他的 pytest 断言功能和技巧可以提升您的测试效率和代码质量:
-
近似断言:使用
pytest.approx()
函数进行浮点数的近似比较。def test_float_approx(): assert pytest.approx(0.1 + 0.2) == 0.3
-
自定义断言消息:在断言失败时,通过使用
--tb=short
参数可以只显示简短的错误信息,使得失败报告更加简洁。pytest --tb=short
-
断言失败时截图:使用插件如
pytest-selenium
可以在断言失败时自动截图,方便查看测试环境和失败的页面状态。pytest --html=report.html --self-contained-html
这些是一些额外的 pytest 断言功能和技巧,可以根据您的具体需求选择合适的断言操作和工具来提升测试的质量和可维护性。