繁体   English   中英

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

[英]What's wrong with this Python mock patch?

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

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

这是我的单元测试:

测试模型.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.")

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

跟踪器/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。

我正在编写一个类似的测试,但我的函数使用Image.open作为上下文管理器( with Image.open(<filepath>) as img: )。 感谢的Martijn Pieters的的答案,这一次我能我的测试获得与工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM