django - python运行测试: ImproperlyConfigured

标签 django unit-testing python-2.7

我正在尝试为 django (1.7) 项目运行一些睾丸。

在项目目录下创建了一个test_models.py目录/tests/

关于运行测试

>> python tests/test_models.py -v

错误:

django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

虽然 以下 Django 标准命令工作正常

>> python manage.py runserver
>> python manage.py shell

test_models.py

import unittest
from django.contrib.auth.models import User
from accounts.models import school

class TestAccounts(unittest.TestCase):

    def setUp(self):
        admin_user = User.objects.get_or_create(
            username="testuser", password=111)
        self.admin = admin_user[0]

        self.school_name = "merucabs"
        self.email = "info@merucabs.com"

    def test_school(self):
        print "Testing school ..."
        school = School(name=self.school_name)
        school.created_by = self.admin
        school.updated_by = self.admin
        school.save()
        self.school = school
        self.assertEqual(self.school.name, self.school_name)



def suite():
    suite = unittest.TestSuite()
    suite.addTests(unittest.makeSuite(TestAccounts))

if __name__ == '__main__':
    unittest.main()

最佳答案

您可以 run Django tests使用 test 命令。

./manage.py test tests/test_models

如果您想将测试作为独立脚本运行(即 python tests/test_models.py),则必须设置 DJANGO_SETTINGS_MODULE 环境变量。从 Django 1.7 开始,您还必须调用 django.setup()

import django
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
django.setup()

关于django - python运行测试: ImproperlyConfigured,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27938620/

相关文章:

django - 如何构建 witt django-mptt 查询连接到 mptt 层次结构元素的任何后代?

html - Django 可以从静态文件加载图像但不能使用 css

python - 断言失败时继续 Python 的单元测试

AngularJS 更改传递给配置进行单元测试的常量值

python - 在 Django 中一次更新多个对象?

其他IP地址上的Django Broken INTERNAL链接

python - 如何模拟 boto3 客户端对象/调用

python - 如何子类化 numpy .`ma.core.masked_array` ?

python - 使用\u转义unicode字符串

python - 一旦 python 脚本从终端 (Ctrl-C) 停止,如何释放 Ubuntu 内存?