python异常模拟工具类(异常生成工具类)
文章目录创建代码类使用主要是做测试的时候方便创建代码类1、新建python文件exception_mock_utils.py代码为importrandomimporttimefromtypingimportAny,OptionalclassExceptionMockUtils: 异常模拟工具类 用于在开发或测试阶段模拟各种常见的程序异常 # --- 基础空值与逻辑异常 ---staticmethoddefmock_null_pointer(msg:strAttempted to access null reference): 模拟 Java 风格的空指针异常 (Python 中对应 TypeError 或 AttributeError) raiseTypeError(msg)staticmethoddefmock_value_error(msg:strInvalid value provided): 模拟参数值错误 raiseValueError(msg)staticmethoddefmock_key_error(key:Anymissing_key): 模拟字典键缺失异常 raiseKeyError(key)staticmethoddefmock_index_error(index:int0): 模拟列表索引越界 raiseIndexError(flist index out of range:{index})staticmethoddefmock_assertion_error(msg:strAssertion failed): 模拟断言失败 raiseAssertionError(msg)# --- 文件与 IO 异常 ---staticmethoddefmock_file_not_found(filepath:str/tmp/missing.txt): 模拟文件未找到 raiseFileNotFoundError(f[Errno 2] No such file or directory: {filepath})staticmethoddefmock_permission_denied(filepath:str/root/secret.txt): 模拟权限拒绝 raisePermissionError(f[Errno 13] Permission denied: {filepath})# --- 网络与 API 异常 (模拟外部服务) ---staticmethoddefmock_timeout(seconds:float30.0): 模拟连接超时 raiseTimeoutError(fConnection timed out after{seconds}seconds)staticmethoddefmock_connection_refused(port:int8080): 模拟连接被拒绝 raiseConnectionRefusedError(fConnection refused on port{port})staticmethoddefmock_http_error(status_code:int500): 模拟 HTTP 错误 (需配合 requests 库或自定义异常) 这里使用通用的 Exception 模拟 raiseException(fHTTP Error{status_code}: Internal Server Error)# --- 运行时与随机异常 ---staticmethoddefmock_runtime_error(msg:strUnexpected runtime error): 模拟通用运行时错误 raiseRuntimeError(msg)staticmethoddefmock_random_failure(rate:float0.5,msg:strRandom failure occurred): 模拟随机失败 :param rate: 失败概率 (0.0 - 1.0) ifrandom.random()rate:raiseRuntimeError(msg)staticmethoddefmock_slow_down(delay:float3.0): 模拟服务响应过慢 (不抛异常但模拟卡顿常用于测试超时逻辑) time.sleep(delay)使用创建python文件test_exception.py代码如下fromexception_mock_utilsimportExceptionMockUtils exceptionMockUtilsExceptionMockUtils()exceptionMockUtils.mock_random_failure()运行即可。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2470377.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!