Debian Codegraph @

tests/test_pagination_cursor.py

raw symbols SCIP
1 from datetime import date, timedelta
2 from http import HTTPStatus
3 from typing import List
4
5 import django
6 import pytest
7 from django.test import override_settings
8 from someapp.api import EventSchema # pyright: ignore[reportMissingImports]
9 from someapp.models import Category, Event # pyright: ignore[reportMissingImports]
10
11 from ninja import NinjaAPI
12 from ninja.pagination import CursorPagination, paginate
13 from ninja.testing import TestAsyncClient, TestClient
14
15 api = NinjaAPI()
16
17
18 @api.get("/cursor_events", response=List[EventSchema])
19 @paginate(CursorPagination, ordering=("start_date",), page_size=10)
20 def cursor_events(request, **kwargs):
21 return Event.objects.all()
22
23
24 @api.get("/cursor_events_reverse", response=List[EventSchema])
25 @paginate(CursorPagination, ordering=("-start_date",), page_size=10)
26 def cursor_events_reverse(request, **kwargs):
27 return Event.objects.all()
28
29
30 @api.get("/cursor_events_end_date_offset", response=List[EventSchema])
31 @paginate(CursorPagination, ordering=("end_date", "start_date"), page_size=2)
32 def cursor_events_end_date_offset(request, **kwargs):
33 return Event.objects.all()
34
35
36 @api.get("/cursor_events_default_size", response=List[EventSchema])
37 @paginate(CursorPagination, ordering=("start_date",))
38 def cursor_events_default_size(request, **kwargs):
39 return Event.objects.all()
40
41
42 @api.get("/cursor_events_with_params", response=List[EventSchema])
43 @paginate(CursorPagination, ordering=("start_date",), page_size=10)
44 def cursor_events_with_params(request, title_filter: str = "", **kwargs):
45 # API method with a filter in query parameter
46 if title_filter:
47 return Event.objects.filter(title__icontains=title_filter)
48 return Event.objects.all()
49
50
51 # Async versions of all endpoints
52 @api.get("/async_cursor_events", response=List[EventSchema])
53 @paginate(CursorPagination, ordering=("start_date",), page_size=10)
54 async def async_cursor_events(request, **kwargs):
55 return Event.objects.all()
56
57
58 @api.get("/async_cursor_events_reverse", response=List[EventSchema])
59 @paginate(CursorPagination, ordering=("-start_date",), page_size=10)
60 async def async_cursor_events_reverse(request, **kwargs):
61 return Event.objects.all()
62
63
64 @api.get("/async_cursor_events_end_date_offset", response=List[EventSchema])
65 @paginate(CursorPagination, ordering=("end_date", "start_date"), page_size=2)
66 async def async_cursor_events_end_date_offset(request, **kwargs):
67 return Event.objects.all()
68
69
70 @api.get("/async_cursor_events_default_size", response=List[EventSchema])
71 @paginate(CursorPagination, ordering=("start_date",))
72 async def async_cursor_events_default_size(request, **kwargs):
73 return Event.objects.all()
74
75
76 @api.get("/async_cursor_events_with_params", response=List[EventSchema])
77 @paginate(CursorPagination, ordering=("start_date",), page_size=10)
78 async def async_cursor_events_with_params(request, title_filter: str = "", **kwargs):
79 # API method with a filter in query parameter
80 if title_filter:
81 return Event.objects.filter(title__icontains=title_filter)
82 return Event.objects.all()
83
84
85 client = TestClient(api)
86 async_client = TestAsyncClient(api)
87
88
89 @pytest.fixture(autouse=True)
90 def clean_db(transactional_db):
91 """Clean up categories and events before and after each test."""
92 Category.objects.all().delete()
93 Event.objects.all().delete()
94 yield
95 Category.objects.all().delete()
96 Event.objects.all().delete()
97
98
99 @pytest.fixture()
100 def start_date():
101 return date(2023, 1, 1)
102
103
104 @pytest.fixture(autouse=True)
105 def events(transactional_db, start_date):
106 """Create a number of test events."""
107
108 events = []
109 for i in range(1, 11):
110 event = Event(
111 title=f"Event {i}", # 1-10
112 start_date=start_date + timedelta(days=i), # sequential start dates
113 end_date=start_date
114 + timedelta(
115 days=((i - 1) // 3) + 1
116 ), # end dates 1, 1, 1, 2, 2, 2, 3, 3, 3, 4
117 )
118 events.append(event)
119
120 return Event.objects.bulk_create(events)
121
122
123 @pytest.fixture(autouse=True)
124 def special_events(transactional_db, start_date, events):
125 """Create a number of special events occurring after the last ones"""
126 n_events = len(events)
127 special_events = []
128 for i in range(n_events + 1, n_events + 4):
129 event = Event(
130 title=f"Special Event {i}", # 11-13
131 start_date=start_date + timedelta(days=i), # sequential start dates
132 end_date=start_date
133 + timedelta(days=((i - 1) // 3) + 1), # end dates 4, 4, 5
134 )
135 special_events.append(event)
136
137 return Event.objects.bulk_create(special_events)
138
139
140 def test_cursor_pagination_first_page():
141 """Test first page of cursor pagination."""
142
143 response = client.get("/cursor_events?page_size=5").json()
144
145 assert len(response["results"]) == 5
146 assert response["results"][0]["title"] == "Event 1"
147 assert response["results"][-1]["title"] == "Event 5"
148 assert response["next"] is not None
149 assert response["previous"] is None
150
151
152 def test_cursor_pagination_with_cursor():
153 """Test navigation using cursor."""
154
155 # Get first page to obtain next cursor
156 first_response = client.get("/cursor_events").json()
157
158 assert len(first_response["results"]) == 10
159 assert first_response["next"] is not None
160
161 if first_response["next"]:
162 # we can't rely on `next` being a well-formed URL, because the testclient
163 # httprequest mock does not pass the path, so we extract the cursor instead
164 next_cursor = first_response["next"].split("cursor=")[1].split("&")[0]
165
166 # Use cursor to get next page
167 response = client.get(f"/cursor_events?cursor={next_cursor}").json()
168
169 assert len(response["results"]) == 3 # Remaining 3 events
170 assert response["next"] is None
171 assert response["previous"] is not None
172
173
174 def test_cursor_pagination_reverse_ordering():
175 """Test cursor pagination with reverse ordering."""
176
177 response = client.get("/cursor_events_reverse").json()
178
179 assert len(response["results"]) == 10
180 # With reverse ordering, should start from the end
181 assert response["results"][0]["title"] == "Special Event 13"
182 assert response["next"] is not None
183 assert response["previous"] is None
184
185
186 def test_cursor_pagination_end_date_offset():
187 """Test cursor pagination handles duplicate end_date values"""
188
189 response = client.get("/cursor_events_end_date_offset").json()
190
191 # Should handle events with same end_date by using id as secondary ordering
192 assert len(response["results"]) == 2
193
194 # Verify ordering is consistent across pages
195 all_results = []
196 current_response = response
197
198 while True:
199 all_results.extend(current_response["results"])
200 if not current_response["next"]:
201 break
202 next_cursor = current_response["next"].split("cursor=")[1].split("&")[0]
203 current_response = client.get(
204 f"/cursor_events_end_date_offset?cursor={next_cursor}"
205 ).json()
206
207 # Should have all events and maintain consistent ordering
208 assert len(all_results) == 13
209 # Verify no duplicates
210 titles = [result["title"] for result in all_results]
211 assert len(titles) == len(set(titles))
212
213 # Verify results are sorted by start_dates, then by id (implicit in creation order)
214 start_dates = [result["start_date"] for result in all_results]
215 assert start_dates == sorted(start_dates), "Results should be sorted by start_date"
216
217
218 def test_cursor_pagination_end_date_offset_backwards():
219 """Test cursor pagination handles duplicate end_date values iterating backwards"""
220
221 # Start from the last page by getting all pages first
222 response = client.get("/cursor_events_end_date_offset").json()
223
224 # Navigate to the last page
225 current_response = response
226 while current_response["next"]:
227 next_cursor = current_response["next"].split("cursor=")[1].split("&")[0]
228 current_response = client.get(
229 f"/cursor_events_end_date_offset?cursor={next_cursor}"
230 ).json()
231
232 # Now iterate backwards using previous links
233 all_results_backwards = []
234 while True:
235 # Insert at beginning to maintain reverse order
236 all_results_backwards = current_response["results"] + all_results_backwards
237 if not current_response["previous"]:
238 break
239 prev_cursor = current_response["previous"].split("cursor=")[1].split("&")[0]
240 current_response = client.get(
241 f"/cursor_events_end_date_offset?cursor={prev_cursor}"
242 ).json()
243
244 # Should have all events and maintain consistent ordering
245 assert len(all_results_backwards) == 13
246 # Verify no duplicates
247 titles = [result["title"] for result in all_results_backwards]
248 assert len(titles) == len(set(titles))
249
250 # Verify results are sorted by start_date when iterating backwards
251 start_dates = [result["start_date"] for result in all_results_backwards]
252 assert start_dates == sorted(
253 start_dates
254 ), "Results should be sorted by start_date when iterating backwards"
255
256
257 def test_cursor_pagination_default_page_size():
258 """Test cursor pagination with default page size."""
259 # Create test events
260
261 response = client.get("/cursor_events_default_size").json()
262
263 # Should use default page size which is 1000
264 assert len(response["results"]) == 13
265 assert response["results"][0]["title"] == "Event 1"
266 assert response["results"][-1]["title"] == "Special Event 13"
267 assert response["next"] is None
268 assert response["previous"] is None
269
270
271 def test_cursor_pagination_custom_page_size_override():
272 """Test overriding page size in request."""
273 # Create test events
274
275 response = client.get("/cursor_events_default_size?page_size=3").json()
276
277 assert len(response["results"]) == 3
278 assert response["results"][0]["title"] == "Event 1"
279 assert response["results"][-1]["title"] == "Event 3"
280 assert response["next"] is not None
281 assert response["previous"] is None
282
283
284 def test_cursor_pagination_with_custom_params():
285 """Test cursor pagination with additional query parameters."""
286
287 response = client.get(
288 "/cursor_events_with_params?title_filter=Special&page_size=5"
289 ).json()
290
291 # Should filter to events with "Special" in title
292 assert len(response["results"]) == 3
293 assert all("Special" in item["title"] for item in response["results"])
294
295
296 def test_cursor_pagination_invalid_cursor():
297 """Test handling of invalid cursor values."""
298
299 response = client.get("/cursor_events?cursor=invalid&page_size=3")
300
301 assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY
302
303
304 def test_cursor_pagination_empty_cursor():
305 """Test handling of empty cursor."""
306
307 response = client.get("/cursor_events?cursor=&page_size=3").json()
308
309 # Should default to first page
310 assert len(response["results"]) == 3
311 assert response["results"][0]["title"] == "Event 1"
312
313
314 def test_cursor_pagination_no_page_size():
315 """Test cursor pagination without specifying page_size."""
316
317 response = client.get("/cursor_events").json()
318
319 # Should use default page size from settings
320 assert len(response["results"]) >= 1
321 assert "next" in response
322 assert "previous" in response
323 assert "results" in response
324
325
326 def test_cursor_pagination_openapi_schema():
327 """Test that cursor pagination generates correct OpenAPI schema."""
328 schema = api.get_openapi_schema()["paths"]["/api/cursor_events"]["get"]
329
330 parameters = {param["name"]: param for param in schema["parameters"]}
331
332 # Check page_size parameter
333 assert "page_size" in parameters
334 page_size_param = parameters["page_size"]
335 assert page_size_param["in"] == "query"
336 assert page_size_param["required"] is False
337
338 # Check cursor parameter
339 assert "cursor" in parameters
340 cursor_param = parameters["cursor"]
341 assert cursor_param["in"] == "query"
342 assert cursor_param["required"] is False
343 assert {"type": "string"} in cursor_param["schema"]["anyOf"]
344 assert {"type": "null"} in cursor_param["schema"]["anyOf"]
345
346
347 def test_cursor_pagination_response_schema():
348 """Test that cursor pagination generates correct response schema."""
349 schema = api.get_openapi_schema()["paths"]["/api/cursor_events"]["get"]
350 response_schema = schema["responses"][HTTPStatus.OK]["content"]["application/json"][
351 "schema"
352 ]
353
354 # Should have cursor pagination structure (may be a $ref)
355 if "$ref" in response_schema:
356 # Extract the schema name and check it exists in components
357 ref_path = response_schema["$ref"]
358 assert ref_path.startswith("#/components/schemas/")
359 schema_name = ref_path.split("/")[-1]
360 components_schema = api.get_openapi_schema()["components"]["schemas"][
361 schema_name
362 ]
363
364 # Check the referenced schema has the right properties
365 assert "properties" in components_schema
366 properties = components_schema["properties"]
367 else:
368 # Direct inline schema
369 assert "properties" in response_schema
370 properties = response_schema["properties"]
371
372 assert "results" in properties
373 assert "next" in properties
374 assert "previous" in properties
375
376 # Results should be array of items
377 assert properties["results"]["type"] == "array"
378
379
380 def test_cursor_pagination_large_page_size():
381 """Test edge cases for cursor pagination."""
382
383 # Very large page_size
384 response = client.get("/cursor_events?page_size=1000").json()
385 # all available items (10 events + 3 special events)
386 assert len(response["results"]) == 13
387 assert response["next"] is None
388
389
390 def test_cursor_pagination_page_size_of_one():
391 # Page size of 1
392 response = client.get("/cursor_events?page_size=1").json()
393 assert len(response["results"]) == 1
394 assert response["results"][0]["title"] == "Event 1"
395 assert response["next"] is not None
396
397 # Request all pages and check length and order
398 all_results = []
399 current_response = response
400
401 while True:
402 all_results.extend(current_response["results"])
403 if not current_response["next"]:
404 break
405 next_cursor = current_response["next"].split("cursor=")[1].split("&")[0]
406 current_response = client.get(
407 f"/cursor_events?cursor={next_cursor}&page_size=1"
408 ).json()
409
410 # Check total length
411 assert len(all_results) == 13 # 10 events + 3 special events
412
413 # Check order - should be sorted by start_date
414 titles = [result["title"] for result in all_results]
415 expected_titles = [f"Event {i}" for i in range(1, 11)] + [
416 f"Special Event {i}" for i in range(11, 14)
417 ]
418 assert titles == expected_titles
419
420
421 def test_cursor_pagination_empty_queryset():
422 """Test cursor pagination with empty queryset."""
423 # Explicitly clear all events for this test
424 Category.objects.all().delete()
425 Event.objects.all().delete()
426
427 response = client.get("/cursor_events?page_size=5").json()
428
429 assert len(response["results"]) == 0
430 assert response["next"] is None
431 assert response["previous"] is None
432
433
434 @override_settings(NINJA_PAGINATION_PER_PAGE=20)
435 def test_cursor_pagination_settings_override():
436 """Test that Django settings affect cursor pagination."""
437
438 response = client.get("/cursor_events_default_size").json()
439 assert "results" in response
440 assert len(response["results"]) == 13
441
442
443 def test_cursor_pagination_deleted_position():
444 """Test cursor pagination when the cursor position is deleted between requests."""
445
446 # Get first page with page_size=3 to get a cursor
447 first_response = client.get("/cursor_events?page_size=3").json()
448 assert len(first_response["results"]) == 3
449 assert first_response["next"] is not None
450
451 # Extract the cursor for the next page
452 next_cursor = first_response["next"].split("cursor=")[1].split("&")[0]
453
454 # Delete the event that the cursor is pointing to
455 # The cursor should be pointing to Event 4
456 event_to_delete = Event.objects.get(title="Event 4")
457 event_to_delete.delete()
458
459 # Now try to use the cursor - it should still work gracefully
460 # even though the position it was pointing to no longer exists
461 response = client.get(f"/cursor_events?cursor={next_cursor}&page_size=3").json()
462
463 # Should still return results, just continuing from where it can
464 assert len(response["results"]) >= 1
465 assert "next" in response
466 assert "previous" in response
467
468 # Verify we get the remaining events after the deleted position
469 titles = [result["title"] for result in response["results"]]
470 assert "Event 4" not in titles
471 # Should now contain the deleted Event 5
472 assert titles[0] == "Event 5"
473
474
475 def test_cursor_pagination_deleted_position_previous():
476 """Test cursor pagination when the cursor position is deleted between requests using previous cursor."""
477
478 # Get to the last page first
479 response = client.get("/cursor_events?page_size=3").json()
480
481 # Navigate to get a page with a previous cursor
482 while response["next"]:
483 next_cursor = response["next"].split("cursor=")[1].split("&")[0]
484 response = client.get(f"/cursor_events?cursor={next_cursor}&page_size=3").json()
485
486 # Now we should have a previous cursor
487 assert response["previous"] is not None
488 prev_cursor = response["previous"].split("cursor=")[1].split("&")[0]
489
490 # Delete an event that will be referenced by the previous cursor
491
492 event_to_delete = Event.objects.get(title="Special Event 13")
493 event_to_delete.delete()
494
495 # Now try to use the previous cursor - it should still work gracefully
496 # even though the position it was pointing to no longer exists
497 prev_response = client.get(
498 f"/cursor_events?cursor={prev_cursor}&page_size=3"
499 ).json()
500
501 # Should still return results, just continuing from where it can
502 assert len(prev_response["results"]) >= 1
503 assert "next" in prev_response
504 assert "previous" in prev_response
505
506 # Verify we get the remaining events and don't include the deleted one
507 titles = [result["title"] for result in prev_response["results"]]
508 assert "Special Event 13" not in titles
509
510
511 def test_cursor_pagination_last_item_deleted():
512 """Test cursor pagination when the cursor is pointed at the last item, but it is deleted."""
513
514 # Navigate through all pages to get to the last one
515 next_cursor = ""
516
517 while True:
518 response = client.get(f"/cursor_events?cursor={next_cursor}&page_size=3").json()
519 if response["next"] is None:
520 break
521 next_cursor = response["next"].split("cursor=")[1].split("&")[0]
522
523 # Delete the last item (Special Event 13)
524 last_event = Event.objects.get(title="Special Event 13")
525 last_event.delete()
526
527 # Now try to use the cursor that was pointing to the last page
528 # It should handle the deletion gracefully
529 response = client.get(f"/cursor_events?cursor={next_cursor}&page_size=3").json()
530
531 # Should return empty results
532 assert len(response["results"]) == 0
533 assert response["next"] is None
534 assert response["previous"] is not None
535
536
537 # Async versions of all tests
538
539
540 @pytest.mark.skipif(
541 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
542 )
543 @pytest.mark.asyncio
544 async def test_async_cursor_pagination_first_page():
545 """Test first page of cursor pagination with async."""
546
547 response = await async_client.get("/async_cursor_events?page_size=5")
548 response_data = response.json()
549
550 assert len(response_data["results"]) == 5
551 assert response_data["results"][0]["title"] == "Event 1"
552 assert response_data["results"][-1]["title"] == "Event 5"
553 assert response_data["next"] is not None
554 assert response_data["previous"] is None
555
556
557 @pytest.mark.skipif(
558 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
559 )
560 @pytest.mark.asyncio
561 async def test_async_cursor_pagination_with_cursor():
562 """Test navigation using cursor with async."""
563
564 # Get first page to obtain next cursor
565 first_response = await async_client.get("/async_cursor_events")
566 first_response_data = first_response.json()
567
568 assert len(first_response_data["results"]) == 10
569 assert first_response_data["next"] is not None
570
571 if first_response_data["next"]:
572 # we can't rely on `next` being a well-formed URL, because the testclient
573 # httprequest mock does not pass the path, so we extract the cursor instead
574 next_cursor = first_response_data["next"].split("cursor=")[1].split("&")[0]
575
576 # Use cursor to get next page
577 response = await async_client.get(f"/async_cursor_events?cursor={next_cursor}")
578 response_data = response.json()
579
580 assert len(response_data["results"]) == 3 # Remaining 3 events
581 assert response_data["next"] is None
582 assert response_data["previous"] is not None
583
584
585 @pytest.mark.skipif(
586 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
587 )
588 @pytest.mark.asyncio
589 async def test_async_cursor_pagination_reverse_ordering():
590 """Test cursor pagination with reverse ordering with async."""
591
592 response = await async_client.get("/async_cursor_events_reverse")
593 response_data = response.json()
594
595 assert len(response_data["results"]) == 10
596 # With reverse ordering, should start from the end
597 assert response_data["results"][0]["title"] == "Special Event 13"
598 assert response_data["next"] is not None
599 assert response_data["previous"] is None
600
601
602 @pytest.mark.skipif(
603 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
604 )
605 @pytest.mark.asyncio
606 async def test_async_cursor_pagination_end_date_offset():
607 """Test cursor pagination handles duplicate end_date values with async"""
608
609 response = await async_client.get("/async_cursor_events_end_date_offset")
610 response_data = response.json()
611
612 # Should handle events with same end_date by using id as secondary ordering
613 assert len(response_data["results"]) == 2
614
615 # Verify ordering is consistent across pages
616 all_results = []
617 current_response = response_data
618
619 while True:
620 all_results.extend(current_response["results"])
621 if not current_response["next"]:
622 break
623 next_cursor = current_response["next"].split("cursor=")[1].split("&")[0]
624 current_response_obj = await async_client.get(
625 f"/async_cursor_events_end_date_offset?cursor={next_cursor}"
626 )
627 current_response = current_response_obj.json()
628
629 # Should have all events and maintain consistent ordering
630 assert len(all_results) == 13
631 # Verify no duplicates
632 titles = [result["title"] for result in all_results]
633 assert len(titles) == len(set(titles))
634
635 # Verify results are sorted by start_dates, then by id (implicit in creation order)
636 start_dates = [result["start_date"] for result in all_results]
637 assert start_dates == sorted(start_dates), "Results should be sorted by end_date"
638
639
640 @pytest.mark.skipif(
641 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
642 )
643 @pytest.mark.asyncio
644 async def test_async_cursor_pagination_end_date_offset_backwards():
645 """Test cursor pagination handles duplicate end_date values iterating backwards with async"""
646
647 # Start from the last page by getting all pages first
648 response = await async_client.get("/async_cursor_events_end_date_offset")
649 response_data = response.json()
650
651 # Navigate to the last page
652 current_response = response_data
653 while current_response["next"]:
654 next_cursor = current_response["next"].split("cursor=")[1].split("&")[0]
655 current_response_obj = await async_client.get(
656 f"/async_cursor_events_end_date_offset?cursor={next_cursor}"
657 )
658 current_response = current_response_obj.json()
659
660 # Now iterate backwards using previous links
661 all_results_backwards = []
662 while True:
663 # Insert at beginning to maintain reverse order
664 all_results_backwards = current_response["results"] + all_results_backwards
665 if not current_response["previous"]:
666 break
667 prev_cursor = current_response["previous"].split("cursor=")[1].split("&")[0]
668 current_response_obj = await async_client.get(
669 f"/async_cursor_events_end_date_offset?cursor={prev_cursor}"
670 )
671 current_response = current_response_obj.json()
672
673 # Should have all events and maintain consistent ordering
674 assert len(all_results_backwards) == 13
675 # Verify no duplicates
676 titles = [result["title"] for result in all_results_backwards]
677 assert len(titles) == len(set(titles))
678
679 # Verify results are sorted by start_date when iterating backwards
680 start_dates = [result["start_date"] for result in all_results_backwards]
681 assert start_dates == sorted(
682 start_dates
683 ), "Results should be sorted by start_date when iterating backwards"
684
685
686 @pytest.mark.skipif(
687 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
688 )
689 @pytest.mark.asyncio
690 async def test_async_cursor_pagination_default_page_size():
691 """Test cursor pagination with default page size with async."""
692 # Create test events
693
694 response = await async_client.get("/async_cursor_events_default_size")
695 response_data = response.json()
696
697 # Should use default page size which is 1000
698 assert len(response_data["results"]) == 13
699 assert response_data["results"][0]["title"] == "Event 1"
700 assert response_data["results"][-1]["title"] == "Special Event 13"
701 assert response_data["next"] is None
702 assert response_data["previous"] is None
703
704
705 @pytest.mark.skipif(
706 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
707 )
708 @pytest.mark.asyncio
709 async def test_async_cursor_pagination_custom_page_size_override():
710 """Test overriding page size in request with async."""
711 # Create test events
712
713 response = await async_client.get("/async_cursor_events_default_size?page_size=3")
714 response_data = response.json()
715
716 assert len(response_data["results"]) == 3
717 assert response_data["results"][0]["title"] == "Event 1"
718 assert response_data["results"][-1]["title"] == "Event 3"
719 assert response_data["next"] is not None
720 assert response_data["previous"] is None
721
722
723 @pytest.mark.skipif(
724 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
725 )
726 @pytest.mark.asyncio
727 async def test_async_cursor_pagination_with_custom_params():
728 """Test cursor pagination with additional query parameters with async."""
729
730 response = await async_client.get(
731 "/async_cursor_events_with_params?title_filter=Special&page_size=5"
732 )
733 response_data = response.json()
734
735 # Should filter to events with "Special" in title
736 assert len(response_data["results"]) == 3
737 assert all("Special" in item["title"] for item in response_data["results"])
738
739
740 @pytest.mark.skipif(
741 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
742 )
743 @pytest.mark.asyncio
744 async def test_async_cursor_pagination_invalid_cursor():
745 """Test handling of invalid cursor values with async."""
746
747 response = await async_client.get("/async_cursor_events?cursor=invalid&page_size=3")
748
749 assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY
750
751
752 @pytest.mark.skipif(
753 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
754 )
755 @pytest.mark.asyncio
756 async def test_async_cursor_pagination_empty_cursor():
757 """Test handling of empty cursor with async."""
758
759 response = await async_client.get("/async_cursor_events?cursor=&page_size=3")
760 response_data = response.json()
761
762 # Should default to first page
763 assert len(response_data["results"]) == 3
764 assert response_data["results"][0]["title"] == "Event 1"
765
766
767 @pytest.mark.skipif(
768 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
769 )
770 @pytest.mark.asyncio
771 async def test_async_cursor_pagination_no_page_size():
772 """Test cursor pagination without specifying page_size with async."""
773
774 response = await async_client.get("/async_cursor_events")
775 response_data = response.json()
776
777 # Should use default page size from settings
778 assert len(response_data["results"]) >= 1
779 assert "next" in response_data
780 assert "previous" in response_data
781 assert "results" in response_data
782
783
784 @pytest.mark.skipif(
785 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
786 )
787 @pytest.mark.asyncio
788 async def test_async_cursor_pagination_large_page_size():
789 """Test edge cases for cursor pagination with async."""
790
791 # Very large page_size
792 response = await async_client.get("/async_cursor_events?page_size=1000")
793 response_data = response.json()
794 # all available items (10 events + 3 special events)
795 assert len(response_data["results"]) == 13
796 assert response_data["next"] is None
797
798
799 @pytest.mark.skipif(
800 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
801 )
802 @pytest.mark.asyncio
803 async def test_async_cursor_pagination_page_size_of_one():
804 # Page size of 1 with async
805 response = await async_client.get("/async_cursor_events?page_size=1")
806 response_data = response.json()
807 assert len(response_data["results"]) == 1
808 assert response_data["results"][0]["title"] == "Event 1"
809 assert response_data["next"] is not None
810
811 # Request all pages and check length and order
812 all_results = []
813 current_response = response_data
814
815 while True:
816 all_results.extend(current_response["results"])
817 if not current_response["next"]:
818 break
819 next_cursor = current_response["next"].split("cursor=")[1].split("&")[0]
820 current_response_obj = await async_client.get(
821 f"/async_cursor_events?cursor={next_cursor}&page_size=1"
822 )
823 current_response = current_response_obj.json()
824
825 # Check total length
826 assert len(all_results) == 13 # 10 events + 3 special events
827
828 # Check order - should be sorted by start_date
829 titles = [result["title"] for result in all_results]
830 expected_titles = [f"Event {i}" for i in range(1, 11)] + [
831 f"Special Event {i}" for i in range(11, 14)
832 ]
833 assert titles == expected_titles
834
835
836 @pytest.mark.skipif(
837 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
838 )
839 @pytest.mark.asyncio
840 async def test_async_cursor_pagination_empty_queryset():
841 """Test cursor pagination with empty queryset with async."""
842 # Explicitly clear all events for this test using async-safe methods
843 await Category.objects.all().adelete()
844 await Event.objects.all().adelete()
845
846 response = await async_client.get("/async_cursor_events?page_size=5")
847 response_data = response.json()
848
849 assert len(response_data["results"]) == 0
850 assert response_data["next"] is None
851 assert response_data["previous"] is None
852
853
854 @pytest.mark.skipif(
855 django.VERSION < (4, 1), reason="Async QuerySet iteration requires Django 4.1+"
856 )
857 @pytest.mark.asyncio
858 @override_settings(NINJA_PAGINATION_PER_PAGE=20)
859 async def test_async_cursor_pagination_settings_override():
860 """Test that Django settings affect cursor pagination with async."""
861
862 response = await async_client.get("/async_cursor_events_default_size")
863 response_data = response.json()
864 assert "results" in response_data
865 assert len(response_data["results"]) == 13
866
867
868 @pytest.mark.skipif(
869 django.VERSION < (4, 2), reason="Model.adelete() requires Django 4.2+"
870 )
871 @pytest.mark.asyncio
872 async def test_async_cursor_pagination_deleted_position():
873 """Test cursor pagination when the cursor position is deleted between requests with async."""
874
875 # Get first page with page_size=3 to get a cursor
876 first_response = await async_client.get("/async_cursor_events?page_size=3")
877 first_response_data = first_response.json()
878 assert len(first_response_data["results"]) == 3
879 assert first_response_data["next"] is not None
880
881 # Extract the cursor for the next page
882 next_cursor = first_response_data["next"].split("cursor=")[1].split("&")[0]
883
884 # Delete the event that the cursor is pointing to
885 # The cursor should be pointing to Event 4
886 event_to_delete = await Event.objects.aget(title="Event 4")
887 await event_to_delete.adelete()
888
889 # Now try to use the cursor - it should still work gracefully
890 # even though the position it was pointing to no longer exists
891 response = await async_client.get(
892 f"/async_cursor_events?cursor={next_cursor}&page_size=3"
893 )
894 response_data = response.json()
895
896 # Should still return results, just continuing from where it can
897 assert len(response_data["results"]) >= 1
898 assert "next" in response_data
899 assert "previous" in response_data
900
901 # Verify we get the remaining events after the deleted position
902 titles = [result["title"] for result in response_data["results"]]
903 assert "Event 4" not in titles
904 # Should now contain the deleted Event 5
905 assert titles[0] == "Event 5"
906
907
908 @pytest.mark.skipif(
909 django.VERSION < (4, 2), reason="Model.adelete() requires Django 4.2+"
910 )
911 @pytest.mark.asyncio
912 async def test_async_cursor_pagination_deleted_position_previous():
913 """Test cursor pagination when the cursor position is deleted between requests using previous cursor with async."""
914
915 # Get to the last page first
916 response = await async_client.get("/async_cursor_events?page_size=3")
917 response_data = response.json()
918
919 # Navigate to get a page with a previous cursor
920 while response_data["next"]:
921 next_cursor = response_data["next"].split("cursor=")[1].split("&")[0]
922 response = await async_client.get(
923 f"/async_cursor_events?cursor={next_cursor}&page_size=3"
924 )
925 response_data = response.json()
926
927 # Now we should have a previous cursor
928 assert response_data["previous"] is not None
929 prev_cursor = response_data["previous"].split("cursor=")[1].split("&")[0]
930
931 # Delete an event that will be referenced by the previous cursor
932
933 event_to_delete = await Event.objects.aget(title="Special Event 13")
934 await event_to_delete.adelete()
935
936 # Now try to use the previous cursor - it should still work gracefully
937 # even though the position it was pointing to no longer exists
938 prev_response = await async_client.get(
939 f"/async_cursor_events?cursor={prev_cursor}&page_size=3"
940 )
941 prev_response_data = prev_response.json()
942
943 # Should still return results, just continuing from where it can
944 assert len(prev_response_data["results"]) >= 1
945 assert "next" in prev_response_data
946 assert "previous" in prev_response_data
947
948 # Verify we get the remaining events and don't include the deleted one
949 titles = [result["title"] for result in prev_response_data["results"]]
950 assert "Special Event 13" not in titles
951
952
953 @pytest.mark.skipif(
954 django.VERSION < (4, 2), reason="Model.adelete() requires Django 4.2+"
955 )
956 @pytest.mark.asyncio
957 async def test_async_cursor_pagination_last_item_deleted():
958 """Test cursor pagination when the cursor is pointed at the last item, but it is deleted with async."""
959
960 # Navigate through all pages to get to the last one
961 next_cursor = ""
962
963 while True:
964 response = await async_client.get(
965 f"/async_cursor_events?cursor={next_cursor}&page_size=3"
966 )
967 response_data = response.json()
968 if response_data["next"] is None:
969 break
970 next_cursor = response_data["next"].split("cursor=")[1].split("&")[0]
971
972 # Delete the last item (Special Event 13)
973 last_event = await Event.objects.aget(title="Special Event 13")
974 await last_event.adelete()
975
976 # Now try to use the cursor that was pointing to the last page
977 # It should handle the deletion gracefully
978 response = await async_client.get(
979 f"/async_cursor_events?cursor={next_cursor}&page_size=3"
980 )
981 response_data = response.json()
982
983 # Should return empty results
984 assert len(response_data["results"]) == 0
985 assert response_data["next"] is None
986 assert response_data["previous"] is not None