Unit tests fail to load with Django in Visual Stud

2019-06-08 15:05发布

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条回答
太酷不给撩
2楼-- · 2019-06-08 15:36

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

查看更多
登录 后发表回答