如何模拟另一个模块中使用的 django 设置属性?
How to mock django settings attribute used in another module?
假设模块 a
代码:
from django.conf import settings
print settings.BASE_URL # prints http://example.com
在 tests.py
我想模拟 BASE_URL
到 http://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
以上的 None 有效。
尝试使用 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
您还可以在您的个人测试函数或整体测试 class 上使用以下装饰器。
@override_settings(BASE_URL='http://localhost')
假设模块 a
代码:
from django.conf import settings
print settings.BASE_URL # prints http://example.com
在 tests.py
我想模拟 BASE_URL
到 http://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
以上的 None 有效。
尝试使用 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
您还可以在您的个人测试函数或整体测试 class 上使用以下装饰器。
@override_settings(BASE_URL='http://localhost')