问题
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