6

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

]

Sachin
  • 185
  • 1
  • 3
  • 10

3 Answers3

10

It would be something like either you inherit the TestCase or TransactionTestCase or by using the same SimpleTestCase in the following way

class CustomClass(django.test.SimpleTestCase):
    databases = '__all__'
    ...

Earlier SimpleTestCase had dependency on allow_database_queries = True which is depreciated since django version 2.2.

This attribute is deprecated in favor of databases. The previous behavior of allow_database_queries = True can be achieved by setting databases = '__all__'.

https://docs.djangoproject.com/en/2.2/topics/testing/tools/#django.test.SimpleTestCase.databases

Umar Asghar
  • 3,808
  • 1
  • 36
  • 32
8

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.

Jacinator
  • 1,413
  • 8
  • 11
  • 1
    is this new? I had tons of tests that ran fine under Django 2.1.5 that now break with this error on 2.2 – user5359531 Sep 06 '19 at 19:17
  • 1
    That might be related to this change https://docs.djangoproject.com/en/2.2/topics/testing/tools/#django.test.SimpleTestCase.databases – Jacinator Sep 06 '19 at 19:35
  • 2
    as suggested there, adding `databases = '__all__'` to the TestCase class instance seems to have resolved it. – user5359531 Sep 06 '19 at 19:44
0
class HomepageTests(SimpleTestCase):

above subclass(SimpleTestCase) change with parent class(TestCase)

class HomepageTests(TestCase):

use it enter image description here

Syed
  • 1
  • 5