Test a Django model with a FileField

How to unit test a Django model, form or view with a FileField

Posted Jan. 14, 2019

How to unit test a Django model with a FileField

If you want to unit test a model that has a FileField in it, there is no need to do it with a real file, you can use MagicMock.

Let's say your model looks like this:

And if you want to test if file field contains a file when you create an instance of the model, you can test it like this:

With MagicMock we can emulate the behavior of a Django File through its spec parameter.

How to unit test a Django CreateView with a FileField

If you have a CreateView for a model which contains a FileField, and you want to add some functionality when the form is valid, it will look like this:

In order to unit test the function form_valid it requires the form as parameter. We didn't define it because we are using a CreateView with a model and its fields to define the form we want to render.

To be able to unit test it, is better if we define the form and we use it in the Class Based View as form_class

The unit test for this view will look like this: