how to unit test file upload in django

后端 未结 11 1105
感动是毒
感动是毒 2020-12-02 07:09

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_         


        
11条回答
  •  孤城傲影
    2020-12-02 07:40

    As mentioned in Django's official documentation:

    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})
    

    More Information: How to check if the file is passed as an argument to some function?

    While testing, sometimes we want to make sure that the file is passed as an argument to some function.

    e.g.

    ...
    class AnyView(CreateView):
        ...
        def post(self, request, *args, **kwargs):
            attachment = request.FILES['attachment']
            # pass the file as an argument
            my_function(attachment)
            ...
    

    In tests, use Python's mock something like this:

    # Mock 'my_function' and then check the following:
    
    response = do_a_post_request()
    
    self.assertEqual(mock_my_function.call_count, 1)
    self.assertEqual(
        mock_my_function.call_args,
        call(response.wsgi_request.FILES['attachment']),
    )
    

提交回复
热议问题