在 Django 中使用 ImageField 进行单元测试

Unit test form with ImageField in django

我有 ImageField 的模型。我正在尝试将 unit test 写入我的表单,但它总是会引发错误。有人能告诉我我错在哪里吗?

根据错误,我了解到该表格无效。 print str(form.errors) return 我这个:

<ul class="errorlist"><li>image<ul class="errorlist"><li>This field is required.</li></ul></li></ul>

错误:

Traceback (most recent call last):
  File "/home/nurzhan/CA/slider/tests.py", in test_form_valid
    self.assertTrue(form.is_valid())
AssertionError: False is not true

tests.py:

def test_form_valid(self):
        self.image_file = open(
            os.path.join(BASE_DIR, 'static/images/test.jpg'), "rb"
        )
        data = {
            'title': 'TEST',
        }
        image_data = {
            'image': self.file_valid
        }
        form = SlideForm(data=data, files=image_data)
        self.assertTrue(form.is_valid())

print data return 我:

{'image': <open file '/home/nurzhan/CA/static/images/test.jpg', mode 'rb' at 0x7efe24b47b70>}

我也试过用这个:

data = {
    'image': SimpleUploadedFile(
        self.image_file.name,
        self.image_file.read()
    )
}

这样的话print datareturn我{'image': <SimpleUploadedFile: test.jpg (text/plain)>}

forms.py:

class ArticleForm(forms.ModelForm):
    class Meta:
    model = Article
    fields = ('image',)

def __init__(self, *args, **kwargs):
    super(SlideForm, self).__init__(*args, **kwargs)
    self.fields['image'].widget.attrs = {
        'accept': 'image/png, image/jpeg, image/gif',
        'id': 'image',
    }

models.py:

from django.db.models.signals import pre_save
from django.dispatch import receiver

class Article(models.Model):
    image = models.ImageField(
        upload_to='article/images/%Y/%m/%d/',
        blank=False,
    )


@receiver(pre_save, sender=Article)
def delete_old_article_image(sender, instance, *args, **kwargs):
    if instance.pk:
        article = article.objects.get(pk=instance.pk)
        if instance.image and article.image != instance.image:
            article.image.delete(False)

答案:

当前的单元测试是:

  def test_form_valid(self):
        data = {
            'title': 'TEST',
        }
        files_data = {
            'image': SimpleUploadedFile(
                self.image_file.name,
                self.image_valid.read()
            )
        }
        form = ArticleForm(data=data, files=files_data)
        self.assertTrue(form.is_valid())

我查阅了 Django 的源代码,发现了这个: https://github.com/django/django/blob/master/django/forms/forms.py#L74-L76

您可能需要将文件作为 files=data.

传递

祝你好运!