pytest学习assert断言

断言(Assert)

在自动化测试用例,需要断言,判断该用例是否正确。

例子1:

def f():
    return 4


def test_function():
    assert f() == 4, "判断函数的值是否等于自定义函数值"

执行结果:通过PASS

例子2:异常断言

import pytest
def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1/0
import pytest
def test_zero_division():
    """断言异常"""
    with pytest.raises(ZeroDivisionError) as execinfo:
        1/0

        # 断言异常类型type
        assert execinfo.type == ZeroDivisionError
        # 断言异常value值
        assert "division by zero" in str(execinfo.value)

例子3:常用断言

import pytest


def is_true(a):
    if a > 0:
        return True
    else:
        return False


def test_01():
    a = 5
    b = -1
    assert is_true(a)
    assert not is_true(b)


def test_02():
    a = "admin"
    b = "hello world"
    assert a in b


def test_03():
    a = "admin"
    b = "admin"
    assert a == b


def test_04():
    a = 5
    b = 6
    assert a != b


if __name__ == '__main__':
    pytest.main(['-s', 'test_02.py'])
原文地址:https://www.cnblogs.com/wzhqzm/p/14392042.html