尝试运行pytest-django时出现“应用尚未加载” - python

以Django tutorial中的(部分)民意测验应用程序为例,我试图让pytest-django运行。

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

.
├── 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中,我创建了QuestionChoice模型:

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模块的,

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,则测试失败了:

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并具有普通的断言):

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命令,出现以下错误:

================================= 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 ================================

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

参考方案

开箱即用,即使安装了pytestpytest-django也不了解Django数据库。不过,请不要担心:pytest-django使您的测试使用其django_db pytest mark轻松访问Django数据库。

试试看:

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

Django:错误:您无权访问该端口 - python

我是整个安装的新手,请保持友善。在dev上,该命令通常可以正常工作,但是自从我尝试使用Django的不同命令以来,某些东西就出错了。python manage.py runserver 0.0.0.0:80 我没有使用此端口的权限了。我可以使用端口8080,但将端口添加到url中通常的主机名末尾时,网站无法正常工作。当我使用端口80时,无论如何我都无需在UR…

Django:DateField“此字段不能为空。” - python

我发布这样的休息请求:{title:some title, recurring:true, day:Wednesday, time:12:30, description:some text} 我没有传递日期,因为该事件重复发生,并且该值应该为空。服务器响应为:{"date": ["This field cannot be bla…

Django TestCase不保存我的模型 - python

我目前正在为Django应用编写一些测试。我的应用程序的signal.py文件中具有以下独立功能:def updateLeaveCounts(): # Setting some variables here todaysPeriods = Period.objects.filter(end__lte=today_end, end__gte=today_sta…

django-simple-history,在admin中显示更改的字段 - python

当我从admin.ModelAdmin继承时,在管理页面的历史记录中,我可以看到哪些字段已更改。但是,现在我需要使用django-simple-history来跟踪所有模型更改。现在,对于管理员,我继承了simple_history.SimpleHistoryAdmin。我可以看到所有模型更改并还原它们,但看不到更改了哪些字段。是否可以在SimpleHist…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…