Django - Writing Tests: Unit testing extra variables passed to generic views

219 views Asked by At

I would like to know if there is a way to use Django's test client to verify that the extra variables that are passed from a generic view are correct.

For example, given the code below, how would I write a test for list_year() to ensure that the template is receiving the current year from the view, or for purchase_yrs() to make sure the correct information is being passed from the model manager?

I can't seem to find a way to draw it out of the response.context attribute.

class PurchaseIndex(generic.ListView):

    def get_queryset(self):
        current_date = datetime.now().year
        return Purchase.objects.filter(purchase_date__year=current_date).reverse()

    def purchase_yrs(self):
        return Purchase.purchase_years.purchase_years_list()

    def list_year(self):
        return datetime.now().year
1

There are 1 answers

0
Adam Starrh On BEST ANSWER

Okay, I finally figured this one out. Pretty simple:

from django.test import TestCase
from views import PurchaseIndex

class IndexPageTest(TestCase):

    def test_current_purchase_index_displays_year(self):
        context = PurchaseIndex.list_year(self)
        self.assertEqual(2015, context)

    def test_current_shipments_included_in_current_purchase_index(self):
        context = PurchaseIndex.purchase_yrs(self)
        self.assertIn(2015, context)
        self.assertIn(2014, context)