how to unit test file upload in django

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

    I do something like this for my own event related application but you should have more than enough code to get on with your own use case

    import tempfile, csv, os
    
    class UploadPaperTest(TestCase):
    
        def generate_file(self):
            try:
                myfile = open('test.csv', 'wb')
                wr = csv.writer(myfile)
                wr.writerow(('Paper ID','Paper Title', 'Authors'))
                wr.writerow(('1','Title1', 'Author1'))
                wr.writerow(('2','Title2', 'Author2'))
                wr.writerow(('3','Title3', 'Author3'))
            finally:
                myfile.close()
    
            return myfile
    
        def setUp(self):
            self.user = create_fuser()
            self.profile = ProfileFactory(user=self.user)
            self.event = EventFactory()
            self.client = Client()
            self.module = ModuleFactory()
            self.event_module = EventModule.objects.get_or_create(event=self.event,
                    module=self.module)[0]
            add_to_admin(self.event, self.user)
    
        def test_paper_upload(self):
            response = self.client.login(username=self.user.email, password='foz')
            self.assertTrue(response)
    
            myfile = self.generate_file()
            file_path = myfile.name
            f = open(file_path, "r")
    
            url = reverse('registration_upload_papers', args=[self.event.slug])
    
            # post wrong data type
            post_data = {'uploaded_file': i}
            response = self.client.post(url, post_data)
            self.assertContains(response, 'File type is not supported.')
    
            post_data['uploaded_file'] = f
            response = self.client.post(url, post_data)
    
            import_file = SubmissionImportFile.objects.all()[0]
            self.assertEqual(SubmissionImportFile.objects.all().count(), 1)
            #self.assertEqual(import_file.uploaded_file.name, 'files/registration/{0}'.format(file_path))
    
            os.remove(myfile.name)
            file_path = import_file.uploaded_file.path
            os.remove(file_path)
    

提交回复
热议问题