背景
本文总结使用pytest编写自动化测试时常用的assert断言。
说明
本文将从以下几点做总结:
- 为测试结果作断言
- 为断言不通过的结果添加说明信息
- 为预期异常作断言
- 为失败断言自定义说明信息
为测试结果作断言
在断言方面,pytest框架比其他类似的框架(比如unittest)更加简洁,易用,我想这是我选择pytest作为自动化测试框架之一的原因之一。
pytest的assert断言关键字支持使用python内置的assert表达式。可以理解为pytest的断言就是直接使用python自带的assert关键字。
python assert的概念:
Python assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。
我们可以在在assert后面添加任何符合python标准的表达式,如果表达式的值通过bool转换后等于False,则意味着断言结果为失败。
以下举例常用的表达式:
# ./test_case/test_func.py
import pytest
from func import *
class TestFunc:
def test_add_by_class(self):
assert add(2,3) == 5
def test_add_by_func_aaa():
assert 'a' in 'abc'
assert 'a' not in 'bbc'
something = True
assert something
something = False
assert not something
assert 1==1
assert 1!=2
assert 'a' is 'a'
assert 'a' is not 'b'
assert 1 < 2
assert 2 > 1
assert 1 <= 1
assert 1 >= 1
assert add(3,3) == 6
'''
# 以上全是合法的表达式且表达式的值都为True,所以测试结果为通过
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-5.3.4, py-1.8.1, pluggy-0.13.1 -- D:\Python3.7\python.exe
cachedir: .pytest_cache
rootdir: D:\Python3.7\project\pytest, inifile: pytest.ini
plugins: allure-pytest-2.8.9, rerunfailures-8.0
collecting ... collected 2 items
test_case/test_func.py::TestFunc::test_add_by_class PASSED [ 50%]
test_case/test_func.py::test_add_by_func_aaa PASSED [100%]
============================== 2 passed in 0.06s ==============================
[Finished in 1.8s]
'''
为断言不通过的结果添加说明信息
在编写测试时,为了提高易用性,我们想知道断言失败时的一些关于失败的原因等说明信息,assert也能满足该功能。
请看示例:
# ./test_case/test_func.py
import pytest
from func import *
class TestFunc:
def test_add_by_class(self):
assert add(2,3) == 5
def test_add_by_func_aaa():
assert add(3,3) == 5


724

被折叠的 条评论
为什么被折叠?



