
在python单元测试中,我们经常需要模拟(mock)外部依赖,以隔离测试目标并控制其行为。`unittest.mock.patch`是实现这一目标的核心工具。然而,当模拟一个类及其方法,并且该方法被配置为抛出异常时,一个常见的困惑是,即使异常被捕获,对该方法调用次数的断言(`call_count`)却显示为零,导致测试失败。本文将详细解析这一现象的根本原因,并提供正确的测试策略。
考虑以下场景:我们有一个UploadService类,其中包含一个upload方法,该方法内部调用了Blob类的一个实例方法upload_from_string。我们希望测试当upload_from_string方法抛出GoogleCloudError时,upload方法如何处理。
原始代码示例 (upload_service.py):
import logging
import json
from unittest.mock import MagicMock # 假设Blob和GoogleCloudError是外部库
# 为了示例运行,这里简单定义一下
class GoogleCloudError(Exception):
pass
class Blob:
def __init__(self, name, bucket):
self.name = name
self.bucket = bucket
def upload_from_string(self, data, content_type):
# 实际操作可能抛出GoogleCloudError
raise GoogleCloudError("Simulated upload error")
class UploadService:
def __init__(self, config):
self.config = config # 示例配置
def upload(self, name, data, gcs_bucket):
try:
gcs_blob = Blob(name, gcs_bucket)
gcs_blob.upload_from_string(data=json.dumps(data), content_type="application/json")
return "Upload successful"
except GoogleCloudError as e:
logging.exception("Error uploading file")
return "Upload failed due to error"错误的测试代码示例 (test_upload_service.py):
import unittest
from unittest.mock import patch, MagicMock
from upload_service import UploadService, Blob, GoogleCloudError # 导入相关类
class TestUploadService(unittest.TestCase):
def test_upload_failure(self):
us = UploadService(config={}) # 实例化服务
with patch("upload_service.Blob") as mocked_blob_class: # 模拟Blob类
# 配置模拟实例的方法,使其抛出异常
gcs_blob_instance = mocked_blob_class.return_value
gcs_blob_instance.upload_from_string.side_effect = GoogleCloudError("Google Cloud error")
# 调用被测试的方法
result = us.upload("test_file", {"key": "value"}, "test_bucket")
# 错误的断言方式:试图在模拟的类对象上检查实例方法的调用计数
self.assertEqual(1, mocked_blob_class.upload_from_string.call_count)
self.assertEqual("Upload failed due to error", result)
运行上述测试,会得到如下失败信息:
立即学习“Python免费学习笔记(深入)”;
AssertionError: 1 != 0 Expected :1 Actual :0
这表明mocked_blob_class.upload_from_string.call_count的值是0,而不是预期的1。
要理解为何会出现上述问题,我们需要明确unittest.mock.patch在模拟类时的行为:
因此,在我们的例子中:
问题在于,我们错误地在mocked_blob_class.upload_from_string上检查了call_count。mocked_blob_class.upload_from_string是Blob类的模拟方法,它只会在直接通过Blob.upload_from_string()(如果这是一个类方法或静态方法)调用时才会被计数。
然而,upload_from_string是一个实例方法,它通过gcs_blob.upload_from_string()被调用,而gcs_blob是mocked_blob_class.return_value。因此,正确的call_count应该在mocked_blob_class.return_value.upload_from_string上进行断言。
正确的测试代码示例 (test_upload_service.py):
import unittest
from unittest.mock import patch, MagicMock
from upload_service import UploadService, Blob, GoogleCloudError # 导入相关类
import logging
# 配置logging,确保异常信息在测试输出中可见
logging.basicConfig(level=logging.INFO)
class TestUploadService(unittest.TestCase):
def test_upload_failure_correct_assertion(self):
us = UploadService(config={})
with patch("upload_service.Blob") as mocked_blob_class:
# 获取模拟的Blob实例
gcs_blob_instance = mocked_blob_class.return_value
# 配置模拟实例的方法,使其抛出异常
gcs_blob_instance.upload_from_string.side_effect = GoogleCloudError("Google Cloud error")
# 调用被测试的方法
result = us.upload("test_file", {"key": "value"}, "test_bucket")
# 正确的断言方式:在模拟的实例对象上检查方法调用计数
self.assertEqual(1, gcs_blob_instance.upload_from_string.call_count)
# 也可以这样写,效果相同:
# self.assertEqual(1, mocked_blob_class().upload_from_string.call_count)
self.assertEqual("Upload failed due to error", result)
# 还可以进一步断言Blob类本身被调用了一次
self.assertEqual(1, mocked_blob_class.call_count)
# 断言Blob类被调用的参数
mocked_blob_class.assert_called_once_with("test_file", "test_bucket")
通过将断言目标从mocked_blob_class.upload_from_string改为gcs_blob_instance.upload_from_string(即mocked_blob_class.return_value.upload_from_string),测试将成功通过。这证明了即使方法抛出异常,unittest.mock也能正确记录其调用计数,关键在于正确地引用被调用的模拟对象。
遵循这些原则,可以确保在Python单元测试中对unittest.mock的正确使用,尤其是在处理方法抛出异常的复杂场景时,能够准确无误地验证代码行为。
以上就是Python单元测试中Mocked实例方法调用计数异常的排查与解决的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号