Задать вопрос

Тел: +7 965 3737 888

518

Просмотров

1

Ответов

Decorator and context manager to override settings

<h2>Overriding settings</h2>
<p>For testing purposes it's often useful to change a setting temporarily and revert to the original value after running the testing code. The following code doubles as a context manager and decorator. It's used like this:</p>
from django.test import TestCase
from whatever import override_settings

class LoginTestCase(TestCase):

    @override_settings(LOGIN_URL='/other/login/')
    def test_login(self):
        response = self.client.get('/sekrit/')
        self.assertRedirects(response, '/other/login/?next=/sekrit/')

<p>The decorator can also be applied to test case classes:</p>
from django.test import TestCase
from whatever import override_settings

class LoginTestCase(TestCase):

    def test_login(self):
        response = self.client.get('/sekrit/')
        self.assertRedirects(response, '/other/login/?next=/sekrit/')

LoginTestCase = override_settings(LOGIN_URL='/other/login/')(LoginTestCase)

<p>On Python 2.6 and higher you can also use the well known decorator syntax to
decorate the class:</p>
from django.test import TestCase
from whatever import override_settings

@override_settings(LOGIN_URL='/other/login/')
class LoginTestCase(TestCase):

    def test_login(self):
        response = self.client.get('/sekrit/')
        self.assertRedirects(response, '/other/login/?next=/sekrit/')

<p>Alternatively it can be used as a context manager:</p>
from django.test import TestCase
from whatever import override_settings

class LoginTestCase(TestCase):

    def test_login(self):
        with override_settings(LOGIN_URL='/other/login/'):
            response = self.client.get('/sekrit/')
            self.assertRedirects(response, '/other/login/?next=/sekrit/')

Вопрос полезен? Да0/Нет0
file_3323.py(1.2Кб)
None

Ответы (1):

Ответtartley:19.08.2011
Ответ полезен? Да0/Нет0

Hey. This is great, thanks.

Just to check I'm understanding correctly: The Django 1.2 docs specifically forbid changing settings anywhere other than in your settings files: https://docs.djangoproject.com/en/dev/topics/settings/#altering-settings-at-runtime

Is this because of the hazards of not undoing the changes that are wrought, thus leaving the application in an inconsistent state? (early-imported modules thing the settings say one thing, imports after your modification think the settings say another thing)

Does a snippet like this run the risk that any global state which depends on the modified settings, and is set within the scope of the context manager, will permanently be set to a value which is inconsistent with the rest of the application?

If so, presumably this can be avoided by not ever setting global state that depends on the values of settings - the settings should be referred to directly every time their value is needed.

Am I vaguely understanding correctly?