由于AppRegistryNotReady,Django 2.0单元测试未运行

时间:2018-05-02 14:56:04

标签: django python-3.x unit-testing

我构建了一个非常简单的Django应用程序来尝试单元测试。在不导入任何Django模型时,我可以毫无问题地运行测试,例如:

import os

from django.test import TestCase

class FirstTest(TestCase):

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testje.settings")

    def test_First(self):
        a = 1
        self.assertEqual(1, a)

我正在运行Django 2.0.1。现在,当我尝试导入类似的模型时:

import os

from django.test import TestCase

from polls.models import Question


class FirstTest(TestCase):

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testje.settings")

    def test_First(self):
        a = 1
        self.assertEqual(1, a)

它会因以下堆栈跟踪而失败:


Testing started at 16:46 ...
C:\Users\martijnka\virtualenvs\Test\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.2\helpers\pycharm\_jb_unittest_runner.py" --path D:/martijnka/Downloads/testDjango/testje/polls/tests.py
Launching unittests with arguments python -m unittest D:/martijnka/Downloads/testDjango/testje/polls/tests.py in D:\martijnka\Downloads\testDjango\testje\polls

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.2\helpers\pycharm\_jb_unittest_runner.py", line 35, in 
    main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)
  File "c:\program files (x86)\python36-32\Lib\unittest\main.py", line 94, in __init__
    self.parseArgs(argv)
  File "c:\program files (x86)\python36-32\Lib\unittest\main.py", line 141, in parseArgs
    self.createTests()
  File "c:\program files (x86)\python36-32\Lib\unittest\main.py", line 148, in createTests
    self.module)
  File "c:\program files (x86)\python36-32\Lib\unittest\loader.py", line 219, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "c:\program files (x86)\python36-32\Lib\unittest\loader.py", line 219, in 
    suites = [self.loadTestsFromName(name, module) for name in names]
  File "c:\program files (x86)\python36-32\Lib\unittest\loader.py", line 153, in loadTestsFromName
    module = __import__(module_name)
  File "D:\martijnka\Downloads\testDjango\testje\polls\tests.py", line 5, in 
    from polls.models import Question
  File "D:\martijnka\Downloads\testDjango\testje\polls\models.py", line 9, in 
    class Question(models.Model):
  File "C:\Users\martijnka\virtualenvs\Test\lib\site-packages\django\db\models\base.py", line 100, in __new__
    app_config = apps.get_containing_app_config(module)
  File "C:\Users\martijnka\virtualenvs\Test\lib\site-packages\django\apps\registry.py", line 244, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\martijnka\virtualenvs\Test\lib\site-packages\django\apps\registry.py", line 127, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Process finished with exit code 1
Empty test suite.

我的设置如下:



    """
    Django settings for testje project.

    Generated by 'django-admin startproject' using Django 2.0.1.

    For more information on this file, see
    https://docs.djangoproject.com/en/2.0/topics/settings/

    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/2.0/ref/settings/
    """

    import os

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '********************************'

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    ALLOWED_HOSTS = ['127.0.0.1', 'localhost']


    # Application definition

    INSTALLED_APPS = [
        'polls.apps.PollsConfig',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    ROOT_URLCONF = 'testje.urls'

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

    WSGI_APPLICATION = 'testje.wsgi.application'


    # Database
    # https://docs.djangoproject.com/en/2.0/ref/settings/#databases

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }


    # Password validation
    # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]


    # Internationalization
    # https://docs.djangoproject.com/en/2.0/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True


    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.0/howto/static-files/

    STATIC_URL = '/static/'

正如您所看到的,我正在从PyCharm CE 9运行最新版本)。我一直在寻找答案并尝试很多东西,但到目前为止没有任何运气。知道我在这里缺少什么(可能非常简单)?

0 个答案:

没有答案