遇一山,过一山,处处有风景;只要勇敢向前,一路尽是繁花盛开。 | (点击查看→)【测试干货】python/java自动化、持续集成、性能、测开、简历、笔试面试等

pytest简易教程(24):pytest中异常处理

 

pytest简易教程汇总,详见https://www.cnblogs.com/uncleyong/p/17982846

常用异常处理方法

try...except

pytest.raises()

 

try...except

平常我们是这样用的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
 
print("begin")
try:
    a = int(input("请输入被除数:"))
    b = int(input("请输入除数:"))
    res = a/b
    print(f"res={res}")
except(ValueError, ArithmeticError):
    print("发生数字格式异常或算数异常")
except:
    print("发生其它异常")
print("finish")

 

右键:

 

 

也可以在测试用例中使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
 
def test_a():
    try:
        assert 1/0 == 1
    except(ValueError, ArithmeticError):
        print("发生数字格式异常或算数异常")
    except:
        print("发生其它异常")
    print("---test_a")

  

结果:

 

pytest.raises()

参考:https://www.osgeo.cn/pytest/reference.html?highlight=pytest%20raises#pytest-raises

作用:

1
2
3
4
5
6
7
可以捕获特定的异常
 
可以获取捕获的异常的细节(异常类型, 异常信息)
 
可以match匹配异常信息
 
发生异常,后面的代码将不会被执行

 

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/
import pytest
 
 
# 捕获特定的异常:哪怕with下面的代码发生了ZeroDivisionError类型的异常,整个用例不会认为是异常用例,认为是正常的
def test_raises1():
    with pytest.raises(ZeroDivisionError):
        1/0
 
# match是正则匹配
def test_raises2():
    with pytest.raises(ValueError, match='must be 0 or None'):
        raise ValueError("value must be 0 or None")
 
# 没有预期的异常就报错,同时,后面的代码不会被执行
def test_raises2_2():
    with pytest.raises(ValueError, match='must be 0 or None'):
        raise ZeroDivisionError("除数为0")
    print("finish")
 
# 多个异常放元组中
def test_raises2_3():
    with pytest.raises((ValueError, ZeroDivisionError)):
        raise ZeroDivisionError("除数为0")
 
 
# match是正则匹配,可以使用正则表达式
def test_raises3():
    with pytest.raises(ValueError, match=r'must be \d+$'):
        raise ValueError("value must be 42")
 
 
# 获取捕获的异常的细节(异常类型, 异常信息)
def test_raises4():
    with pytest.raises(ValueError) as exc_info:
        raise ValueError("value must be 42")
    assert exc_info.type is ValueError
    assert exc_info.value.args[0] == "value must be 42"

  

结果:

 

 

posted @   全栈测试笔记  阅读(242)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2022-02-23 答疑记录:jmeter从返回的html中提取指定内容
浏览器标题切换
浏览器标题切换end
点击右上角即可分享
微信分享提示