Login

change settings locally in an individual test

Author:
akaihola
Posted:
August 19, 2010
Language:
Python
Version:
Not specified
Tags:
settings testing unittest
Score:
1 (after 1 ratings)

So you need to change some settings when running an individual test in a test case. You could just wrap the test between old_value = settings.MY_SETTING and settings.MY_SETTING = old_value. This snippet provides a helper which makes this a bit more convenient, since settings are restored to their old values automatically.

Example usage:

class MyTestCase(TestCase):

    def test_something(self):
        with patch_settings(MY_SETTING='my value',
                            OTHER_SETTING='other value'):
            do_my_test()
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from contextlib import contextmanager

class SettingDoesNotExist:
    pass

@contextmanager
def patch_settings(**kwargs):
    from django.conf import settings
    old_settings = []
    for key, new_value in kwargs.items():
        old_value = getattr(settings, key, SettingDoesNotExist)
        old_settings.append((key, old_value))
        setattr(settings, key, new_value)
    yield
    for key, old_value in old_settings:
        if old_value is SettingDoesNotExist:
            delattr(settings, key)
        else:
            setattr(settings, key, old_value)

More like this

  1. TestCase base class to easily temporarily change module values by SmileyChris 5 years ago
  2. TestSettingsManager: temporarily change settings for tests by carljm 6 years, 11 months ago
  3. Run a testcase with custom INSTALLED_APPS by vdboor 2 years, 8 months ago
  4. Add a print link to the admin to print individual record by jimmylam 6 years, 8 months ago
  5. Decorator and context manager to override settings by jezdez 4 years, 2 months ago

Comments

Please login first before commenting.