提供在运行测试时重写django设置的方法
django-override-settings的Python项目详细描述
django覆盖设置提供了一种在 Django测试。
override_settings类可以用作类或 方法decorator或作为上下文管理器临时重写 设置值。在每个测试用例完成后(使用它时 作为装饰器)或在上下文管理器退出之后,它重置 django.conf.settings中的值与以前的值相同。这样可以防止 悄悄进入并让每个测试用例在自己的环境中运行的副作用 沙箱。
这个包还提供了两个方便的函数(^{tt3})$ 以及without_apps)来修改INSTALLED_APPS以及 特殊对象(SETTING_DELETED)在没有给定对象的情况下运行测试 设置已定义。
当 django 1.4已经发布,因为它将带有一个内置的 override_settings。但对于那些保持1.4之前的代码库的人来说, 希望这个包裹能派上用场。
用法
如果您有一系列需要给定设置的测试,则可以 修饰类,每个测试用例都将使用该值。为了 示例:
from django.conf import settings from django.test import TestCase from override_settings import override_settings @override_settings(FOO="abc") class TestFoo(TestCase): def test_foo(self): self.assertEqual(settings.FOO, "abc")
或者你可以装饰一个单独的测试用例,并让它只应用于 方法:
@override_settings(BAR="123") class TestBar(TestCase): @override_settings(BAR="abc") def test_bar(self): self.assertEqual(settings.BAR, "abc") def test_bar_no_decoration(self): self.assertEqual(settings.BAR, "123")
您也可以将其用作上下文管理器:
class TestBar(TestCase): @override_settings(BAR="123") def test_bar(self): self.assertEqual(settings.BAR, "123") with override_settings(BAR="abc") self.assertEqual(settings.BAR, "abc") self.assertEqual(settings.BAR, "123")
要仅修改INSTALLED_APPS,请使用with_apps或 without_apps:
from override_settings import with_apps, without_apps class TestAppModifiers(TestCase): @with_apps('django.contrib.humanize') def test_humanize(self): # ... @without_apps('django.contrib.sites') def test_no_sites(self): # ...
要在没有设置的情况下运行测试,请使用SETTING_DELETED:
from override_settings import override_settings, SETTING_DELETED class TestMissingSetting(TestCase): @override_settings(CUSTOM_OPTION=SETTING_DELETED) def test_delete_custom_option(self): """ Useful to make sure a missing setting raises an Exception. """ self.assertRaises(AttributeError, getattr, settings, 'CUSTOM_OPTION')
要求
- django>;=1.2
谢谢
- Jannis Leidel对于original snippet和更新它的工作 在将测试用例作为Django proper的一部分进行装饰时工作。
- Joost Cassee对于SETTING_DELETED以及 with_apps和without_apps作为其django-analytical的一部分 项目。
联系人
如果你发现任何错误,请open a ticket。