Search code examples
djangodjango-unittest

Django test pagination EmptyPage


I am trying to write a function that tests if we exceed the page limit it returns the last page, but I'm a little stuck

Here is my function:

def test_pagination_returns_last_page_if_page_out_of_range(self):
    response = self.client.get(reverse('catalog:search'),  {'query': '',  'page': 999})
    # Check that if page is out of range (e.g. 999), deliver last page of results
    self.assertEquals(response.context['products'], response.context['products'].paginator.page(2))

When I run this test it returns to me:

Traceback (most recent call last):
  File "/home/rouizi/pur_beurre/catalog/tests/test_views.py", line 120, in 
test_pagination_returns_last_page_if_page_out_of_range
    self.assertEquals(response.context['products'],response.context['products'].paginator.page(2))
AssertionError: <Page 2 of 2> != <Page 2 of 2>

my view function is somthing like this:

...
try:
    prods = paginator.page(page)
except EmptyPage:
    # We return the last page
    prods = paginator.page(paginator.num_pages)

return render(request, 'catalog/search.html',
              {'products': prods, 'query': query})

Solution

  • You should compare the page number rather than the page objects themselves

    self.assertEquals(response.context['products'].number, response.context['products'].paginator.page(2).number)