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()

运行即可。

相关推荐
极序时代GEO品牌优化4 小时前
杭州极序时代|面向地域、设备与用户画像的动态GEO
人工智能·python·算法·极序时代geo
mlidongfeng5 小时前
[AI][C++26] SIMD 编程模型思考
开发语言·c++·人工智能
j7~5 小时前
【Linux】二十七.线程篇四《Linux多线程编程:线程互斥(互斥量的底层到封装)、线程安全和冲入、死锁》---详解
linux·开发语言·c++·线程安全·死锁·线程互斥·重入
刘名喜5 小时前
第09篇-协程基础-Kotlin异步编程
开发语言·kotlin·springboot
其实防守也摸鱼5 小时前
HackBar 工具完全指南:信息探测、漏洞验证与安全测试实战
开发语言·人工智能·学习·安全·网络安全·安全威胁分析·安全性测试
qq_22589174665 小时前
基于Python的外卖订单数据分析可视化系统
python·信息可视化·django
MC皮蛋侠客5 小时前
SQLAlchemy 系列(三):声明式映射与 Schema——让类型、默认值和约束一致
数据库·python
会博通·代码搬运工5 小时前
会博通API对接实战:工程企业文档分布式采集系统的技术实现与Python SDK详解
开发语言·分布式·python·线性代数·矩阵·架构·电子档案合规
空堂与归5 小时前
大模型再火,也得先过 class 这一关
python
Muselit5 小时前
Python 泛型:把 list[User] 讲明白
python·fastapi