目录
- 1、前言
- 2、常用断言
- 3、预期异常断言
- 4、优化断言提示
- 5、自定义失败断言提示
1、前言
Pytest使用python自带关键字assert进行断言,断言内容为一个表达式,只要表达式的最终结果为True,那么断言通过,用例执行成功,否则用例执行失败。
assert + 表达式
2、常用断言
assert xx
:判断xx为真assert not xx
: 判断xx不为真assert a in b
:判断b包含aassert a == b
: 判断a等于bassert a != b
: 判断a不等于b
3、预期异常断言
除了支持对代码正常运行的结果断言之外,Pytest也能够对 Exception 和 Warnning 进行断言。有时候断言会引发我们意料之中的异常,借助pytest.raises
可以捕获匹配到的异常,避免该条用例执行Failed。
- 示例1:如果抛出
ZeroDivisionError
测试结果是Pass,否则为Failed
def test_zero():
# 捕获预期异常
with pytest.raises(ZeroDivisionError) as ec:
res = 1 / 0
# 断言异常信息, 官方提示, raise 的异常应该是当前代码块最后一行,如果在其后面还有代码,那么将不会被执行。
assert \"zero\" in str(ec.value)
- 示例2:将异常信息存储到一个变量中,从而可以进一步断言
def test_zero():
# 捕获预期异常
with pytest.raises(ValueError) as ec:
raise ValueError(\"Zero Error\")
# 官方提示, raise 的异常应该是当前代码块最后一行,如果在其后面还有代码,那么将不会被执行。
print(\"错误说明\", ec.value)
print(\"错误回溯\", ec.traceback)
print(\"错误类型\",ec.type)
assert str(ec.value) == \"Zero Error\"
\"\"\"
执行结果
collected 1 item
test_temp.py::test_zero 错误说明 Zero Error
错误回溯 [<TracebackEntry /Users/qishuai/Desktop/笔记/web自动化测试/pytest/demo/test_temp.py:30>]
错误类型 <class \'ValueError\'>
PASSED
\"\"\"
- 示例3:预期异常还可以传递一个元祖
def test_Error_tuple():
with pytest.raises((ValueError, ZeroDivisionError)):
# res = 1/0
raise ValueError
- 示例4:通过match关键字进行正则表达式更精确断言异常
def match_error():
raise ValueError(\"This is Test Error\")
def match_error_2():
raise ValueError
def test_match():
with pytest.raises(ValueError,match=r\".* Test Error\") as ec:
match_error_2()
assert ec.type == ValueError
assert str(ec.value) == \"This is Test Error\"
上面示例4代码中由于添加了match关键字,所以match_error
引发的异常能被pytest.raise
捕获到,match_error_2
引发的异常不能被pytest.raise
捕获到。
更多异常断言:https://docs.pytest.org/en/latest/how-to/assert.html#assertions-about-expected-exceptions
4、优化断言提示
在断言时加入注释字符串,在报错时注释能够被打印出来
def test_assert_fail():
assert 1 > 2, \"断言1是否大于2\"
\"\"\"
执行结果
============================ test session starts ==============================
collecting ... collected 1 item
test_1.py::test_assert_fail FAILED [100%]
test_1.py:41 (test_assert_fail)
def test_assert_fail():
> assert 1 > 2, \"断言1是否大于2\"
E AssertionError: 断言1是否大于2
E assert 1 > 2
test_1.py:43: AssertionError
============================== 1 failed in 0.06s ===============================
\"\"\"
5、自定义失败断言提示
通过在conftest.py
中添加pytest_assertrepr_compare
钩子来添加您自己的详细解释,如下:
# content of conftest.py
def pytest_assertrepr_compare(op, left, right):
\"\"\"
:param op: 操作符
:param left: 操作符左边内容
:param right: 操作符右边内容
:return:
\"\"\"
if op == \">\":
return [\"比较大小\",f\"{left}不大于{right}\"]
# content of test_compare.py
def test_compare():
a = 1
b = 2
assert a > b
\"\"\"
执行结果:
collected 1 item
temp/test_compare_foo.py::test_compare FAILED
================================================================== FAILURES ===================================================================
________________________________________________________________ test_compare _________________________________________________________________
def test_compare():
a = 1
b = 2
> assert a > b
E assert 比较大小
E 1不大于2
temp/test_compare_foo.py:19: AssertionError
=========================================================== short test summary info ===========================================================
FAILED temp/test_compare_foo.py::test_compare - assert 比较大小
============================================================== 1 failed in 0.08s ==============================================================
\"\"\"
参考:
https://cloud.tencent.com/developer/article/1693769
http://www.360doc.com/content/22/0211/10/78594709_1016826734.shtml
https://docs.pytest.org/en/latest/how-to/assert.html#assertions-about-expected-exceptions
来源:https://www.cnblogs.com/qishuaiRisen/p/16573596.html
本站部分图文来源于网络,如有侵权请联系删除。