2

I have a form that I want to unittest:

app/form.py

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

app/test.py

class MyFormTest(TestCase):

    def test_my_form(self):
        file_mock = MagicMock(spec=File)
        form = MyForm({'file':file_mock})
        self.assertTrue(form.is_valid())

How can i unit test this form using mock or other was? If possible I would like to test this form using mock. How can I patch and mock test it?

SpiXel
  • 4,338
  • 1
  • 29
  • 45
Al-Alamin
  • 1,438
  • 2
  • 15
  • 34

2 Answers2

2

I found this solution from another source:

form = MyForm(files={'file':file_mock})

or

file_dict = {'file': SimpleUploadedFile(upload_file.name, upload_file.read())}
form = MyForm(files=file_dict)

This did the trick.

Al-Alamin
  • 1,438
  • 2
  • 15
  • 34
0
from django.core.files.uploadedfile import SimpleUploadedFile
 ...
def test_form(self):
        upload_file = open('path/to/file', 'rb')
        file_dict = {'file': SimpleUploadedFile(upload_file.name, upload_file.read())}
        form = MyForm(file_dict)
        self.assertTrue(form.is_valid())
  • This is not working. This shows asserts false is not true. It is even reading data from the file but the form validation is failing – Al-Alamin Sep 20 '16 at 09:26