English 中文(简体)
原标题:Unit Testing a Django Form with a FileField

我有这样的形式:

#forms.py
from django import forms

class MyForm(forms.Form):
    title = forms.CharField()
    file = forms.FileField()


#tests.py
from django.test import TestCase
from forms import MyForm

class FormTestCase(TestCase)
    def test_form(self):
        upload_file = open( path/to/file ,  r )
        post_dict = { title :  Test Title }
        file_dict = {} #??????
        form = MyForm(post_dict, file_dict)
        self.assertTrue(form.is_valid())

我如何将file_dict改为upload_file

最佳回答

到目前为止,我已经找到了这一办法。

from django.core.files.uploadedfile import SimpleUploadedFile
 ...
def test_form(self):
        upload_file = open( path/to/file ,  rb )
        post_dict = { title :  Test Title }
        file_dict = { file : SimpleUploadedFile(upload_file.name, upload_file.read())}
        form = MyForm(post_dict, file_dict)
        self.assertTrue(form.is_valid())
问题回答

也许这并不完全正确,但我会利用斯特林国际组织在单位测试中制造图像档案:

imgfile = StringIO( GIF87ax01x00x01x00x80x01x00x00x00x00ccc,x00 
                      x00x00x00x01x00x01x00x00x02x02Dx01x00; )
imgfile.name =  test_img_file.gif 

response = self.client.post(url, { file : imgfile})

这里还有另一种方式要求你使用实际形象。

EDIT: 更新3版。

from PIL import Image
from io import BytesIO # Python 2: from StringIO import StringIO
from django.core.files.uploadedfile import InMemoryUploadedFile

...

def test_form(self):
    im = Image.new(mode= RGB , size=(200, 200)) # create a new image using PIL
    im_io = BytesIO() # a BytesIO 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 , len(im_io.getvalue()), None
    )

    post_dict = { title :  Test Title }
    file_dict = { picture : image}

    form = MyForm(data=post_dict, files=file_dict)

接受的答案是 down倒的,即你总是必须在你的环境中保存一个用于检测的 du子。

假设你在团队或生产中工作,这并不是非常好的做法。 对我来说,@xyres办法似乎比较清洁。 可进一步简化。

http://docs.python.org/3/library/io.html“rel=“nofollow noreferer” 这里指的是:

loaded_file = BytesIO(b"some dummy bcode data: x00x01")
loaded_file.name =  test_file_name.xls 

# and to load it in form
file_dict = { file : SimpleUploadedFile(loaded_file.name, loaded_file.read())}

Full version

# Python3
from io import BytesIO
from django.core.files.uploadedfile import SimpleUploadedFile

class FormTestCase(TestCase)
    def test_form(self):
        # Simple and Clear
        loaded_file = BytesIO(b"some dummy bcode data: x00x01")
        loaded_file.name =  test_file_name.xls 

        post_dict = { title :  Test Title }
        file_dict = { file : SimpleUploadedFile(loaded_file.name, loaded_file.read())}
        form = MyForm(post_dict, file_dict)
        self.assertTrue(form.is_valid())

It is also advised to utilize setUpTestData(cls) and setUp(self) class methods for data preparation. I personally found Mozilla s intro to unit testing very informative and straightforward.

这里和其他Stack哨所用3号合并了几个想法。 不需要外部档案或图书馆。

from django.core.files.uploadedfile import SimpleUploadedFile

png_hex = [ x89 ,  P ,  N ,  G ,  
 ,  
 ,  x1a ,  
 ,  x00 ,
            x00 ,  x00 ,  
 ,  I ,  H ,  D ,  R ,  x00 ,
            x00 ,  x00 ,  x01 ,  x00 ,  x00 ,  x00 ,  x01 ,
            x08 ,  x02 ,  x00 ,  x00 ,  x00 ,  x90 ,
            w ,  S ,  xde ,  x00 ,  x00 ,  x00 ,  x06 ,  b ,  K ,
            G ,  D ,  x00 ,  x00 ,  x00 ,  x00 ,
            x00 ,  x00 ,  xf9 ,  C ,  xbb ,  x7f ,  x00 ,  x00 ,
            x00 ,  	 ,  p ,  H ,  Y ,  s ,  x00 ,
            x00 ,  x0e ,  xc3 ,  x00 ,  x00 ,  x0e ,  xc3 ,
            x01 ,  xc7 ,  o ,  xa8 ,  d ,  x00 ,  x00 ,
            x00 ,  x07 ,  t ,  I ,  M ,  E ,  x07 ,  xe0 ,  x05 ,
            
 ,  x08 ,  % ,  / ,  xad ,  + ,  Z ,
            x89 ,  x00 ,  x00 ,  x00 ,  x0c ,  I ,  D ,  A ,  T ,
            x08 ,  xd7 ,  c ,  xf8 ,  xff ,  xff ,
            ? ,  x00 ,  x05 ,  xfe ,  x02 ,  xfe ,  xdc ,  xcc ,
            Y ,  xe7 ,  x00 ,  x00 ,  x00 ,  x00 ,
            I ,  E ,  N ,  D ,  xae ,  B ,  ` ,  x82 ]

valid_png_bin = str.encode("".join(png_hex))
png = SimpleUploadedFile("test.png", valid_png_bin)

post_dict = { title :  Test Title }
file_dict = { picture : png}

form = MyForm(data=post_dict, files=file_dict)




相关问题
run unit tests and coverage in certain python structure

I have some funny noob problem. I try to run unit tests from commandline: H:PROpyEstimator>python src estpython est_power_estimator.py Traceback (most recent call last): File "src est...

How to unit-test an enterprise symfony project?

I´m working on a huge project at my work. We have about 200 database tables, accordingly a huge number of Models, Actions and so on. How should I begin to write tests for this? My biggest problem ...

Code Coverage Tools & Visual Studio 2008 Pro

Just wondering what people are using for code coverage tools when using MS Visual Studio 2008 Pro. We are using the built-in MS test project and unit testing tool (the one that come pre-installed ...

Unit testing. File structure

I have a C++ legacy codebase with 10-15 applications, all sharing several components. While setting up unittests for both shared components and for applications themselves, I was wondering if there ...

Unit Testing .NET 3.5 projects using MStest in VS2010

There s a bug/feature in Visual Studio 2010 where you can t create a unit test project with the 2.0 CLR. https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=483891&wa=...

Unit Test for Exceptions Message

Is there a simple (Attribute-driven) way to have the following test fail on the message of the exception. [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void ExceptionTestTest() ...

热门标签