3.Assert

乙醇 创建于 over 6 years 之前

最后更新: about 1 month 之前

阅读数: 1

3.Assert

Assert就是断言,每个测试用例都需要断言。

与unittest不同,pytest使用的是python自带的assert关键字来进行断言,大大降低了学习成本。

assert关键字后面可以接一个表达式,只要表达式的最终结果为True,那么断言通过,用例执行成功,否则用例执行失败。

详尽的用例失败描述

pytest的用例失败描述非常详尽,一目了人。考虑下面的例子

# content of test_assert1.py
def f():
    return 3

def test_function():
    assert f() == 4

执行上面的用例

$ pytest test_assert1.py
======= test session starts ========
platform linux -- Python 3.x.y, pytest-3.x.y, py-1.x.y, pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR, inifile:
collected 1 item

test_assert1.py F

======= FAILURES ========
_______ test_function ________

    def test_function():
>       assert f() == 4
E       assert 3 == 4
E        +  where 3 = f()

test_assert1.py:5: AssertionError
======= 1 failed in 0.12 seconds ========

可以很明显的看出,pytest给出的错误提示是:f()的值是3,也就是实际结果是3,而预期结果是4,3不等于4,因此断言未通过,用例失败。

断言异常抛出

pytest有自己的异常抛出断言套路,下面是最简单的形式

import pytest

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

上面代码的意思是: 1/0的时候应该抛出ZeroDivisionError,否则用例失败,断言不通过。

另外pytest还允许我们访问异常的具体信息,如下面的例子

def test_recursion_depth():
    with pytest.raises(RuntimeError) as excinfo:
        def f():
            f()
        f()
    assert 'maximum recursion' in str(excinfo.value)

我们还可以定制断言异常的错误信息,比如

>>> with raises(ZeroDivisionError, message="Expecting ZeroDivisionError"):
...    pass
... Failed: Expecting ZeroDivisionError

总结

更多断言异常以及定制assert中比较方式的例子,请参阅官方文档

0

相关课程

webium简明教程
图文
webium简明教程

课程分类: 测试框架

开箱即用的page object模式

  • 已完结
  • 已更新8集
  • 最后更新时间: 2024-03-18 12:48:12

免费

查看详情
TestNG教程
图文
TestNG教程

课程分类: 测试框架

Java语言中最流行的测试框架了

  • 已完结
  • 已更新12集
  • 最后更新时间: 2024-03-18 12:55:14

免费

查看详情
python unittest测试框架教程
图文
python unittest测试框架教程

课程分类: 测试框架

python 自带的单元测试框架

  • 已完结
  • 已更新8集
  • 最后更新时间: 2024-03-18 12:12:46

免费

查看详情
TDD测试驱动开发教程
图文
TDD测试驱动开发教程

课程分类: 测试框架 软件测试基础

TDD其实并不神秘

  • 已完结
  • 已更新7集
  • 最后更新时间: 2024-03-18 11:53:22

免费

查看详情