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?
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.
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 ...
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.
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.
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})
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With