Django testing model with ImageField

后端 未结 8 1643
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 16:52

I need to test the Photo model of my Django application. How can I mock the ImageField with a test image file?

tests.py

class PhotoT         


        
8条回答
  •  隐瞒了意图╮
    2020-12-07 17:11

    You can do a few additional things to (1) avoid having to keep a dedicated test image around, and (2) ensure that all test files created during testing are deleted right after:

    import shutil
    import tempfile
    
    from django.core.files.uploadedfile import SimpleUploadedFile
    from django.test import TestCase, override_settings
    
    MEDIA_ROOT = tempfile.mkdtemp()
    
    @override_settings(MEDIA_ROOT=MEDIA_ROOT)
    class MyTest(TestCase):
    
        @classmethod
        def tearDownClass(cls):
            shutil.rmtree(MEDIA_ROOT, ignore_errors=True)  # delete the temp dir
            super().tearDownClass()
    
        def test(self):
            img = SimpleUploadedFile('test.jpg', b'whatevercontentsyouwant')
            # ^-- this will be saved in MEDIA_ROOT
            # do whatever ...
    

提交回复
热议问题