
在构建健壮的应用程序时,自定义异常是处理特定错误情境的有效机制。它们能够提供比标准python异常更详细、更具业务含义的错误信息。以下是一个典型的自定义api异常类定义:
import inspect
class ApiException(Exception):
def __init__(self, response) -> None:
self.http_code = response.status_code
self.message = response.text.replace("\n", " ")
# 获取调用者信息,用于调试
self.caller = inspect.getouterframes(inspect.currentframe(), 2)[1]
self.caller_file = self.caller[1]
self.caller_line = self.caller[2]
def __str__(self) -> str:
return f"Error code {self.http_code} with message '{self.message}' in file {self.caller_file} line {self.caller_line}"当API调用返回非成功状态码时,我们通常会抛出此类异常:
# 假设response是一个模拟的HTTP响应对象 if response.ok: return MergeRequest(json.loads(response.text)) else: raise ApiException(response=response)
在单元测试中,我们常常需要验证代码是否在特定条件下抛出了预期的异常类型。一个直观的做法是使用try...except块捕获异常,然后通过isinstance()来检查其类型。然而,这种方法有时会遇到意想不到的问题,即isinstance()返回False,即使type(err)显示的是正确的异常类。
考虑以下测试代码片段,它尝试验证ApiException是否被正确抛出:
import unittest
from unittest.mock import MagicMock
# 假设 ApiException 和 GitLab 类已正确导入
# from APIs.api_exceptions import ApiException
# from your_module import GitLab, ApiCall, ApiCallResponse, TestLogger
class TestException(unittest.TestCase):
def test_raise_exception_with_isinstance(self):
# 模拟API调用和响应
api_call = MagicMock()
api_response = MagicMock()
api_response.ok = False
api_response.status_code = 401
api_response.text = "Unauthorized"
api_call.get_with_header.return_value = api_response
# 模拟GitLab客户端
# GitLab需要一个logger和api_call实例
# TestLogger = MagicMock() # 假设TestLogger是一个简单的模拟日志器
# 假设GitLab类接受logger和api_call作为参数
# class GitLab:
# def __init__(self, logger, api_call):
# self.logger = logger
# self.api_call = api_call
# def get_project_by_url(self, url):
# response = self.api_call.get_with_header(url)
# if response.ok:
# return "Project Data" # 简化处理
# else:
# raise ApiException(response=response)
# 实例化GitLab,传入模拟对象
# gitlab = GitLab(logger=TestLogger, api_call=api_call) # 假设TestLogger是可用的
# 为了使示例可运行,我们直接模拟抛出ApiException
# 实际测试中,gitlab.get_project_by_url会抛出异常
# 模拟一个ApiException实例
mock_response = MagicMock()
mock_response.status_code = 401
mock_response.text = "Unauthorized"
try:
# 假设这里是实际会抛出异常的代码
# gitlab.get_project_by_url("https://git.mycompany.de/group/project")
raise ApiException(response=mock_response) # 直接抛出,方便演示
self.fail("Expected ApiException but none was raised.") # 如果没抛异常,则测试失败
except Exception as err:
# TestLogger.info(type(err)) # 打印类型,可能显示 <class 'APIs.api_exceptions.ApiException'>
# TestLogger.info(isinstance(err, ApiException)) # 可能显示 False
self.assertIsInstance(err, ApiException, "Expected ApiException type")
# self.assertTrue(isinstance(err, ApiException), "Expected ApiException type") # 原始问题中的断言方式
上述代码中self.assertIsInstance(err, ApiException)(或原始的assert isinstance(err, ApiException))可能会失败,并报错assert False。这通常发生在以下情况:
立即学习“Python免费学习笔记(深入)”;
为了避免isinstance()可能带来的混淆,并编写更健壮的异常测试,我们推荐以下两种策略:
最直接且可靠的方法是在except块中指定要捕获的精确异常类型。如果抛出的异常与指定的类型不匹配,或者不是其子类,那么它将不会被该except块捕获,而是继续向上传播,导致测试失败。
import unittest
from unittest.mock import MagicMock
# 确保 ApiException 在这里被正确导入
class ApiException(Exception):
def __init__(self, response):
self.http_code = response.status_code
self.message = response.text
def __str__(self):
return f"Error {self.http_code}: {self.message}"
class TestExceptionDirectCatch(unittest.TestCase):
def test_raise_specific_exception(self):
mock_response = MagicMock()
mock_response.status_code = 401
mock_response.text = "Unauthorized"
try:
# 模拟会抛出 ApiException 的代码
raise ApiException(response=mock_response)
self.fail("Expected ApiException but none was raised.")
except ApiException:
# 如果成功捕获到 ApiException,则测试通过
self.assertTrue(True, "ApiException was correctly caught.")
except Exception as e:
# 捕获到其他异常,则测试失败
self.fail(f"Caught an unexpected exception type: {type(e).__name__}")这种方法清晰地表达了测试意图:我们期望代码抛出ApiException,并且只处理这种类型的异常。
unittest框架提供了专门用于测试异常的断言方法assertRaises。这是测试异常抛出的最推荐方式,因为它更简洁、更具可读性,并且能够自动处理try...except逻辑。
assertRaises可以作为上下文管理器使用,也可以直接调用。
作为上下文管理器使用(推荐):
import unittest
from unittest.mock import MagicMock
# 确保 ApiException 在这里被正确导入
class ApiException(Exception):
def __init__(self, response):
self.http_code = response.status_code
self.message = response.text
def __str__(self):
return f"Error {self.http_code}: {self.message}"
class TestExceptionAssertRaises(unittest.TestCase):
def test_raise_exception_with_context_manager(self):
mock_response = MagicMock()
mock_response.status_code = 401
mock_response.text = "Unauthorized"
with self.assertRaises(ApiException) as cm:
# 在这个块中执行预期会抛出 ApiException 的代码
raise ApiException(response=mock_response)
# 此时,cm.exception 属性将包含被捕获的异常实例
caught_exception = cm.exception
self.assertEqual(caught_exception.http_code, 401)
self.assertIn("Unauthorized", caught_exception.message)这种方式不仅能验证异常类型,还能方便地访问捕获到的异常实例,从而进一步断言异常的属性(如错误码、错误消息等)。
直接调用 assertRaises:
import unittest
from unittest.mock import MagicMock
# 确保 ApiException 在这里被正确导入
class ApiException(Exception):
def __init__(self, response):
self.http_code = response.status_code
self.message = response.text
def __str__(self):
return f"Error {self.http_code}: {self.message}"
# 假设有一个函数会抛出 ApiException
def function_that_raises_api_exception(response_obj):
raise ApiException(response=response_obj)
class TestExceptionAssertRaisesDirectCall(unittest.TestCase):
def test_raise_exception_with_direct_call(self):
mock_response = MagicMock()
mock_response.status_code = 401
mock_response.text = "Unauthorized"
# 传入异常类型、可调用对象和其参数
self.assertRaises(ApiException, function_that_raises_api_exception, mock_response)这种方式适用于测试简单的函数调用。
在Python单元测试中检测自定义异常时,isinstance()可能因模块导入路径不一致等问题导致误判。为了编写更可靠、更清晰的异常测试,推荐采用以下两种策略:在except块中直接指定捕获的异常类型,或更优选地,使用unittest.TestCase.assertRaises上下文管理器。这些方法不仅能有效验证异常的抛出,还能方便地检查异常的详细信息,从而确保代码在错误处理方面的正确性。始终注意导入的一致性,这是避免类型匹配问题的关键。
以上就是Python单元测试中自定义异常的检测与最佳实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号