Skip to main content
 首页 » 编程设计

python之使用本地设置的 Django 测试

2025年05月04日32linjiqin

python 2.7 Django 1.2

我在测试 Django 应用程序时遇到奇怪的 local_settings 行为。我有我的 <project>/settings.py像这样设置:

DEBUG = False 
TEMPLATE_DEBUG = DEBUG 
 
ADMINS = ( 
        ("Me", "me@me.com"), 
) 
 
MANAGERS = ADMINS + (('Person1', 'person1@blah.com'),) 
 
# ... rest of settings 
 
try: 
    from local_settings import * 
except ImportError: 
    pass 

并在<project>/local_settings.py我有:

DEBUG = True 
 
MANAGERS = ( 
        ('Me', 'me@me.com'), 
) 

因此,在本地工作时,MANAGERS设置应为 (('Me', 'me@me.com'),) , 和 DEBUG应设置为 True .

但是,在我的一个应用程序的测试中,我正在测试 settings.DEBUG并得到 False ,但是 MANAGERS设置设置正确(其中只有“我”)。为什么会发生这种情况的任何想法?以下是 <project>/<app>/tests.py 的相关部分文件:

from django.conf import settings 
from django.test import TestCase 
 
# ... 
class MyTests(TestCase): 
    def mytest(self): 
        if settings.DEBUG: 
            self.assertEqual(settings.MANAGERS, (('Me', 'me@me.com'),)) 
        else: 
            self.assertEqual(settings.MANAGERS, (('Me', 'me@me.com'), ('Person1', 'person1@blah.com'))) 

结果是

AssertionError: (('Me', 'me@me.com'),) != (('Me', 'me@me.com'), ('Person1', 'person1@blah.com')) 

所以看起来它正在测试 else由于 settings.DEBUG 的分支设置不正确,然后提高 AssertionError自 settings.MANAGERS设置正确。

如果我运行 python manage.py shell我明白了:

>>> from django.conf import settings 
>>> settings.DEBUG 
True 
>>> settings.MANAGERS 
(('Me', 'me@me.com'),) 

所以它们在那里设置正确。

我知道我可以在测试中手动覆盖设置,但我想尝试使用 settings.DEBUG这样无论是在本地运行还是在生产环境中,测试都会通过。

有什么想法吗?

请您参考如下方法:

这是 Django 中的一个有意选择:

Regardless of the value of the DEBUG setting in your configuration file, all Django tests run with DEBUG=False. This is to ensure that the observed output of your code matches what will be seen in a production setting.

引用:https://docs.djangoproject.com/en/dev/topics/testing/#other-test-conditions