测试Django视图时出现断言错误 [英] Assertion error while testing Django views

查看:323
本文介绍了测试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中添加默认"以使此失败保持沉默.

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.

这是我的观点.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')

]

推荐答案

文档在

As it states in the docs under SimpleTestCase, "If your tests make any database queries, use subclasses TransactionTestCase or TestCase."

您收到的错误是告诉您您的视图正在尝试在SimpleTestCase的子类中执行数据库查询.您应该更改正在使用的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆