how to unit test file upload in django

后端 未结 11 1110
感动是毒
感动是毒 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:31

    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:

    from django.core.files.uploadedfile import SimpleUploadedFile
    
    def test_upload_video(self):
        video = SimpleUploadedFile("file.mp4", "file_content", content_type="video/mp4")
        self.client.post(reverse('app:some_view'), {'video': video})
        # some important assertions ...
    

    In Python 3.5+ you need to use bytes object instead of str. Change "file_content" to b"file_content"

    It's been working fine, SimpleUploadedFile creates an InMemoryFile that behaves like a regular upload and you can pick the name, content and content type.

提交回复
热议问题