Search code examples
djangotestingdjango-settings

How to override app_settings while testing


Okay now, I have

settings.py

SETTING1='value'
SETTING2='value'

After that we realized that these settings SETTING1 and SETTING2 are more specified to app1 So we've added them apps.py

from django.apps import AppConfig


class EXAPPConfig(AppConfig):
    name = 'EXAPPConfig'
    verbose_name = "EXAPPConfig"
    SETTING1 = 'value'
    def ready(self):
        pass

and call them withviews.py

app_settings = apps.get_app_config('ex_app')
app_settings.SETTING1

according to Django documentation

So how can I override them with override_settings at tests @override_settings I tried @patch to patch the config app but failed


Solution

  • You can mock only an attribute of your app config with this:

    from unittest.mock import patch
    
    from django.apps import apps
    from django.test import TestCase
    
    
    class EXAPPTest(TestCase):
        def test_mocking_app_config(self):
            original = apps.get_app_config('ex_app').SETTING1
            with patch.object(apps.get_app_config('ex_app'), 'SETTING1', new='definitely-not-original'):
                mocked = apps.get_app_config('ex_app').SETTING1
            self.assertNotEqual(original, mocked)