如何在 Django 中使用不同的设置进行单元测试? [英] How to Unit test with different settings in Django?
问题描述
是否有任何简单的机制来覆盖单元测试的 Django 设置?我的一个模型上有一个管理器,它返回特定数量的最新对象.它返回的对象数量由 NUM_LATEST 设置定义.
Is there any simple mechanism for overriding Django settings for a unit test? I have a manager on one of my models that returns a specific number of the latest objects. The number of objects it returns is defined by a NUM_LATEST setting.
如果有人要更改设置,这有可能使我的测试失败.如何覆盖 setUp()
上的设置并随后在 tearDown()
上恢复它们?如果这是不可能的,有什么方法可以修改方法或模拟设置吗?
This has the potential to make my tests fail if someone were to change the setting. How can I override the settings on setUp()
and subsequently restore them on tearDown()
? If that isn't possible, is there some way I can monkey patch the method or mock the settings?
这是我的经理代码:
class LatestManager(models.Manager):
"""
Returns a specific number of the most recent public Articles as defined by
the NEWS_LATEST_MAX setting.
"""
def get_query_set(self):
num_latest = getattr(settings, 'NEWS_NUM_LATEST', 10)
return super(LatestManager, self).get_query_set().filter(is_public=True)[:num_latest]
管理器使用 settings.NEWS_LATEST_MAX
对查询集进行切片.getattr()
仅用于在设置不存在时提供默认值.
The manager uses settings.NEWS_LATEST_MAX
to slice the queryset. The getattr()
is simply used to provide a default should the setting not exist.
推荐答案
如果您想更改少量特定测试的设置,则此答案适用.
This answer applies if you want to change settings for a small number of specific tests.
从 Django 1.4 开始,有多种方法可以在测试期间覆盖设置:https://docs.djangoproject.com/en/stable/topics/testing/tools/#overriding-settings
Since Django 1.4, there are ways to override settings during tests: https://docs.djangoproject.com/en/stable/topics/testing/tools/#overriding-settings
TestCase
将有一个 self.settings
上下文管理器,并且还有一个 @override_settings
装饰器,可以应用于测试方法或整个 TestCase
子类.
TestCase
will have a self.settings
context manager, and there will also be an @override_settings
decorator that can be applied to either a test method or a whole TestCase
subclass.
这些特性在 Django 1.3 中还不存在.
These features did not exist yet in Django 1.3.
如果您想更改所有测试的设置,您需要为测试创建一个单独的设置文件,该文件可以加载和覆盖主设置文件中的设置.在其他答案中有几种很好的方法;我已经看到 hspander's 和 dmitrii 的 方法.
If you want to change settings for all your tests, you'll want to create a separate settings file for test, which can load and override settings from your main settings file. There are several good approaches to this in the other answers; I have seen successful variations on both hspander's and dmitrii's approaches.
这篇关于如何在 Django 中使用不同的设置进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!