Django test FileField using test fixtures

前端 未结 5 1339
囚心锁ツ
囚心锁ツ 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:39

    I've written unit tests for an entire gallery app before, and what worked well for me was using the python tempfile and shutil modules to create copies of the test files in temporary directories and then delete them all afterwards.

    The following example is not working/complete, but should get you on the right path:

    import os, shutil, tempfile
    
    PATH_TEMP = tempfile.mkdtemp(dir=os.path.join(MY_PATH, 'temp'))
    
    def make_objects():
        filenames = os.listdir(TEST_FILES_DIR)
    
        if not os.access(PATH_TEMP, os.F_OK):
            os.makedirs(PATH_TEMP)
    
        for filename in filenames:
            name, extension = os.path.splitext(filename)
            new = os.path.join(PATH_TEMP, filename)
            shutil.copyfile(os.path.join(TEST_FILES_DIR, filename), new)
    
            #Do something with the files/FileField here
    
    def remove_objects():
        shutil.rmtree(PATH_TEMP)
    

    I run those methods in the setUp() and tearDown() methods of my unit tests and it works great! You've got a clean copy of your files to test your filefield that are reusable and predictable.

提交回复
热议问题