Unit tests fail to load with Django in Visual Studio

余生颓废 提交于 2019-12-23 03:18:18

问题


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."

This is my test class:

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)

回答1:


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

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)

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



来源:https://stackoverflow.com/questions/41590167/unit-tests-fail-to-load-with-django-in-visual-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!