Search code examples
djangounit-testingfile-upload

how to unit test file upload in django


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?


Solution

  • From Django docs on Client.post:

    Submitting files is a special case. To POST a file, you need only provide the file field name as a key, and a file handle to the file you wish to upload as a value. For example:

    c = Client()
    with open('wishlist.doc') as fp:
      c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})