我最终创建了一个测试运行器来实现我的目的。我需要模拟文件存储,以便在测试时图像实际上不会写入文件系统。在许多测试中都会调用图像对象,因此不会修补每个类DRY
。此外,我注意到模拟文件本身会将其留在系统中,以防测试失败。但是这个方法没有。
我runner.py
在项目根目录中创建了一个文件
# runner.py
from unittest.mock import patch
from django.test.runner import DiscoverRunner
from myapp.factories import ImageFactory
class UnitTestRunner(DiscoverRunner):
@patch('django.core.files.storage.FileSystemStorage.save')
def run_tests(self, test_labels, mock_save, extra_tests=None, **kwargs):
mock_save.return_value = ImageFactory.get_image()
return super().run_tests(test_labels, extra_tests=None, **kwargs)
然后我会使用python manage.py tests --testrunner=runner.UnitTestRunner
只是为了清楚起见,该ImageFactory.get_image
方法是自定义方法
from django.core.files.base import ContentFile
from factory.django import DjangoModelFactory
from io import BytesIO
from PIL import Image as PilImage
from random import randint
class ImageFactory(DjangoModelFactory):
@classmethod
def get_image(cls, name='trial', extension='png', size=None):
if size is None:
width = randint(20, 1000)
height = randint(20, 1000)
size = (width, height)
color = (256, 0, 0)
file_obj = BytesIO()
image = PilImage.new("RGBA", size=size, color=color)
image.save(file_obj, extension)
file_obj.seek(0)
return ContentFile(file_obj.read(), f'{name}.{extension}')