views:

249

answers:

2

I have a form like:

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

How do I construct the *file_dict* to pass *upload_file* to the form?

A: 

May be this is not quite correct, but I'm creating image file in unit test using StringIO:

imgfile = StringIO('GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00'
                     '\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;')
imgfile.name = 'test_img_file.gif'

response = self.client.post(url, {'file': imgfile})
dragoon
I am try to test the form separately from the view. Actually, I haven't even made the view yet.
Jason Christa
Ok, seems that SimpleUploadedFile is a quite clear solution for testing
dragoon
+3  A: 

So far I have found this way that works

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