# 3.Assert




Assert就是断言，每个测试用例都需要断言。

与unittest不同，pytest使用的是python自带的assert关键字来进行断言，大大降低了学习成本。

assert关键字后面可以接一个表达式，只要表达式的最终结果为True，那么断言通过，用例执行成功，否则用例执行失败。

### 详尽的用例失败描述

pytest的用例失败描述非常详尽，一目了人。考虑下面的例子

```python
# 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有自己的异常抛出断言套路，下面是最简单的形式

```python
import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1 / 0
```

上面代码的意思是: 1/0的时候应该抛出ZeroDivisionError，否则用例失败，断言不通过。

另外pytest还允许我们访问异常的具体信息，如下面的例子

```python
def test_recursion_depth():
    with pytest.raises(RuntimeError) as excinfo:
        def f():
            f()
        f()
    assert 'maximum recursion' in str(excinfo.value)
```

我们还可以定制断言异常的错误信息，比如

```python
>>> with raises(ZeroDivisionError, message="Expecting ZeroDivisionError"):
...    pass
... Failed: Expecting ZeroDivisionError
```

### 总结

更多断言异常以及定制assert中比较方式的例子，请参阅[官方文档](https://docs.pytest.org/en/latest/assert.html)




原始封面

![课程图片](https://images.unsplash.com/photo-1422493757035-1e5e03968f95?w=300)


