python异常模拟工具类(异常生成工具类)

文章目录

主要是做测试的时候方便,

创建代码类

1、新建python文件exception_mock_utils.py,代码为:

python 复制代码
import random
import time
from typing import Any, Optional

class ExceptionMockUtils:
    """
    异常模拟工具类
    用于在开发或测试阶段模拟各种常见的程序异常
    """

    # --- 基础空值与逻辑异常 ---

    @staticmethod
    def mock_null_pointer(msg: str = "Attempted to access null reference"):
        """
        模拟 Java 风格的空指针异常 (Python 中对应 TypeError 或 AttributeError)
        """
        raise TypeError(msg)

    @staticmethod
    def mock_value_error(msg: str = "Invalid value provided"):
        """
        模拟参数值错误
        """
        raise ValueError(msg)

    @staticmethod
    def mock_key_error(key: Any = "missing_key"):
        """
        模拟字典键缺失异常
        """
        raise KeyError(key)

    @staticmethod
    def mock_index_error(index: int = 0):
        """
        模拟列表索引越界
        """
        raise IndexError(f"list index out of range: {index}")

    @staticmethod
    def mock_assertion_error(msg: str = "Assertion failed"):
        """
        模拟断言失败
        """
        raise AssertionError(msg)

    # --- 文件与 IO 异常 ---

    @staticmethod
    def mock_file_not_found(filepath: str = "/tmp/missing.txt"):
        """
        模拟文件未找到
        """
        raise FileNotFoundError(f"[Errno 2] No such file or directory: '{filepath}'")

    @staticmethod
    def mock_permission_denied(filepath: str = "/root/secret.txt"):
        """
        模拟权限拒绝
        """
        raise PermissionError(f"[Errno 13] Permission denied: '{filepath}'")

    # --- 网络与 API 异常 (模拟外部服务) ---

    @staticmethod
    def mock_timeout(seconds: float = 30.0):
        """
        模拟连接超时
        """
        raise TimeoutError(f"Connection timed out after {seconds} seconds")

    @staticmethod
    def mock_connection_refused(port: int = 8080):
        """
        模拟连接被拒绝
        """
        raise ConnectionRefusedError(f"Connection refused on port {port}")

    @staticmethod
    def mock_http_error(status_code: int = 500):
        """
        模拟 HTTP 错误 (需配合 requests 库或自定义异常)
        这里使用通用的 Exception 模拟
        """
        raise Exception(f"HTTP Error {status_code}: Internal Server Error")

    # --- 运行时与随机异常 ---

    @staticmethod
    def mock_runtime_error(msg: str = "Unexpected runtime error"):
        """
        模拟通用运行时错误
        """
        raise RuntimeError(msg)

    @staticmethod
    def mock_random_failure(rate: float = 0.5, msg: str = "Random failure occurred"):
        """
        模拟随机失败
        :param rate: 失败概率 (0.0 - 1.0)
        """
        if random.random() < rate:
            raise RuntimeError(msg)

    @staticmethod
    def mock_slow_down(delay: float = 3.0):
        """
        模拟服务响应过慢 (不抛异常,但模拟卡顿,常用于测试超时逻辑)
        """
        time.sleep(delay)
使用

创建python文件test_exception.py,代码如下:

python 复制代码
from exception_mock_utils import ExceptionMockUtils

exceptionMockUtils = ExceptionMockUtils()
exceptionMockUtils.mock_random_failure()

运行即可。

相关推荐
曲幽2 小时前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码3 小时前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱12 小时前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵14 小时前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio17 小时前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户03321266636719 小时前
使用 Python 从零创建 Word 文档
python
Csvn1 天前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python
曲幽1 天前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户556918817531 天前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维
兵慌码乱2 天前
基于 MediaPipe 与 PySide2 的手势交互音乐控制系统实现:轻量化视觉交互全流程解析
python·opencv·计算机视觉·人机交互·手势识别·mediapipe·pyside2