如何嘲笑的Django设置在另一个模块中使用的属性?

问题描述 投票:3回答:1

比方说,模块a代码:

from django.conf import settings
print settings.BASE_URL # prints http://example.com

tests.py我想嘲笑BASE_URLhttp://localhost

我曾尝试以下:

with mock.patch('django.conf.settings.BASE_URL', 'http://localhost'):
    pass

with mock.patch('a.settings.BASE_URL', 'http://localhost'):
    pass

from a import settings

with mock.patch.object(settings, 'BASE_URL', 'http://localhost'):
    pass

import a

with mock.patch.object(a.settings, 'BASE_URL', 'http://localhost'):
    pass

以上都不工作。

python mocking
1个回答
9
投票

尝试使用上下文管理器设置()内置Django的。

with self.settings(BASE_URL='http://localhost'):
    # perform your test

https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.SimpleTestCase.settings

© www.soinside.com 2019 - 2024. All rights reserved.