Login

change settings locally in an individual test

Author:
akaihola
Posted:
August 19, 2010
Language:
Python
Version:
Not specified
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 4 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.