简体   繁体   English

带有 ImageField 的 Django 测试模型

[英]Django testing model with ImageField

I need to test the Photo model of my Django application.我需要测试我的 Django 应用程序的照片模型。 How can I mock the ImageField with a test image file?如何使用测试图像文件模拟 ImageField?

tests.py测试文件

class PhotoTestCase(TestCase):

    def test_add_photo(self):
        newPhoto = Photo()
        newPhoto.image = # ??????
        newPhoto.save()
        self.assertEqual(Photo.objects.count(), 1)

For future users, I've solved the problem.对于未来的用户,我已经解决了这个问题。 You can mock an ImageField with a SimpleUploadedFile instance.你可以嘲笑的ImageField一个SimpleUploadedFile实例。

test.py测试文件

from django.core.files.uploadedfile import SimpleUploadedFile

newPhoto.image = SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg')

You can use a temporary file, using tempfile .您可以使用临时文件,使用tempfile So you don't need a real file to do your tests.所以你不需要一个真实的文件来做你的测试。

import tempfile

image = tempfile.NamedTemporaryFile(suffix=".jpg").name

If you prefer to do manual clean-up, use tempfile.mkstemp() instead.如果您更喜欢手动清理,请改用tempfile.mkstemp()

Tell the mock library to create a mock object based on Django's File class告诉 mock 库基于 Django 的 File 类创建一个 mock 对象

import mock
from django.core.files import File

file_mock = mock.MagicMock(spec=File, name='FileMock')

and then use in your tests然后在你的测试中使用

newPhoto.image = file_mock

If you don't want to create an actual file in the filesystem, you can use this 37-byte GIF instead, small enough to a be a bytes literal in your code:如果你不想在文件系统中创建一个实际的文件,你可以使用这个 37 字节的 GIF 来代替,它小到可以在你的代码中成为一个字节文字:

from django.core.files.uploadedfile import SimpleUploadedFile

small_gif = (
    b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x00\x00\x00\x21\xf9\x04'
    b'\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02'
    b'\x02\x4c\x01\x00\x3b'
)
uploaded = SimpleUploadedFile('small.gif', small_gif, content_type='image/gif')

Solution:解决方案:

from StringIO import StringIO
# in python 3: from io import StringIO
from PIL import Image
from django.core.files.base import File

And create a static method in your TestCase class:并在您的 TestCase 类中创建一个静态方法:

@staticmethod
def get_image_file(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)):
    file_obj = StringIO()
    image = Image.new("RGB", size=size, color=color)
    image.save(file_obj, ext)
    file_obj.seek(0)
    return File(file_obj, name=name)

Example:例子:

instance = YourModel(name=value, image=self.get_image_file())

You can do a few additional things to (1) avoid having to keep a dedicated test image around, and (2) ensure that all test files created during testing are deleted right after:您可以做一些额外的事情来 (1) 避免必须保留专用的测试映像,以及 (2) 确保在测试期间创建的所有测试文件在以下之后立即删除:

import shutil
import tempfile

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, override_settings

MEDIA_ROOT = tempfile.mkdtemp()

@override_settings(MEDIA_ROOT=MEDIA_ROOT)
class MyTest(TestCase):

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(MEDIA_ROOT, ignore_errors=True)  # delete the temp dir
        super().tearDownClass()

    def test(self):
        img = SimpleUploadedFile('test.jpg', b'whatevercontentsyouwant')
        # ^-- this will be saved in MEDIA_ROOT
        # do whatever ...

My approach how to test model with no intention to pass any useful data:我的方法是如何在无意传递任何有用数据的情况下测试模型:

from django.core.files import File
SomeModel.objects.create(image=File(file=b""))

For someone to try upload-image test with python 3.xx对于有人尝试使用 python 3.xx 进行上传图像测试

I fix little with Maxim Panfilov's excellent answer to make more dummy image with independent name.我用 Maxim Panfilov 的出色答案修复了很少的问题,以制作更多具有独立名称的虚拟图像。

from io import BytesIO
from PIL import Image
from django.core.files.base import File

#in your TestCase class:
class TestClass(TestCase):
    @staticmethod
    def get_image_file(name, ext='png', size=(50, 50), color=(256, 0, 0)):
        file_obj = BytesIO()
        image = Image.new("RGBA", size=size, color=color)
        image.save(file_obj, ext)
        file_obj.seek(0)
        return File(file_obj, name=name)

    def test_upload_image(self):
        c= APIClient()
        image1 = self.get_image('image.png')
        image2 = self.get_image('image2.png')
        data = 
            { 
                "image1": iamge1,
                "image2": image2,
            }
        response = c.post('/api_address/', data ) 
        self.assertEqual(response.status_code, 201) 

If you use Factory Boy to generate your test data, that library handles this situation with an ImageField factory .如果您使用Factory Boy生成测试数据,该库会使用ImageField factory处理这种情况。

Here is a complete example.这是一个完整的例子。 I'm assuming that all of these files are in the same Django app.我假设所有这些文件都在同一个 Django 应用程序中。

models.py example:模型.py示例:

from django.db import models


class YourModel(models.Model):
    
    image = models.ImageField(upload_to="files/")

factories.py example: factory.py 示例:

import factory
from . import models


class YourModelFactory(factory.django.DjangoModelFactory):
    
    class Meta:
        model = models.YourModel
 
    image = factory.Django.ImageField()

tests.py example:测试.py示例:

from django import test    
from . import factories


class YourModelTests(test.TestCase):
    
    def test_image_model(self):
        yourmodel = factories.YourModelFactory()
        self.assertIsNotNone(yourmodel.image)

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

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