Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing a Django Form with a FileField

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?

like image 235
Jason Christa Avatar asked Mar 18 '10 21:03

Jason Christa


People also ask

How do you write unit test cases in Django?

Writing tests Django's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach. When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.

How do you write a test case in Django project?

To write a test you derive from any of the Django (or unittest) test base classes (SimpleTestCase, TransactionTestCase, TestCase, LiveServerTestCase) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in True or False values ...

What is unit testing in Django?

Unit Tests are isolated tests that test one specific function. Integration Tests, meanwhile, are larger tests that focus on user behavior and testing entire applications. Put another way, integration testing combines different pieces of code functionality to make sure they behave correctly.

How does Django do testing?

The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.


2 Answers

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}) 
like image 27
dragoon Avatar answered Sep 18 '22 21:09

dragoon


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()) 
like image 134
Jason Christa Avatar answered Sep 20 '22 21:09

Jason Christa