In my django app, I have a view which accomplishes file upload.The core snippet is like this
...
if (request.method == 'POST'):
if request.FILES.has_key('file'):
file = request.FILES['file']
with open(settings.destfolder+'/%s' % file.name, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
I would like to unit test the view.I am planning to test the happy path as well as the fail path..ie,the case where the request.FILES
has no key 'file' , case where request.FILES['file']
has None
..
How do I set up the post data for the happy path?Can somebody tell me?
I used to do the same
with open('some_file.txt') as fp:
but then I needed images, videos and other real files in the repo and also I was testing a part of a Django core component that is well tested, so currently this is what I have been doing:In Python 3.5+ you need to use
bytes
object instead ofstr
. Change"file_content"
tob"file_content"
It's been working fine,
SimpleUploadedFile
creates anInMemoryFile
that behaves like a regular upload and you can pick the name, content and content type.Hope this helps.