首页 > 其他分享 >Pytest框架断言总结

Pytest框架断言总结

时间:2022-12-16 16:03:35浏览次数:37  
标签:__ 断言 框架 pytest assert Pytest fun def

 

 案例1:使用assert进行断言

"""
pytest框架使用python中的assert进行断言
assert a in b
assert a==b
assert a!=b
assert not a
assert a
"""
import pytest

def fun():
    pwd="123479"
    return pwd

def test_fun_one():
    passwd=fun()
    assert len(passwd)==6


def test_fun_two():
    passwd=fun()
    assert passwd.isdigit()
    
if __name__ == '__main__':
    pytest.main()

案例2:优化断言信息

添加断言自检,这样当断言失败时可以给出错误的提示信息

"""
优化断言,添加断言自检信息
assert 表达式,"错误原因"

"""
import pytest
def fun(a):
    return a+10


def test_one():
    a=fun(5)
    assert a % 2 == 0, "a是奇数,预期a为偶数。a的值是%d" %a

if __name__ == '__main__':
       pytest.main()

案例3:异常断言

在使用断言的过程中时常会出现异常,所以可以对特定的异常进行断言

import pytest

def test_excep_value():
    with pytest.raises(ZeroDivisionError) as zero:
        1/0 #这个是表达式,也可以是方法

    print(zero.traceback)
    assert "division by zero" in str(zero.value)
    assert zero.type==ZeroDivisionError

自定义异常:

import pytest
def is_leap_year(year):
    if isinstance(year,int) is not True:
        raise TypeError("年份必须是整数")#自定义异常
    elif year<=0:
        raise ValueError("年份必须大于等于0")#自定义异常
    elif(year%4==0 and year%100!=0) or year%400==0:
        print("%d年是闰年"%year)
        return True
    else:
        print("%d年不是闰年"%year)
        return False

def test_year_one():
    with pytest.raises(TypeError) as ex: #断言第一个异常
        is_leap_year("hello")

    print(ex.typename)
    print(ex.traceback)
    assert "年份必须是整数" in str(ex.value)
    assert ex.type==TypeError

if __name__ == '__main__':
    pytest.main()

拓展一:match关键字

将match关键字参数传递给上下文管理器,以测试 正则表达式 是否与异常的字符串表示形式匹配.

注意:这种方法只能断言value,不能断言type

'''
将match关键字参数传递给上下文管理器,
以测试 正则表达式 是否与异常的字符串表示形式匹配.
'''
import pytest
def myfunc():
    raise ValueError("Exception 123 raised")

def test_match():
    with pytest.raises(ValueError,match=r".* 123 .*") as ex:#这里只能和值比较
        myfunc()

    print(ex.traceback)
    print(ex.typename)
    assert ex.type==ValueError

案例4:mark标记注解方式:

@pytest.mark.xfail(raise=XXX)

import pytest
@pytest.mark.xfail(raises=IndexError)#对异常进行断言
def test_one():
    x=[1]
    x[1]=1

if __name__ == '__main__':
    pytest.main()

 更多使用方式可以私信我,wx:xiaoshanhu_ck

标签:__,断言,框架,pytest,assert,Pytest,fun,def
From: https://www.cnblogs.com/lijiabiao/p/16987562.html

相关文章