18👍
You should override the whole dict:
@override_settings(SETTING_DICT={'key': True})
def test_something(self):
...
Or, you can use override_settings
as a context manager:
def test_something(self):
value = settings.SETTING_DICT
value['key'] = True
with override_settings(SETTING_DICT=value):
...
8👍
Since Python 3.3, you may use collections.Chainmap
if you wand to override specific values in the dict (or other mapping) object using decorator and keep code clean from context manager.
https://docs.python.org/3/library/collections.html#collections.ChainMap
from collections import ChainMap
@override_settings(SETTING_DICT=ChainMap({'key': 'value'}, settings.SETTING_DICT))
def test_something(self):
...
The above will not override whole dict, and all other values in SETTINGS_DICT
will be available.
For Python 2.7 you may use backport, which contains Chainmap
implementation.
https://pypi.org/project/chainmap/
2👍
I didn’t want to override the whole dict either, so I copied the dictionary in question from the settings
object and just modified the attribute I was interested in:
import copy
from django.conf import settings
settings_dict = copy.deepcopy(settings.SETTINGS_DICT)
settings_dict['key1']['key2'] = 'new value'
@override_settings(SETTINGS_DICT=settings_dict)
def test_something(self):
pass
It suits my purposes, but if you wanted to make this more widely usable, you could write a short function with a few arguments which could do something like this dynamically.
Note: I tried using settings.SETTINGS_DICT.copy()
instead of copy.deepcopy(settings.SETTINGS_DICT)
but that seemed to globally override the setting for all tests.
- How to describe parameters in DRF Docs
- Django models across multiple projects/microservices. How to?
- How can I test whether Django is running in debug mode?
0👍
Simplest solution for me (works with python 3.6):
@override_settings(SETTINGS_DICT={**SETTINGS_DICT, 'yournewkey': yournewvalue})
- How passing string on filter keyword to Django Objects Model?
- Could not import 'oauth2_provider.ext.rest_framework.OAuth2Authentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
- Can't install python mysql library on Mac Mavericks
- Can not create South database models in Django 1.7