Pytest 框架断言

Pytest使用的是python自带的assert关键字来进行断言
1 常用断言:

assert xx :判断 xx 为真
assert not xx :判断 xx 不为真
assert a in b :判断 b 包含 a
assert a == b :判断 a 等于 b
assert a != b :判断 a 不等于 b

2 异常断言
适用场景:预测输入某些特定数据,会抛出特定异常,若出现特定异常,则用例执行通过。
栗子:针对如下代码做异常判断:

def is_leap_year(year):
    if isinstance(year, int) is not True:
        raise TypeError("传入的参数不是整数")
    elif year == 0:
        raise ValueError("公元元年是从公元一年开始!!")
    elif abs(year) != year:
        raise ValueError("传入的参数不是正整数")
    elif (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
        print("%d年是闰年" % year)
        return True
    else:
        print("%d年不是闰年" % year)
    return False

2.1 pytest.raises()

def test_exception_typeerror(self):
    with pytest.raises(TypeError):
        is_leap_year('ss')

2.2 pytest.raises() as objectname;

def test_exception_value(self):
    with pytest.raises(ValueError) as excinfo:
        is_leap_year(0)

    assert "从公元一年开始" in str(excinfo.value)
    assert excinfo.type == ValueError

2.3 pytest.raises(ValueError, match=r"pattern'')

def test_exception_match(self):
    with pytest.raises(ValueError, match=r'公元元年是从公元一年开始') as excinfo:
        is_leap_year(0)

    assert excinfo.type == ValueError

*2.4 @pytest.mark.xfail(raises=**)
Error匹配则用例标记为Xfail,不抛异常

@pytest.mark.xfail(raises=ValueError)
def test_a(self):
    is_leap_year(-100)

3 多重断言--pytest.assume(condition)
3.1 安装插件
pip3 install pytest-assume
3.2 作用
有多重断言时,用assert 有一个失败,则后续不执行。而pytest.assume会执行后续脚本

def test_assume():
    pytest.assume(eval('1+1')==3)
    pytest.assume(eval('1 + 1') == 2)
讨论数量: 1

简单明了的入门

4年前

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!