如何在 Django Rest Framework 上测试图像上传

Mat*_*oco 5 python django temporary-files django-rest-framework

我正在挣扎。问题出在单元测试(“test.py”)上,我想出了如何使用tempfilePIL上传图像,但这些临时图像永远不会被删除。我考虑创建一个临时目录,然后使用os.remove删除该 temp_dir,但图像上传到不同的媒体目录取决于模型,所以我真的不知道如何发布 temp_images 然后删除它们。

\n

这是我的models.py

\n
class Noticia(models.Model):\n  ...\n  img = models.ImageField(upload_to="noticias", storage=OverwriteStorage(), default="noticias/tanque_arma3.jpg")\n  ...\n
Run Code Online (Sandbox Code Playgroud)\n

测试.py

\n
def temporary_image():\n    import tempfile\n    from PIL import Image\n\n    image = Image.new(\'RGB\', (100, 100))\n    tmp_file = tempfile.NamedTemporaryFile(suffix=\'.jpg\', prefix="test_img_")\n    image.save(tmp_file, \'jpeg\')\n    tmp_file.seek(0)\n    return tmp_file\n\nclass NoticiaTest(APITestCase):\n    def setUp(self):\n        ...\n        url = reverse(\'api:noticia-create\')\n        data = {\'usuario\': usuario.pk, "titulo":"test", "subtitulo":"test", "descripcion":"test", "img": temporary_image()}\n        response = client.post(url, data,format="multipart")\n\n        ...\n
Run Code Online (Sandbox Code Playgroud)\n

所以,总而言之,问题是,\xc2\xbf如何从不同的目录中删除临时文件,考虑到这些文件必须严格上传到这些目录上?

\n

And*_*ker 3

为了进行测试,您可以使用dj-inmemorystorage包,Django 不会保存到磁盘。序列化器和模型仍将按预期工作,并且您可以根据需要读回数据。

在您的设置中,当您处于测试模式时,覆盖默认文件存储。您还可以在此处放置任何其他“测试模式”设置,只需确保它在其他设置之后最后运行即可。

if 'test' in sys.argv :
    # store files in memory, no cleanup after tests are finished
    DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage'
    # much faster password hashing, default one is super slow (on purpose)
    PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher']
Run Code Online (Sandbox Code Playgroud)

当您上传文件时,您可以使用SimpleUploadFile,它纯粹在内存中。这负责“客户端”端,而dj-inmemorystorage包则负责 Django 的存储。

def temporary_image():
    bts = BytesIO()
    img = Image.new("RGB", (100, 100))
    img.save(bts, 'jpeg')
    return SimpleUploadedFile("test.jpg", bts.getvalue())
Run Code Online (Sandbox Code Playgroud)