“尚未加载应用".尝试运行pytest-django时 [英] "Apps aren't loaded yet" when trying to run pytest-django

查看:68
本文介绍了“尚未加载应用".尝试运行pytest-django时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Django教程中的(部分)民意调查应用例如,我正在尝试运行 pytest-django .

Using the (partial) polls app from the Django tutorial as an example, I'm trying to get pytest-django to run.

使用命令 django-admin startproject mysite2 ,我创建了一个具有以下结构的项目目录:

Using the command django-admin startproject mysite2, I've created a project directory with the following structure:

.
├── db.sqlite3
├── manage.py
├── mysite2
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── polls
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
└── pytest.ini

我的 pytest.ini 看起来像

[pytest]
DJANGO_SETTINGS_MODULE = mysite2.settings
python_files = tests.py test_*.py *_tests.py

在教程之后,我在 polls/models.py 中创建了 Question Choice 模型:

Following the tutorial, in polls/models.py I've created Question and Choice models:

import datetime

from django.db import models
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

现在,如果我按照本教程中的说明进行 tests.py 的创建,该教程基于Python的内置 unittest 模块,

Now, if I make tests.py as described in the tutorial, which is based on Python's built-in unittest module,

import datetime

from django.utils import timezone
from django.test import TestCase

from .models import Question

class QuestionModelTests(TestCase):
    def test_was_published_recently_with_future_question(self):
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

并且我从命令行运行 python manage.py test ,测试失败了:

and I run python manage.py test from the command line, the test fails expected:

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/kurtpeek/Documents/Scratch/mysite2/polls/tests.py", line 23, in test_was_published_recently_with_future_question
    self.assertIs(future_question.was_published_recently(), False)
AssertionError: True is not False

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)
Destroying test database for alias 'default'...

但是,如果我将测试代码更改为(尝试过的) pytest 等效项(也就是说,无需子类化 TestCase 并具有普通的断言):

However, if I change the testing code to the (attempted) pytest equivalent (that is, without having to subclass TestCase and with ordinary assertions):

def test_was_published_recently_with_future_question():
    time = timezone.now() + datetime.timedelta(days=30)
    future_question = Question(pub_date=time)
    assert future_question.was_published_recently() is False

并运行 pytest 命令,出现以下错误:

and run the pytest command, I get the following error:

================================= test session starts ==================================
platform darwin -- Python 3.6.3, pytest-3.2.3, py-1.4.34, pluggy-0.4.0
rootdir: /Users/kurtpeek/Documents/Scratch/mysite2, inifile: pytest.ini
plugins: timeout-1.2.1
collected 0 items / 1 errors                                                            

======================================== ERRORS ========================================
___________________________ ERROR collecting polls/tests.py ____________________________
polls/tests.py:10: in <module>
    from .models import Question
polls/models.py:6: in <module>
    class Question(models.Model):
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py:100: in __new__
    app_config = apps.get_containing_app_config(module)
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/registry.py:244: in get_containing_app_config
    self.check_apps_ready()
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/registry.py:127: in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
E   django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 0.64 seconds ================================

到目前为止,我还没有找到解决此问题的方法.有关如何运行测试的任何想法?

So far I haven't been able to find a way to fix this. Any ideas on how to get the test to run?

推荐答案

开箱即用,即使使用 pytest-django pytest 也不了解Django数据库.>已安装.不过请不要担心: pytest-django 使您的测试使用其

Out of the box, pytest doesn't know about the Django database, even with pytest-django installed. Never fear, though: pytest-django makes it easy for your tests to access the Django database using its django_db pytest mark.

尝试一下:

import pytest


@pytest.mark.django_db
def test_was_published_recently_with_future_question():
    time = timezone.now() + datetime.timedelta(days=30)
    future_question = Question(pub_date=time)
    assert future_question.was_published_recently() is False

这篇关于“尚未加载应用".尝试运行pytest-django时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆