如何在测试时覆盖 app_settings

How to override app_settings while testing

好的,我有

settings.py

SETTING1='value'
SETTING2='value'

之后我们意识到这些设置 SETTING1SETTING2 更具体到 app1 所以我们添加了它们 apps.py

from django.apps import AppConfig


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

并用views.py

称呼他们
app_settings = apps.get_app_config('ex_app')
app_settings.SETTING1

根据Django documentation

那么我怎样才能在测试时用 override_settings 覆盖它们 @override_settings 我尝试使用@patch 来修补配置应用程序但失败了

您可以只模拟应用配置的一个属性:

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)