Paginate Search Results
The search page needs to show results a page at a time. The README has the rules, and pagination.py has the Page type and the outline of paginate. Build it with the assistant: accept, edit, or reject each suggestion, and keep the tests green.
pagination.py1 of 3
Files
pagination.py
Python · Editablefrom dataclasses import dataclass
@dataclass
class Page:
items: list
number: int
total_pages: int
def paginate(results, page, per_page=10):
"""Returns one page of results. Pages are numbered from 1."""
total_pages = page_count(len(results), per_page)
raise NotImplementedError
return Page(items, page, total_pages)
def page_count(total, per_page):
"""How many pages it takes to show total results, per_page at a time."""
raise NotImplementedError
import pytest
from pagination import paginate
RESULTS = ["a", "b", "c", "d", "e"]
def test_first_page():
page = paginate(RESULTS, 1, per_page=2)
assert page.items == ["a", "b"]
assert page.number == 1
def test_last_page_holds_the_remainder():
page = paginate(RESULTS, 3, per_page=2)
assert page.items == ["e"]
assert page.total_pages == 3
def test_total_pages_on_an_exact_multiple():
assert paginate(RESULTS[:4], 1, per_page=2).total_pages == 2
def test_empty_results_are_one_empty_page():
page = paginate([], 1, per_page=2)
assert page.items == []
assert page.total_pages == 1
def test_has_next_and_has_prev():
first, middle, last = (paginate(RESULTS, n, per_page=2) for n in (1, 2, 3))
assert (first.has_prev, first.has_next) == (False, True)
assert (middle.has_prev, middle.has_next) == (True, True)
assert (last.has_prev, last.has_next) == (True, False)
def test_no_next_page_on_an_exact_multiple():
assert not paginate(RESULTS[:4], 2, per_page=2).has_next
def test_page_past_the_end_shows_the_last_page():
page = paginate(RESULTS, 9, per_page=2)
assert page.number == 3
assert page.items == ["e"]
def test_rejects_page_zero():
with pytest.raises(ValueError):
paginate(RESULTS, 0, per_page=2)
def test_rejects_zero_per_page():
with pytest.raises(ValueError):
paginate(RESULTS, 1, per_page=0)
# Search Pagination
The search page shows results one page at a time through paginate (pagination.py), which returns a Page.
## Rules
- Pages are numbered from 1. page and per_page must both be at least 1, or paginate raises ValueError.
- total_pages is the number of pages it takes to show every result. A search with no results is one empty page.
- A page past the last page shows the last page, and its number says so.
- has_next and has_prev tell the page controls whether to show Next and Previous.
The tests in test_pagination.py use 2 results per page.
Test Output
No runs yet.