如何使用Django中的不同设置进行单元测试? [英] How to Unit test with different settings in Django?
问题描述
如果有人要更改设置,这有可能使我的测试失败。如何覆盖 setUp()
上的设置,然后在 tearDown()
上恢复它们?如果这是不可能的,有没有办法我可以猴子修补方法或模拟设置?
编辑:这是我的经理代码:
class LatestManager(models.Manager):
返回一个特定数量的
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
来切片查询。
编辑:如果要更改 特定测试的小数量的设置,则此答案适用。
自Django 1.4以来,在测试过程中有办法覆盖设置:
https://docs.djangoproject.com/en/dev/topics/testing/tools/#overriding-settings
TestCase将有一个self.settings上下文管理器,并且还将有一个@override_settings装饰器可以应用于测试方法或整个TestCase子类。
这些功能在Django 1.3中还不存在。
如果要更改所有测试的设置,您需要创建一个单独的设置文件进行测试,可以加载和覆盖从您的主设置文件设置。在其他答案中有几个很好的方法来实现;我看到 hspander的和 dmitrii的方法。
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.
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?
EDIT: Here is my manager code:
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]
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.
EDIT: This answer applies if you want to change settings for a small number of specific tests.
Since Django 1.4, there are ways to override settings during tests: https://docs.djangoproject.com/en/dev/topics/testing/tools/#overriding-settings
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.
These features did not exist yet in Django 1.3.
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屋!