Django test FileField using test fixtures

前端 未结 5 1351
囚心锁ツ
囚心锁ツ 2020-12-25 11:52

I\'m trying to build tests for some models that have a FileField. The model looks like this:

class SolutionFile(models.Model):
    \'\'\'
    A file from a s         


        
5条回答
  •  清歌不尽
    2020-12-25 12:23

    This is what I did for my test. After uploading the file it should end up in the photo property of my organization model object:

        import tempfile
        filename = tempfile.mkstemp()[1]
        f = open(filename, 'w')
        f.write('These are the file contents')
        f.close()
        f = open(filename, 'r')
        post_data = {'file': f}
        response = self.client.post("/org/%d/photo" % new_org_data["id"], post_data)
        f.close()
        self.assertEqual(response.status_code, 200)
    
        ## Check the file
        ## org is where the file should end up
        org = models.Organization.objects.get(pk=new_org_data["id"])
        self.assertEqual("These are the file contents", org.photo.file.read())
    
        ## Remove the file
        import os
        os.remove(org.photo.path)
    

提交回复
热议问题