Sunjaree
Sunjaree

Reputation: 138

Getting AttributeError: 'TestCase' object has no attribute 'assertTemplateUsed' when trying to unit test views.py using unittest framework

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)

Upvotes: 0

Views: 897

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

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

Upvotes: 1

neverwalkaloner
neverwalkaloner

Reputation: 47374

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

Upvotes: 2

Related Questions