Home > other >  Getting AttributeError: 'TestCalls' object has no attribute 'assertTemplateUsed'
Getting AttributeError: 'TestCalls' object has no attribute 'assertTemplateUsed'

Time:04-16

Here is my code for unit test fruit view. But getting AttributeError

test_views.py

class TestViews(unittest.TestCase):

    def test_fruit_GET(self):
        client = Client()
        response = client.get(reverse('products:fruit'))
        self.assertEquals(response.status_code, 200)
        self.assertTemplateUsed(response, 'products/fruit.html')

views.py

def fruit(request):

    product = Product.objects.filter(category="Fruit")
    n = Product.objects.filter(category="Fruit").count()
    params = {'product': product, 'n': n}
    return render(request, 'products/fruit.html', params)

CodePudding user response:

This method is part of django's TestCase class, so you need to use it instead:

from django.test import TestCase

class TestViews(TestCase):

    def test_fruit_GET(self):
        client = Client()
        response = client.get(reverse('products:fruit'))
        self.assertEquals(response.status_code, 200)
        self.assertTemplateUsed(response, 'products/fruit.html')

CodePudding user response:

This is not available for the unittest.TestCase. This is provided by Django's TestCase class [Django-doc], so:

from django.test import TestCase

class TestViews(TestCase):

    def test_fruit_GET(self):
        response = self.client.get(reverse('products:fruit'))
        self.assertEquals(response.status_code, 200)
        self.assertTemplateUsed(response, 'products/fruit.html')

You can implement this yourself, but it is very inconvenient:

def assertTemplateUsed(self, response, template_name):
    self.assertIn(
        template_name,
        [t.name for t in response.templates if t.name is not None]
    )
  • Related