【问题标题】:How to mock django settings attribute used in another module?如何模拟另一个模块中使用的 django 设置属性?
【发布时间】:2016-08-05 07:35:12
【问题描述】:

假设模块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】:

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

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

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

【讨论】:

    【解决方案2】:

    您还可以在您的单个测试函数或整个测试类上使用以下装饰器。

    @override_settings(BASE_URL='http://localhost')
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 2014-04-09
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多