Pytest自动化测试用例中的断言详解

news/2025/2/21 7:17:54/

前言
测试的主要工作目标就是验证实际结果与预期结果是否一致;在接口自动化测试中,通过断言来实现这一目标。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 != eggsExpected :eggs
Actual   :spamself = 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
3、断言集合类型

断言字典、列表、元组集合等类型在测试中也是很常见的。比如下面这段测试用例代码:

class TestCollections(object):def test_dict(self):assert {"a": 0, "b": 1, "c": 0} == {"a": 0, "b": 2, "d": 0}def test_dict2(self):assert {"a": 0, "b": {"c": 0}} == {"a": 0, "b": {"c": 2}}def test_list(self):assert [0, 1, 2] == [0, 1, 3]def test_list2(self):assert [0, 1, 2] == [0, 1, [1, 2]]def test_tuple(self):assert (0, 1, 2) ==(0, 1, 3)def test_set(self):assert {0, 10, 11, 12} == {0, 20, 21}

执行测试用例结果:

FAILED                    [ 16%]
test_assertions.py:1 (TestCollections.test_dict)
{'a': 0, 'b': 1, 'c': 0} != {'a': 0, 'b': 2, 'd': 0}Expected :{'a': 0, 'b': 2, 'd': 0}
Actual   :{'a': 0, 'b': 1, 'c': 0}self = def test_dict(self):
>       assert {"a": 0, "b": 1, "c": 0} == {"a": 0, "b": 2, "d": 0}
E       AssertionError: assert {'a': 0, 'b': 1, 'c': 0} == {'a': 0, 'b': 2, 'd': 0}test_assertions.py:3: AssertionError
FAILED                   [ 33%]
test_assertions.py:4 (TestCollections.test_dict2)
{'a': 0, 'b': {'c': 0}} != {'a': 0, 'b': {'c': 2}}Expected :{'a': 0, 'b': {'c': 2}}
Actual   :{'a': 0, 'b': {'c': 0}}self = def test_dict2(self):
>       assert {"a": 0, "b": {"c": 0}} == {"a": 0, "b": {"c": 2}}
E       AssertionError: assert {'a': 0, 'b': {'c': 0}} == {'a': 0, 'b': {'c': 2}}test_assertions.py:6: AssertionError
FAILED                    [ 50%]
test_assertions.py:7 (TestCollections.test_list)
[0, 1, 2] != [0, 1, 3]Expected :[0, 1, 3]
Actual   :[0, 1, 2]self = def test_list(self):
>       assert [0, 1, 2] == [0, 1, 3]
E       assert [0, 1, 2] == [0, 1, 3]test_assertions.py:9: AssertionError
FAILED                   [ 66%]
test_assertions.py:10 (TestCollections.test_list2)
[0, 1, 2] != [0, 1, [1, 2]]Expected :[0, 1, [1, 2]]
Actual   :[0, 1, 2]self = def test_list2(self):
>       assert [0, 1, 2] == [0, 1, [1, 2]]
E       assert [0, 1, 2] == [0, 1, [1, 2]]test_assertions.py:12: AssertionError
FAILED                   [ 83%]
test_assertions.py:13 (TestCollections.test_tuple)
(0, 1, 2) != (0, 1, 3)Expected :(0, 1, 3)
Actual   :(0, 1, 2)self = def test_tuple(self):
>       assert (0, 1, 2) ==(0, 1, 3)
E       assert (0, 1, 2) == (0, 1, 3)test_assertions.py:15: AssertionError
FAILED                     [100%]
test_assertions.py:16 (TestCollections.test_set)
{0, 10, 11, 12} != {0, 20, 21}Expected :{0, 20, 21}
Actual   :{0, 10, 11, 12}self = def test_set(self):
>       assert {0, 10, 11, 12} == {0, 20, 21}
E       assert {0, 10, 11, 12} == {0, 20, 21}test_assertions.py:18: AssertionErrorAssertion failed

除了相等断言,常用的类型断言有以下几种:

assert xx #判断xx为真
assert not xx #判断xx不为真
assert a > b #判断a大于b
assert a < b #判断a小于b
assert a != b #判断a不等于b
assert a in b #判断b包含a
assert a not in b #判断b不包含a


更多断言的例子,大家可以参考Pytest的官方文档:
https://docs.pytest.org/en/latest/example/reportingdemo.html

这里一共有44个断言的例子,非常全面,几乎涵盖了所有的结果断言场景。

Pytest断言Excepiton
除了支持对代码正常运行的结果断言之外,Pytest也能够对 Exception 和 Warnning 进行断言,来断定某种条件下,一定会出现某种异常或者警告。在功能测试和集成测试中,这两类断言用的不多,这里简单介绍一下。

对于异常的断言,Pytest的语法是:with pytest.raises(异常类型),可以看下面的这个例子:

def test_zero_division():with pytest.raises(ZeroDivisionError):1 / 0

这个测试用例断言运算表达式1除以0会产生ZeroDivisionError异常。除了对异常类型进行断言,还可以对异常信息进行断言,比如:

import pytest# content of test_assertions.py
class TestAssertions(object):def test_zero_division(self):with pytest.raises(ZeroDivisionError) as excinfo:1 / 0assert 'division by zero' in str(excinfo.value)

这个测试用例,就断言了excinfo.value的内容中包含division by zero这个字符串,这在需要断言具体的异常信息时非常有用。对于Warnning的断言,其实与Exception的断言的用法基本一致。这里就不介绍了,

优化断言
我们可以在异常的时候,输出一些提示信息。这样报错后。可以方便我们来查看原因。

拿最开始的例子来说,在assert后面加上说明(在断言等式后面加上 , 然在后写上说明信息):
 

# content of test_assertions.py
class TestAssertions(object):def test_string(self):assert "spam" == "eggs","校验字符串'spam'是否等于'eggs'"

执行测试用例结果:

FAILED                   [100%]
AssertionError: 判断字符串'spam'是否等于'eggs'
spam != eggsExpected :eggs
Actual   :spamself = def test_string(self):
>       assert "spam" == "eggs","校验字符串'spam'是否等于'eggs'"
E       AssertionError: 校验字符串'spam'是否等于'eggs'
E       assert 'spam' == 'eggs'test_assertions.py:4: AssertionError

这样当断言失败的时候,会给出自己写的失败原因了 E AssertionError: 校验字符串'spam'是否等于'eggs'

总结:

感谢每一个认真阅读我文章的人!!!

作为一位过来人也是希望大家少走一些弯路,如果你不想再体验一次学习时找不到资料,没人解答问题,坚持几天便放弃的感受的话,在这里我给大家分享一些自动化测试的学习资源,希望能给你前进的路上带来帮助

软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。'

 


http://www.ppmy.cn/news/1267411.html

相关文章

三天精通Selenium Web 自动化 - Selenium(Java)环境搭建 (new)

0 背景 开发工具idea代码管理mavenjdk1.8webdriver chrome 1 chromedriver & chrome chromedriver和chrome要对应上&#xff1a; chomedriver下载地址&#xff1a;淘宝镜像 这里用的是 chromedriver88-0-4324-96.zipchrome下载地址&#xff1a;如何降级和安装旧版本的C…

智能查券机器人:导购APP的新趋势

智能查券机器人&#xff1a;导购APP的新趋势 大家好&#xff0c;我是免费搭建查券返利机器人赚佣金就用微赚淘客系统3.0的小编&#xff0c;也是冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01; 在当今这个数字化时代&#xff0c;网络购物已经成为人们日常生活的一部…

深入理解Disruptor - 无锁并发框架的革命

1. Disruptor框架简介 概述&#xff1a; Disruptor是一种高性能的内存队列&#xff0c;最初由LMAX开发&#xff0c;目的是在低延迟交易系统中替代传统的阻塞队列。它通过使用环形数组和无锁的发布/订阅模式&#xff0c;显著降低了线程间通信的延迟。这种设计使得它在多生产者-…

(C++)最大连续1的个数--滑动窗口

个人主页&#xff1a;Lei宝啊 愿所有美好如期而遇 力扣&#xff08;LeetCode&#xff09;官网 - 全球极客挚爱的技术成长平台备战技术面试&#xff1f;力扣提供海量技术面试资源&#xff0c;帮助你高效提升编程技能&#xff0c;轻松拿下世界 IT 名企 Dream Offer。https://le…

听GPT 讲Rust源代码--src/tools(8)

File: rust/src/tools/rust-analyzer/crates/ide-assists/src/handlers/add_missing_match_arms.rs 在Rust源代码中&#xff0c;rust-analyzer是一个Rust编程语言的语言服务器。它提供了代码补全、代码重构和代码导航等功能来帮助开发者提高编码效率。 在rust-analyzer的代码目…

​secrets --- 生成管理密码的安全随机数​

3.6 新版功能. 源代码: Lib/secrets.py secrets 模块用于生成高度加密的随机数&#xff0c;适于管理密码、账户验证、安全凭据及机密数据。 最好用 secrets 替代 random 模块的默认伪随机数生成器&#xff0c;该生成器适用于建模和模拟&#xff0c;不宜用于安全与加密。 参见…

ArcGIS Pro 指定范围裁剪点云

一、轨迹点 转 轨迹线&#xff1a;【工具】点集转线 二、线平行复制 三、封闭线 四、线转面&#xff1a;【工具】要素转面 五、裁剪点云&#xff1a;【工具】提取LAS

第三十二章 控制到 XML 模式的映射 - %ListOfObjects

文章目录 第三十二章 控制到 XML 模式的映射 - %ListOfObjects%ArrayOfObjects 第三十二章 控制到 XML 模式的映射 - %ListOfObjects 本部分显示了从支持 XML 的类生成的 XML架构的一部分&#xff0c;该类包含定义为 %ListOfObjects 的属性。例如&#xff0c;考虑以下属性定义…