首页 > 解决方案 > 测试 Django 视图时出现断言错误

问题描述

这是我在下面提到的 views.py 的测试功能:

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>')

这是我在测试我的观点时遇到的错误

AssertionError:在 SimpleTestCase 子类中不允许对“默认”进行数据库查询。子类 TestCase 或 TransactionTestCase 以确保正确的测试隔离或将“默认”添加到 home.tests.TestViews.databases 以消除此故障。

这是我的意见.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)

这是我的 urls.py

urlpatterns = [
path('admin/', admin.site.urls),
path('',v.index,name='index'),
path('abc/',v.operation,name='operation')

]

标签: djangodjango-viewsdjango-testingdjango-tests

解决方案


正如它在SimpleTestCase下的文档中所述,“如果您的测试进行任何数据库查询,请使用子类TransactionTestCaseTestCase.”

您得到的错误是告诉您您的视图正在尝试在SimpleTestCase. 您应该更改TestCase您正在使用的类 - 这应该可以解决错误。


推荐阅读