我想测试一个带有自己的设置模块的小型可重用应用程序。在应用程序的设置中访问全局(项目)设置以支持变量覆盖,例如
# in <my_app>/settings.py
from django.conf import settings
MY_SETTING_VAR = getattr(settings, 'MY_OVERRIDDEN_VAR', False)
当我使用 manage.py test myapp 运行测试时,我得到以下内容:
ImportError:无法导入设置,因为环境 变量DJANGO_SETTINGS_MODULE未定义。
在这种情况下运行测试的正确方法是什么?
答案 0 :(得分:1)
我不确定,我测试了你发布的内容,它对我有用:
<<< 12:18.25 Fri Feb 24 2012!~/testproject
<<< jpic@germaine!10019 env
>>> ./manage.py test testapp
Creating test database for alias 'default'...
Destroying old test database 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Destroying test database for alias 'default'...
<<< 12:18.27 Fri Feb 24 2012!~/testproject
<<< jpic@germaine!10020 env
>>> cat testapp/tests.py
from django.test import TestCase
from .settings import *
class SomeTestCase(TestCase):
def testSomething(self):
self.assertEqual(MY_SETTING_VAR, 'default')
<<< 12:18.30 Fri Feb 24 2012!~/testproject
<<< jpic@germaine!10021 env
>>> cat testapp/settings.py
from django.conf import settings
MY_SETTING_VAR = getattr(settings, 'MY_OVERRIDDEN_VAR', 'default')
您希望确保您的实际代码符合此工作代码。
应用程序包含演示应用程序或至少允许测试的虚拟项目会更好。例如:
<<< 12:42.56 Fri Feb 24 2012!~/testproject/testapp
<<< jpic@germaine!10034 E:1 env
>>> pip install -e git+git@github.com:subsume/django-subscription.git#egg=sub
Obtaining sub from git+git@github.com:subsume/django-subscription.git#egg=sub
Cloning git@github.com:subsume/django-subscription.git to /home/jpic/env/src/sub
Running setup.py egg_info for package sub
Installing collected packages: sub
Running setup.py develop for sub
Creating /home/jpic/env/lib/python2.7/site-packages/django-subscription.egg-link (link to .)
Removing django-subscription 0.0 from easy-install.pth file
Adding django-subscription 0.1 to easy-install.pth file
Installed /home/jpic/env/src/sub
Successfully installed sub
Cleaning up...
<<< 12:43.08 Fri Feb 24 2012!~/testproject/testapp
<<< jpic@germaine!10035 env
<<< 12:43.11 Fri Feb 24 2012!~/testproject/testapp
<<< jpic@germaine!10035 env
>>> cd ../../env/src/sub
<<< 12:43.15 Fri Feb 24 2012!~/env/src/sub
<<< jpic@germaine!10036 G:master env
>>> ls
django_subscription.egg-info docs README setup.py subscription subscription_test_project
<<< 12:43.16 Fri Feb 24 2012!~/env/src/sub
<<< jpic@germaine!10037 G:master env
>>> cd subscription_test_project
<<< 12:43.20 Fri Feb 24 2012!~/env/src/sub/subscription_test_project
<<< jpic@germaine!10038 G:master env
>>> ./manage.py test subscription
Creating test database for alias 'default'...
........
----------------------------------------------------------------------
Ran 8 tests in 0.012s
OK
Destroying test database for alias 'default'...
答案 1 :(得分:1)
ImportError:无法导入设置,因为未定义环境变量DJANGO_SETTINGS_MODULE。
你得到这个是因为DJANGO_SETTINGS_MODULE
不在你的python环境变量中......要解决你的问题,你必须将其定义为
import os
os.environ['DJANGO_SETTINGS_MODULE'] = '<django_application_root>.settings'
您可以将其添加到根__init__.py
文件...