测试 Django 视图时出现断言错误 [英] Assertion error while testing Django views
问题描述
这是我在下面提到的 views.py 的测试函数:
def test_operation_page(self):url = reverse('操作')响应 = self.client.get(url)self.assertEqual(response.status_code, 200)self.assertTemplateUsed(响应,'abc.html')self.assertContains(response, '<b>BOOK id具有特定的标题:</b>')
这是我在测试视图时遇到的错误
<块引用>AssertionError:SimpleTestCase 子类中不允许对默认"的数据库查询.子类化 TestCase 或 TransactionTestCase 以确保正确的测试隔离,或将默认"添加到 home.tests.TestViews.databases 以消除此故障.
这是我的views.py
def 操作(请求):queryset=Mytable.objects.filter(title="弗吉尼亚伍尔夫日记第五卷:1936-1941").values('bookid')textset=list(Mytable.objects.order_by('-bookid').values('title'))上下文={'key1':查询集,'key2':文本集}返回渲染(请求,'abc.html',上下文)
这是我的 urls.py
urlpatterns = [路径('管理员/',admin.site.urls),路径('',v.index,name='index'),路径('abc/',v.operation,name='operation')
]
正如它在 SimpleTestCase, "如果您的测试进行任何数据库查询,请使用子类 TransactionTestCase
或 TestCase
.">
您得到的错误是告诉您您的视图正在尝试在 SimpleTestCase
的子类中执行数据库查询.您应该更改正在使用的 TestCase
类 - 这应该可以解决错误.
This is my testing function for views.py which I have mention below:
def test_operation_page(self):
url = reverse('operation')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'abc.html')
self.assertContains(response, '<b>BOOK id having certain title:</b>')
This is the error I am having while testing my views
AssertionError: Database queries to 'default' are not allowed in SimpleTestCase subclasses. Either subclass TestCase or TransactionTestCase to ensure proper test isolation or add 'default' to home.tests.TestViews.databases to silence this failure.
This is my views.py
def operation(request):
queryset=Mytable.objects.filter(title="The Diary of Virginia Woolf Volume Five: 1936-1941").values('bookid')
textset=list(Mytable.objects.order_by('-bookid').values('title'))
context={
'key1' : queryset,
'key2' : textset
}
return render(request,'abc.html',context)
This is my urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',v.index,name='index'),
path('abc/',v.operation,name='operation')
]
As it states in the docs under SimpleTestCase, "If your tests make any database queries, use subclasses TransactionTestCase
or TestCase
."
The error that you are getting is telling you that your view is trying to execute a database query in a subclass of SimpleTestCase
. You should change what TestCase
class you are using - that should solve the error.
这篇关于测试 Django 视图时出现断言错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!