在django中使用ImageField的单元测试表

时间:2017-09-15 07:10:25

标签: python django python-2.7 unit-testing django-1.11

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

从错误中我知道表单无效。 print str(form.errors)让我回复:

<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回复我:

{'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 data会返回{'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)

解答:

Corrent单元测试是:

  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())

1 个答案:

答案 0 :(得分:2)

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

您可能需要将文件作为files=data传递。

祝你好运!