我在单元测试中遇到了模拟导入模块的问题。我正在尝试使用mock模块来模拟tracker.models
模块中的PIL Image类。我知道你应该在使用它们的地方模拟它们,所以我编写了@mock.patch('tracker.models.Image')
作为我的单元测试装饰器。我正在尝试检查下载的图像是否被打开为PIL Image。模拟补丁似乎覆盖了整个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
这是我的单元测试:
测试模型文件: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.size
必须是一个元组,但你没有为该元组设置任何模拟值。因此image.size
返回一个模拟对象。 - Martijn Pieters.called
而不是为整个模块批量执行。 - Stewart