1

I am trying to find the cleanest way of testing ImageField in Django, without polluting or affecting in anyway the MEDIA_ROOT folder (even for local development purposes). Currently, my code is this:

models.py:

class Image:

def __init__(self, path):
    self.path = path
    with PilImage.open(path) as f:
        self.pil = f

tests.py:

class MyTest(TestCase):

    @classmethod
    @override_settings(MEDIA_ROOT=tempfile.gettempdir())
    def setUpTestData(cls):
       temp_image = get_temporary_image()
       cls.image = Image(path=temp_image.name) # Error

And the code for get_temporary_image

import tempfile
from PIL import Image


def get_temporary_image():
    temp_file = tempfile.NamedTemporaryFile()

    size = (200, 200)
    color = (255, 0, 0, 0)
    image = Image.new("RGB", size, color)
    image.save(temp_file, 'jpeg')
    return temp_file

When I run my test, the setUpTestData method yields error saying:

Traceback (most recent call last): File "C:\Users\Edgar\venvs\image-resize\lib\site-packages\django\test\testcases.py", line 1137, in setUpClass cls.setUpTestData() File "C:\Users\Edgar\Desktop\test_tasks\image-resize\upload\tests\test_model_image.py", line 21, in setUpTestData cls.image = Image(path=temp_image.name) File "C:\Users\Edgar\Desktop\test_tasks\image-resize\upload\models.py", line 55, in init with PilImage.open(path) as f: File "C:\Users\Edgar\venvs\image-resize\lib\site-packages\PIL\Image.py", line 2843, in open fp = builtins.open(filename, "rb") PermissionError: [Errno 13] Permission denied: 'C:\Users\Edgar\AppData\Local\Temp\tmp3nwytxx0'

I spent 4 hours trying to figure out what I am doing wrong, but all in vain.

Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

0 Answers0