断言
前言:
一条测试用例,断言是必不可少的,没有断言的测试用例是不完整的,当断言为真时,用例通过,反之则不通过。
一、pytest断言:
在pytest框架中,断言使用python自带的 assert 关键字。
| assert xx | 断言 xx 是否为真 |
| assert not xx | 断言 xx 是否为假 |
| assert a in b | 断言 b 中包含 a |
| assert a == b | 断言 a 是否等于 b |
| assert a != b | 断言 a 是否不等于 b |
示例:
def sum(a, b): return a + b flag = True var_a = 1 var_b = 1 class TestAssert: def test_a_1(self): assert sum(1, 3) == 4 def test_a_2(self): assert sum(1, 2) != 4 def test_a_3(self): assert 'a' in 'hello' def test_a_4(self): assert flag def test_a_5(self): assert not flag def test_a_6(self): print(id(var_a)) print(id(var_b)) assert var_a is var_b
执行结果:
collecting ... collected 6 items test_a_s.py::TestAssert::test_a_1 PASSED [ 16%] test_a_s.py::TestAssert::test_a_2 PASSED [ 33%] test_a_s.py::TestAssert::test_a_3 FAILED [ 50%] test_3\test_a_s.py:18 (TestAssert.test_a_3) self = <test_3.test_a_s.TestAssert object at 0x00000209982E3D30> def test_a_3(self): > assert 'a' in 'hello' E AssertionError: assert 'a' in 'hello' test_a_s.py:20: AssertionError test_a_s.py::TestAssert::test_a_4 PASSED [ 66%] test_a_s.py::TestAssert::test_a_5 FAILED [ 83%] test_3\test_a_s.py:24 (TestAssert.test_a_5) self = <test_3.test_a_s.TestAssert object at 0x00000209982E38E0> def test_a_5(self): > assert not flag E assert not True test_a_s.py:26: AssertionError test_a_s.py::TestAssert::test_a_6 PASSED [100%]140713376679584 140713376679584 ================================== FAILURES =================================== _____________________________ TestAssert.test_a_3 _____________________________ self = <test_3.test_a_s.TestAssert object at 0x00000209982E3D30> def test_a_3(self): > assert 'a' in 'hello' E AssertionError: assert 'a' in 'hello' test_a_s.py:20: AssertionError _____________________________ TestAssert.test_a_5 _____________________________ self = <test_3.test_a_s.TestAssert object at 0x00000209982E38E0> def test_a_5(self): > assert not flag E assert not True test_a_s.py:26: AssertionError =========================== short test summary info =========================== FAILED test_a_s.py::TestAssert::test_a_3 - AssertionError: assert 'a' in 'hello' FAILED test_a_s.py::TestAssert::test_a_5 - assert not True ========================= 2 failed, 4 passed in 0.06s ========================= Process finished with exit code 1
从执行结果中可以看出,assert 关键字可以 对测试用例进行断言。
二、异常断言
在pytest中,可以对异常进行断言。使用 with 上下文接收器,对生成的异常实例进行类型与值的判断。
示例:
import pytest class TestAssert: def test_a_1(self): with pytest.raises(ZeroDivisionError) as f: 1 / 0assert f.type == ZeroDivisionError assert "division by zero" in str(f.value)
分析:
pytest.raises()里面传入异常类型。
f为异常实例,with代码模块中放入可能出现报错的代码块。
f.type用于获取异常实例类型,f.value用于获取异常实例的值,但需要将其转换为str类型。
执行结果:
collecting ... collected 1 item test_a_s.py::TestAssert::test_a_1 PASSED [100%] ============================== 1 passed in 0.02s ==============================
思考:
1,如何进行多重断言?
2,pytest.raises()有没有更多的用法?
浙公网安备 33010602011771号