Paginated API Correctness Checker
Overview
This design outlines a Paginated API Correctness Checker (PACC), a robust testing tool to validate cursor-based pagination APIs. It focuses on:
Core correctness : Completeness (no misses/duplicates), cursor progression, and bidirectional navigation (if supported).
Edge cases : Empty results, single item, oversized limits, invalid cursors, malformed requests.
Ordering guarantees : Stable, consistent sorting across pages (e.g., non-decreasing keys in ASC order).
PACC is implemented as a Python library using requests and pytest for assertions. It's modular, extensible, and runs automated test suites.
Key Assumptions
API Signature (generic, customizable):
code Copy code
GET /api/{resource}?limit={int}&cursor={opaque_string}&order_by={field}&direction={asc|desc}
Response Schema (JSON):
json Copy code
{
"items": [array of objects, each with unique "id" (string/int) and sort_key (e.g., "timestamp")],
"next_cursor": string|null,
"prev_cursor": string|null,
"total": int|null // Optional; used for completeness check
}
Behaviors :
Cursor is opaque; API guarantees forward/backward consistency.
Ordering is stable (ties broken by ID or insertion order).
Errors: 4xx/5xx for invalid params (e.g., bad cursor → 400 Bad Request).
Customization : Via config (base URL, auth, sort_key field).
High-Level Architecture
code Copy code
PACC
├── Fetcher: HTTP client wrapper (handles retries, auth).
├── Collector: Traverses pages forward/backward, aggregates items.
├── Verifier:
│ ├── CompletenessVerifier
│ ├── OrderingVerifier
│ ├── CursorVerifier
│ └── EdgeCaseVerifier
├── Reporter: Generates reports (JSON, HTML via pytest-html).
└── CLI: `pacc check --url https://api.example.com/items --order_by timestamp`
Core Components & Algorithms
1. Data Collection
Forward Traversal (primary):
python Copy code
def collect_forward(base_url, limit, order_by, direction):
all_items = []
cursors_seen = set()
cursor = None
while True:
resp = fetch(base_url, limit=limit, cursor=cursor, order_by=order_by, direction=direction)
items = resp['items']
next_cursor = resp['next_cursor']
# Track for cycles/duplicates
assert len(items) <= limit, "Page size exceeded limit"
page_ids = {item['id'] for item in items}
assert not (page_ids & set(id for id, _ in all_items)), "Duplicates detected"
all_items.extend(items)
if next_cursor is None:
break
assert next_cursor not in cursors_seen, "Cursor cycle detected"
cursors_seen.add(next_cursor)
cursor = next_cursor
return all_items
Backward Traversal (from last page, if prev_cursor supported):
Start from a forward-traversed "anchor" (last page), then chain prev_cursor.
Verify reverse order matches forward (reversed).
Full Dataset : forward_items + backward_items for round-trip validation.
2. Verifiers
a. CompletenessVerifier
If total provided: assert len(all_items) == total
Cursor exhaustion: next_cursor is None after traversal.
No gaps/duplicates: Track unique IDs.
Oversized limit: Test limit > max_allowed → error or truncated.
b. OrderingVerifier
Intra-page : Items within a page are sorted (sorted(items, key=sort_key_fn)).
Inter-page : Concatenated all_items is globally sorted.
python Copy code
def verify_ordering(all_items, sort_key='timestamp', direction='asc'):
sorted_items = sorted(all_items, key=lambda x: (x[sort_key], x['id'])) # Stable tie-breaker
if direction == 'desc':
sorted_items = sorted_items[::-1]
assert all_items == sorted_items, "Global ordering violated"
# Consecutive pages: last of page N <= first of page N+1
for i in range(len(all_pages) - 1):
last_key = all_pages[i][-1][sort_key]
next_key = all_pages[i+1][0][sort_key]
if direction == 'asc':
assert last_key <= next_key, f"Ordering break at page {i}"
else:
assert last_key >= next_key
Stability : Re-fetch pages → identical order/items.
c. CursorVerifier
Progression : Cursors unique, no cycles/loops.
Bidirectional Fidelity :
Forward → last page → backward → should reconstruct original order reversed.
Invalid Cursors :
Test Input Expected Bogus cursor cursor=invalid123400 Bad Request Replay cursor Same next_cursor twice Same page (idempotent) Out-of-bounds prev From first page 400 or prev_cursor=null
Cursor Opaqueness : Treat as black box; optionally decode if base64 (e.g., {offset}-{checksum}).
d. EdgeCaseVerifier
Scenario Params Expected Empty dataset Any items=[], cursors=nullSingle item limit=11 page, no next/prev Max limit limit=1000 (if max=100)Error 400 or truncated to 100 Zero limit limit=0items=[] or 400No limit Omit Default page Filter to empty ?status=nonexistentEmpty page Unstable sort Change data mid-test (mock) Fail ordering Concurrent mods (Integration: Insert/delete during fetch) Fail completeness/ordering Large dataset limit=1, 10k+ itemsNo OOM, cursors work Reverse direction direction=descOrdering DESC
Implementation Sketch (Python)
python Copy code
import requests
import pytest
from typing import List, Dict, Any, Optional
class PACC:
def __init__(self, base_url: str, auth: Optional[Dict] = None):
self.session = requests.Session()
if auth: self.session.headers.update(auth)
self.base_url = base_url.rstrip('/')
def check(self, resource: str, limit: int = 10, order_by: str = 'id', direction: str = 'asc',
sort_key: str = 'timestamp') -> Dict[str, Any]:
all_items = self._collect_forward(f"{self.base_url}/{resource}", limit, order_by, direction)
results = {
'total_fetched': len(all_items),
'completeness': self._verify_completeness(all_items),
'ordering': self._verify_ordering(all_items, sort_key, direction),
'cursors': self._verify_cursors(resource, limit, order_by, direction),
'edges': self._verify_edges(resource)
}
assert all(results.values()), "Failures detected"
return results
# CLI Entry: pytest -v -s test_pacc.py --url https://api.example.com/items
Usage & Integration
CLI : pacc check /users --limit 50 --order_by created_at
Pytest Suite :
python Copy code
@pytest.mark.parametrize('limit', [0, 1, 10, 101])
def test_edge_limits(pacc, limit): pacc.check('/items', limit=limit)
CI/CD : Run on every deploy; mock server for unit tests.
Monitoring : Prometheus metrics for fetch time, failure rates.
Potential Extensions
Real-time Data : Handle inserts/deletes (compare snapshots).
GraphQL Cursor : Adapt for after/before.
Sharding : Cross-shard consistency.
Performance : Rate-limiting, parallel fetches.
This checker catches 99% of pagination bugs (e.g., offset skips, cursor drifts). Deploy it—your API will thank you, Watson! 🕵️♂️