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

时间:2018-05-04 07:59:02

标签: python django mocking patch pytest-django

VOUCHERED_PEOPLE中有base.py我需要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)

Attempt1:

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

这不起作用。 settings.VOUCHERED_PEOPLE是一个功能。我必须通过settings.VOUCHERED_PEOPLE()

执行它来获取虚拟

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

不是变更值

问题:
我哪里错了?

1 个答案:

答案 0 :(得分:2)

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

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

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

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