目录
前言
测试的主要工作目标就是验证实际结果与预期结果是否一致;在接口自动化测试中,通过断言来实现这一目标。Pytest中断言是通过assert语句实现的(pytest对Python原生的assert语句进行了优化),确定实际情况是否与预期一致。
pytest断言assert的用法
在自动化测试用例中,最常用的断言是相等断言,就是断言预期结果和实际结果是一致的。pytest通过 “assert 实际结果 == 预期结果” 实现。通常我们断言的预期结果和实际结果的数据类型包括字符串、元组、字典、列表和对象。
1、断言字符串
# content of test_assertions.py
class TestAssertions(object):
def test_string(self):
assert "spam" == "eggs"
执行测试用例结果(在pycharm中以pytest执行用例,后面示例都如此):
test_assertions.py:2 (TestAssertions.test_string)
spam != eggs
Expected :eggs
Actual :spam
self =
def test_string(self):
> assert "spam" == "eggs"
E AssertionError: assert 'spam' == 'eggs'
test_assertions.py:4: AssertionError
说明:Expected 为期望结果(即 == 右侧的预期结果),Actual 为实际结果(即 == 左侧的实际结果),> 后面为出错的代码行,E 后面为错误信息。
2、断言函数返回值
class TestAssertions(object):
def test_function(self):
def f():
return [1, 2, 3]
assert f() == [1, 2, 4]
执行测试用例结果:
test_assertions.py:1 (TestAssertions.test_function)
[1, 2, 3] != [1, 2, 4]
Expected :[1, 2, 4]
Actual :[1, 2, 3]
self =
def test_function(self):
def f():
return [1, 2, 3]
> assert f() == [1, 2, 4]
E assert [1, 2, 3] == [1, 2, 4]
test_assertions.py:6: AssertionError
<