【问题标题】:python running test: ImproperlyConfiguredpython运行测试:配置不当
【发布时间】:2015-03-12 09:09:30
【问题描述】:

我正在尝试为 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()

【问题讨论】:

标签: django unit-testing python-2.7


【解决方案1】:

您可以使用test 命令run Django tests

./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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 2012-01-16
    • 2019-07-16
    • 2017-05-19
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多