补丁 django.conf 设置不会改变值

patch django.conf settings does not mutate the value

我在 base.py 中有 VOUCHERED_PEOPLE 我需要通过 dummy 测试它 我已经阅读了 this 以便对 settings.VOUCHERED_PEOPLE 进行修补,但它在 Django2

中不起作用

utils.py

from django.conf import settings
def get_voucher_people(mobile_phone: str) -> typing.Dict[str, typing.Union[str, int]]:
    """Read name from base.py"""
    for record in settings.VOUCHERED_PEOPLE:
        if record['mobile_phone'] == mobile_phone:
            return record
    return None

base.py

VOUCHERED_PEOPLE = [{...}, {...}]

tests.py

with patch('poinkbackend.apps.vouchers.utils.settings', VOUCHERED_PEOPLE=dummy):
    from pprint import pprint
    import ipdb;
    ipdb.set_trace()
    give_voucher(sarit.userprofile, True)

尝试 1:

with patch.object(settings, 'VOUCHERED_PEOPLE') as mock_settings:
    mock_settings.return_value = dummy

这不起作用。 settings.VOUCHERED_PEOPLE 是一个函数。我必须执行它才能通过 settings.VOUCHERED_PEOPLE()

获得虚拟

问题:
补丁不起作用。我的 dummy

不是更改值

问题:
我哪里错了?

有一个特定的 context manager 用于在测试中修改设置:

with self.settings(VOUCHERED_PEOPLE=dummy):
    ...

有了pytest-django,可以use settings as a fixture直接修改;它将在每次测试结束时恢复。

def test_vouchered_people(settings):
    settings.VOUCHERED_PEOPLE=dummy
    ...