zmbq
zmbq

Reputation: 39023

Initializing MEDIA_ROOT and the Django Storage before each test

As explained in this question, I'm trying to isolate file-system changes done in Django tests.

I'm basically changing settings.MEDIA_ROOT before the tests are run. Unfortunately, the Django storage class seems to be unaffected by it, so files are saved in the original location even though MEDIA_ROOT is pointing to another, temporary, directory.

How do I reinitialized the Django Storage system to reflect the new media root?

UPDATE: The problem is that the settings file is preloaded into a django.conf.Settings object, and any changes to settings.MEDIA_ROOT are not reflected in the preloaded instance. I still don't know how to overcome this problem.

Upvotes: 0

Views: 1072

Answers (2)

Thomas Orozco
Thomas Orozco

Reputation: 55253

You might want to use Django's built-in feature to override settings in tests. That's exactly what it's designed for.

Straight from the docs, notice with self.settings:

from django.test import TestCase

class LoginTestCase(TestCase):

    def test_login(self):

        # First check for the default behavior
        response = self.client.get('/sekrit/')
        self.assertRedirects(response, '/accounts/login/?next=/sekrit/')

        # Then override the LOGIN_URL setting
        with self.settings(LOGIN_URL='/other/login/'):
            response = self.client.get('/sekrit/')
            self.assertRedirects(response, '/other/login/?next=/sekrit/')

Upvotes: 1

zmbq
zmbq

Reputation: 39023

Turns out I just need to change both settings:

from django.conf import settings as django_settings
from project import settings

django_settings.MEDIA_ROOT = settings.MEDIA_ROOT = '....'

This fixes the problem.

Perhaps another problem is that I'm not using django.conf.settings throughout the system, but rather my own imported settings. I'll change that at some point.

Upvotes: 1

Related Questions