gpt4 book ai didi

python - 这个 Python 模拟补丁有什么问题?

转载 作者:太空狗 更新时间:2023-10-30 01:01:06 25 4
gpt4 key购买 nike

我在单元测试中模拟导入模块时遇到问题。我正在尝试使用模拟模块模拟我的模块 tracker.models 中的 PIL Image 类。我知道你应该在使用它们的地方模拟东西,所以我写了 @mock.patch('tracker.models.Image') 作为我的单元测试装饰器。我正在尝试检查下载的图像是否作为 PIL 图像打开。模拟补丁似乎覆盖了整个图像模块。这是我在运行测试时遇到的错误:

File "/home/ubuntu/workspace/tracker/models.py", line 40, in set_photo
width, height = image.size
ValueError: need more than 0 values to unpack

这是我的单元测试:

test_models.py

@responses.activate
@mock.patch('tracker.models.Image')
def test_set_photo(self, mock_pil_image):
# Initialize data
hammer = Product.objects.get(name="Hammer")
fake_url = 'http://www.example.com/prod.jpeg'
fake_destination = 'Hammer.jpeg'

# Mock successful image download using sample image. (This works fine)
with open('tracker/tests/test_data/small_pic.jpeg', 'r') as pic:
sample_pic_content = pic.read()
responses.add(responses.GET, fake_url, body=sample_pic_content, status=200, content_type='image/jpeg')

# Run the actual method
hammer.set_photo(fake_url, fake_destination)

# Check that it was opened as a PIL Image
self.assertTrue(mock_pil_image.open.called,
"Failed to open the downloaded file as a PIL image.")

这是它正在测试的一段代码。

tracker/models.py

class Product(models.Model):
def set_photo(self, url, filename):
image_request_result = requests.get(url)
image_request_result.content
image = Image.open(StringIO(image_request_result.content))

# Shrink photo if needed
width, height = image.size # Unit test fails here
max_size = [MAX_IMAGE_SIZE, MAX_IMAGE_SIZE]
if width > MAX_IMAGE_SIZE or height > MAX_IMAGE_SIZE:
image.thumbnail(max_size)
image_io = StringIO()
image.save(image_io, format='JPEG')
self.photo.save(filename, ContentFile(image_io.getvalue()))

最佳答案

您需要配置 Image.open 的返回值以包含 size 属性:

opened_image = mock_pil_image.open.return_value
opened_image.size = (42, 83)

现在,当您的被测函数调用 Image.open 时,返回的 MagicMock 实例将有一个 size 属性,它是一个元组。

您可以对需要返回某些内容的任何其他方法或属性执行相同的操作。

opened_image 引用也可用于测试被测函数的其他方面;您现在可以断言调用了 image.thumbnailimage.save:

opened_image = mock_pil_image.open.return_value
opened_image.size = (42, 83)

# Run the actual method
hammer.set_photo(fake_url, fake_destination)

# Check that it was opened as a PIL Image
self.assertTrue(mock_pil_image.open.called,
"Failed to open the downloaded file as a PIL image.")

self.assertTrue(opened_image.thumbnail.called)
self.assertTrue(opened_image.save.called)

这让您可以非常准确地测试您的缩略图大小逻辑是否正常工作,例如,无需测试 PIL 是否正在执行它所做的;毕竟,PIL 并未在这里进行测试。

关于python - 这个 Python 模拟补丁有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29717052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com