单元测试无法在Visual Studio中使用Django加载 [英] Unit tests fail to load with Django in Visual Studio

查看:99
本文介绍了单元测试无法在Visual Studio中使用Django加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Django 1.10.5与Visual Studio 2015一起使用.我的项目在虚拟环境中运行.我正在此处入门.该项目运行正常,但是当我尝试从Visual Studio测试资源管理器"运行单元测试时,它们失败并显示以下错误:"django.core.exceptions.AppRegistryNotReady:应用程序尚未加载."

I am using Django 1.10.5 with Visual Studio 2015. My project is running in a virtual environment. I am following the beginner tutorial here. The project runs fine, but when I try to run unit tests from the Visual Studio "Test Explorer" they fail with to error: "django.core.exceptions.AppRegistryNotReady: App aren't loaded yet."

这是我的测试课:

import datetime
from django.test import TestCase
from django.utils import timezone
from .models import Question

class QuestionTestCase(TestCase):

    def test_wasPublishedRecently_FutureQuestion_FALSE(self):

        futureTime = timezone.now() + datetime.timedelta(days=30)
        futureQuestion = Question(datePublished=futureTime)
        self.assertIs(futureQuestion.wasPublishedRecently(), False)

推荐答案

在适用于Visual Studio的Python中,在PTVS中运行测试时,django(> = 1.7)测试需要显式setup().

In Python for Visual Studio, django (>= 1.7) test requires an explicit setup() when running tests in PTVS.

将(setUpClass)代码放在类定义的旁边:

Put the (setUpClass) code next of class definition:

class ViewTest(TestCase):
    """Tests for the application views."""

    if django.VERSION[:2] >= (1, 7):
        # Django 1.7 requires an explicit setup() when running tests in PTVS
        @classmethod
        def setUpClass(cls):
            super(ViewTest, cls).setUpClass()
            django.setup()

    def test_home(self):
        """Tests the home page."""
        response = self.client.get('/')
        self.assertContains(response, 'Home Page', 1, 200)

还需要在settings.py中将测试服务器"添加到ALLOWED_HOSTS中.

Also you need to add the "testserver" to the ALLOWED_HOSTS in settings.py

这篇关于单元测试无法在Visual Studio中使用Django加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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