0

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.

Community
  • 1
  • 1
zmbq
  • 38,013
  • 14
  • 101
  • 171

2 Answers2

1

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.

zmbq
  • 38,013
  • 14
  • 101
  • 171
1

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/')
Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
  • Ooooh, that seems like a good idea! I'll add that in my setUp() method and clean up in tearDown()! – zmbq Feb 23 '14 at 14:19
  • @zmbq Be careful, this is a [context manager](http://legacy.python.org/dev/peps/pep-0343/) so it will not work with `setUp` and `tearDown`. The change to `settings` is only active while you're "inside the indented block". – Thomas Orozco Feb 23 '14 at 14:31
  • I'm pretty sure I can call `self.settings(...)` in setUp, save the resulting context and close it in tearDown. However, it's not enough because of the problem I mentioned in my original question - I also need to change the MEDIA_ROOT from the test runner, to avoid problems when people forget to call setUp. – zmbq Feb 23 '14 at 14:35