简体   繁体   English

如何在Django中使用FileField测试表单?

[英]How can I test a form with FileField in Django?

I have this form: 我有这样的形式:

# forms.py

class BookForm(forms.ModelForm):

    class Meta:
        model = Book
        fields = ['book_title', 'language', 'author', 'release_year', 'genre', 'ages', 'cover']

Type of fields: Where book_title and author are CharField , language and genre are too CharField but for them I have choice option, release_year and ages are IntegerField , and the last cover are FileField . 字段类型:book_titleauthorCharFieldlanguagegenre都太CharField但对他们我有选择的选项, release_yearagesIntegerField ,最后coverFileField

Choice Options: 选择选项:

# models.py
ENGLISH = 'english'
LANGUAGE_CHOICES = (
    (ENGLISH, 'English'),
)

ADVENTURE = 'adventure'
GENRE_CHOICES = (
    (ADVENTURE, 'Adventure'),
)

Now: I want to test this form, but I don't know how can test cover , here is my form test. 现在:我想测试这个表单,但我不知道如何测试cover ,这里是我的表单测试。

# test_forms.py
from .. import forms
from django.core.files import File


class TestBookForm:
    def test_form(self):
        form = forms.BookForm(data={})
        assert form.is_valid() is False, 'Should be invalid if no data is given'

        img = File(open('background'))

        data = {'book_title': 'Lord Of The Rings',
                'language': 'english',
                'author': 'J. R. R. Tolkien',
                'release_year': 1957,
                'genre': 'adventure',
                'ages': 16,
                'cover': img}

        form = forms.BookForm(data=data)

        assert form.is_valid() is True

I tried: from django.core.files.uploadedfile import SimpleUploadedFile 我试过:从django.core.files.uploadedfile导入SimpleUploadedFile

img = open('background')
uploaded = SimpleUploadedFile(img.name, img.read())
{'cover': uploaded}

This is my error: 这是我的错误:

E       assert False is True
E        +  where False = <bound method BaseForm.is_valid of <BookForm bound=True, valid=False, fields=(book_title;language;author;release_year;genre;ages;cover)>>()
E        +    where <bound method BaseForm.is_valid of <BookForm bound=True, valid=False, fields=(book_title;language;author;release_year;genre;ages;cover)>> = <BookForm bound=True, valid=False, fields=(book_title;language;author;release_year;genre;ages;cover)>
.is_valid

NOTE: I use Python 3.5 , Django 1.9.4 and I start test using py.test . 注意:我使用Python 3.5Django 1.9.4并使用py.test开始测试。

UPDATE: If i try open('background.jpg') don't work. 更新:如果我尝试open('background.jpg')不工作。 Error: FileNotFoundError: [Errno 2] No such file or directory: 'background.jpg' I fix this 错误: FileNotFoundError: [Errno 2] No such file or directory: 'background.jpg' 我解决了这个问题

UPDATE 2: 更新2:

I try to use mock 我尝试使用mock

from django.core.files import File
import mock

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

{'cover': file_mock}

I try to use InMemoryUploadedFile 我尝试使用InMemoryUploadedFile

from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
from PIL import Image

im = Image.new(mode='RGB', size=(200, 200))  # create a new image using PIL
im_io = BytesIO()  # a StringIO object for saving image
im.save(im_io, 'JPEG')  # save the image to im_io
im_io.seek(0)  # seek to the beginning

image = InMemoryUploadedFile(
    im_io, None, 'random-name.jpg', 'image/jpeg', None, None
)

{'cover': image}

I fix the path to my image. 我修复了我的图像的路径。

I find the problem This is my code: 我发现问题这是我的代码:

#test_forms.py
from .. import forms
from django.core.files.uploadedfile import SimpleUploadedFile
import os

TEST_DIR = os.path.dirname(os.path.abspath(__file__))
TEST_DATA_DIR = os.path.join(TEST_DIR, 'data')


class TestBookForm:
    def test_form(self):
        form = forms.BookForm(data={})
        assert form.is_valid() is False, 'Should be invalid if no data is given'

        test_image_path = os.path.join(TEST_DATA_DIR, 'background.jpg')

        data = {'book_title': 'Lord Of The Rings',
                'language': 'english',
                'author': 'J. R. R. Tolkien',
                'release_year': 1957,
                'genre': 'adventure',
                'ages': 16}

        with open(test_image_path, 'rb') as f:
            form = forms.BookForm(data=data, files={'cover': SimpleUploadedFile('cover', f.read())})
            assert form.is_valid(), 'Invalid form, errors: {}'.format(form.errors)

More info in the docs 更多信息在文档中

Either you create a file in your repository, so it is there physically, or you mock your test for your file. 您可以在存储库中创建一个文件,因此它在物理上存在,或者您为您的文件模拟测试。

Try THIS 试试这个


EDIT 编辑

Try to pass full path 尝试传递完整路径

import os
from django.conf import settings
file_path = os.path.join(settings.BASE_DIR, your_folder, background.jpg)

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

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