Search code examples
djangoformsmockingfilefielddjango-unittest

Django mock unit test form filefield


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?


Solution

  • 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.