Django测试分页EmptyPage

时间:2019-11-20 22:38:19

标签: django django-unittest

我正在尝试编写一个函数来测试我们是否超过了页面限制,它会返回最后一页,但是我有点卡住了

这是我的功能:

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

当我运行此测试时,它会返回给我:

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>

我的视图功能是这样的:

...
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})

1 个答案:

答案 0 :(得分:0)

您应该比较页码而不是页面对象本身

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