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

时间:2016-09-14 07:51:36

标签: python django python-3.x django-forms django-testing

我有这样的表格:

# forms.py

class BookForm(forms.ModelForm):

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

字段类型: book_titleauthor CharField languagegenre CharField release_year ages IntegerField cover FileField # models.py ENGLISH = 'english' LANGUAGE_CHOICES = ( (ENGLISH, 'English'), ) ADVENTURE = 'adventure' GENRE_CHOICES = ( (ADVENTURE, 'Adventure'), ) 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 ,最后img = open('background') uploaded = SimpleUploadedFile(img.name, img.read()) {'cover': uploaded} 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

选择选项:

Python 3.5

现在:我想测试一下此表单,但我不知道如何测试Django 1.9.4,这是我的表单测试。

py.test

我试过了:     来自django.core.files.uploadedfile import SimpleUploadedFile

open('background.jpg')

这是我的错误:

FileNotFoundError: [Errno 2] No such file or directory: 'background.jpg'

注意:我使用mockfrom django.core.files import File import mock file_mock = mock.MagicMock(spec=File, name='FileMock') file_mock.name = 'test1.jpg' {'cover': file_mock} 并使用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} 不工作。 错误: {{1}} 我解决了这个问题

更新2:

我尝试使用{{1}}

{{1}}

我尝试使用{{1}}

{{1}}

我修复了我的图片路径。

2 个答案:

答案 0 :(得分:1)

我发现问题这是我的代码:

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

答案 1 :(得分:0)

您可以在存储库中创建一个文件,因此它在物理上存在,或者您模拟测试文件。

尝试THIS

修改

尝试传递完整路径

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