Visual Studio 中的 Django 单元测试无法加载
Unit tests fail to load with Django in Visual Studio
我在 Visual Studio 2015 中使用 Django 1.10.5。我的项目 运行 在虚拟环境中运行。我正在学习初学者教程 here。项目 运行 很好,但是当我尝试 运行 来自 Visual Studio "Test Explorer" 的单元测试时,它们失败并出现错误:"django.core.exceptions.AppRegistryNotReady: App aren't loaded yet."
这是我的测试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)
在 Python for Visual Studio 中,当 运行 在 PTVS 中测试时,django (>= 1.7) 测试需要显式设置()。
将 (setUpClass) 代码放在 class 定义的后面:
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)
您还需要将 "testserver" 添加到 settings.py
中的 ALLOWED_HOSTS
我在 Visual Studio 2015 中使用 Django 1.10.5。我的项目 运行 在虚拟环境中运行。我正在学习初学者教程 here。项目 运行 很好,但是当我尝试 运行 来自 Visual Studio "Test Explorer" 的单元测试时,它们失败并出现错误:"django.core.exceptions.AppRegistryNotReady: App aren't loaded yet."
这是我的测试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)
在 Python for Visual Studio 中,当 运行 在 PTVS 中测试时,django (>= 1.7) 测试需要显式设置()。
将 (setUpClass) 代码放在 class 定义的后面:
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)
您还需要将 "testserver" 添加到 settings.py
中的 ALLOWED_HOSTS