Unit Testing File Objects in Django with SimpleUploadedFile
SimpleUploadedFile
is undocumented, but referenced in the Django documentation.
To use SimpleUploadedFile
when unit testing a FileField
such as
from django.db import models
class MyModel(models.Model):
file = models.FileField(upload_to='somewhere')
Create a SimpleUploadedFile
with Model Bakery, for example, in a test:
from model_bakery import baker
from django.core.files.uploadedfile import SimpleUploadedFile
#... some other code ...
baker.make(
'myapp.MyModel',
# note that the file content must be bytes
file=SimpleUploadedFile('file.jpg', b"file_content", content_type='image/jpeg')
)
# ... some more code ...
You can now test code that references that file object.
Feedback?
Email us at enquiries@kinsa.cc.