Debian Codegraph @

tests/test_pagination.py

raw symbols SCIP
1 import importlib
2 from sys import version_info
3 from typing import Any, List
4
5 import pytest
6 from django.test import override_settings
7 from pydantic.errors import PydanticSchemaGenerationError
8
9 from ninja import NinjaAPI, Schema
10 from ninja.constants import NOT_SET
11 from ninja.errors import ConfigError
12 from ninja.operation import Operation
13 from ninja.pagination import (
14 LimitOffsetPagination,
15 PageNumberPagination,
16 PaginationBase,
17 _find_collection_response,
18 make_response_paginated,
19 paginate,
20 )
21 from ninja.testing import TestClient
22
23 api = NinjaAPI()
24
25
26 ITEMS = list(range(100))
27
28
29 class CustomPagination(PaginationBase):
30 # only offset param, defaults to 5 per page
31 class Input(Schema):
32 skip: int
33
34 class Output(Schema):
35 items: List[Any]
36 count: str
37 skip: int
38
39 def paginate_queryset(self, items, pagination: Input, **params):
40 skip = pagination.skip
41 return {
42 "items": items[skip : skip + 5],
43 "count": "many",
44 "skip": skip,
45 }
46
47
48 class NoOutputPagination(PaginationBase):
49 # Outputs items without count attribute
50 class Input(Schema):
51 skip: int
52
53 Output = None
54
55 def paginate_queryset(self, items, pagination: Input, **params):
56 skip = pagination.skip
57 return items[skip : skip + 5]
58
59
60 class ResultsPaginator(PaginationBase):
61 "Use 'results' instead of 'items' for the output"
62
63 class Input(Schema):
64 skip: int
65
66 class Output(Schema):
67 results: List[int]
68 count: int
69 skip: int
70
71 items_attribute: str = "results"
72
73 def paginate_queryset(self, items, pagination: Input, **params):
74 skip = pagination.skip
75 return {
76 "results": items[skip : skip + 5],
77 "count": self._items_count(items),
78 "skip": skip,
79 }
80
81
82 class NextPrevPagination(PaginationBase):
83 # only offset param, defaults to 5 per page
84 class Input(Schema):
85 skip: int
86
87 class Output(Schema):
88 items: List[Any]
89 next: str = None
90 prev: str = None
91
92 def paginate_queryset(self, items, pagination: Input, request, **params):
93 skip = pagination.skip
94 prev_skip = skip - 5
95 if prev_skip < 0:
96 prev_skip = 0
97 return {
98 "items": items[skip : skip + 5],
99 "next": request.build_absolute_uri(f"?skip={skip + 5}"),
100 "prev": request.build_absolute_uri(f"?skip={prev_skip}"),
101 }
102
103
104 class CustomItemsLimitOffsetPagination(LimitOffsetPagination):
105 """Minimal LimitOffsetPagination with custom items_attribute."""
106
107 items_attribute = "results"
108
109 class Output(Schema):
110 results: List[int]
111 count: int
112
113
114 class CustomItemsPageNumberPagination(PageNumberPagination):
115 """Minimal PageNumberPagination with custom items_attribute."""
116
117 items_attribute = "results"
118
119 class Output(Schema):
120 results: List[int]
121 count: int
122
123
124 class NoPagination(PaginationBase):
125 """
126 Pagination class that returns all records without slicing.
127 Does not define its own Input - uses empty PaginationBase.Input.
128 This reproduces bug from https://github.com/vitalik/django-ninja/issues/1564
129 """
130
131 def paginate_queryset(self, items, pagination: PaginationBase.Input, **params):
132 return {
133 "count": self._items_count(items),
134 "items": items,
135 }
136
137
138 @api.get("/items_1", response=List[int])
139 @paginate # WITHOUT brackets (should use default pagination)
140 def items_1(request, **kwargs):
141 return ITEMS
142
143
144 @api.get("/items_2", response=List[int])
145 @paginate() # with brackets (should use default pagination)
146 def items_2(request, someparam: int = 0, **kwargs):
147 # also having custom param `someparam` - that should not be lost
148 return ITEMS
149
150
151 @api.get("/items_3", response=List[int])
152 @paginate(CustomPagination)
153 def items_3(request, **kwargs):
154 return ITEMS
155
156
157 @api.get("/items_4", response=List[int])
158 @paginate(PageNumberPagination, page_size=10)
159 def items_4(request, **kwargs):
160 return ITEMS
161
162
163 @api.get("/items_5", response=List[int])
164 @paginate(PageNumberPagination, page_size=10)
165 def items_5(request):
166 return ITEMS
167
168
169 @api.get("/items_6", response={101: int, 200: List[Any]})
170 @paginate(PageNumberPagination, page_size=10, pass_parameter="page_info")
171 def items_6(request, **kwargs):
172 return ITEMS + [kwargs["page_info"]]
173
174
175 @api.get("/items_7", response=List[int])
176 @paginate(NoOutputPagination)
177 def items_7(request):
178 return list(range(15))
179
180
181 @api.get("/items_8", response=List[int])
182 @paginate(ResultsPaginator)
183 def items_8(request):
184 return list(range(1000))
185
186
187 @api.get("/items_9", response=List[int])
188 @paginate(NextPrevPagination)
189 def items_9(request):
190 return list(range(100))
191
192
193 @api.get("/items_10", response=List[int])
194 @paginate(PageNumberPagination, page_size=10, max_page_size=20)
195 def items_10(request):
196 return ITEMS
197
198
199 @api.get("/items_11", response=List[int])
200 @paginate(CustomItemsLimitOffsetPagination)
201 def items_11(request):
202 return list(range(100))
203
204
205 @api.get("/items_12", response=List[int])
206 @paginate(CustomItemsPageNumberPagination)
207 def items_12(request):
208 return list(range(100))
209
210
211 @api.get("/items_no_pagination", response=List[int])
212 @paginate(NoPagination)
213 def items_no_pagination(request):
214 return ITEMS
215
216
217 client = TestClient(api)
218
219
220 def test_case1():
221 response = client.get("/items_1?limit=10").json()
222 assert response == {"items": ITEMS[:10], "count": 100}
223
224 schema = api.get_openapi_schema()["paths"]["/api/items_1"]["get"]
225 # print(schema)
226 assert schema["parameters"] == [
227 {
228 "in": "query",
229 "name": "limit",
230 "schema": {
231 "title": "Limit",
232 "default": 100,
233 "minimum": 1,
234 "type": "integer",
235 },
236 "required": False,
237 },
238 {
239 "in": "query",
240 "name": "offset",
241 "schema": {
242 "title": "Offset",
243 "default": 0,
244 "minimum": 0,
245 "type": "integer",
246 },
247 "required": False,
248 },
249 ]
250
251
252 def test_case2():
253 response = client.get("/items_2?limit=10").json()
254 assert response == {"items": ITEMS[:10], "count": 100}
255
256 schema = api.get_openapi_schema()["paths"]["/api/items_2"]["get"]
257 # print(schema["parameters"])
258 assert schema["parameters"] == [
259 {
260 "in": "query",
261 "name": "someparam",
262 "schema": {"default": 0, "title": "Someparam", "type": "integer"},
263 "required": False,
264 },
265 {
266 "in": "query",
267 "name": "limit",
268 "schema": {
269 "title": "Limit",
270 "default": 100,
271 "minimum": 1,
272 "type": "integer",
273 },
274 "required": False,
275 },
276 {
277 "in": "query",
278 "name": "offset",
279 "schema": {
280 "title": "Offset",
281 "default": 0,
282 "minimum": 0,
283 "type": "integer",
284 },
285 "required": False,
286 },
287 ]
288
289
290 def test_case3():
291 response = client.get("/items_3?skip=5").json()
292 assert response == {"items": ITEMS[5:10], "count": "many", "skip": 5}
293
294 schema = api.get_openapi_schema()["paths"]["/api/items_3"]["get"]
295 # print(schema)
296 assert schema["parameters"] == [
297 {
298 "in": "query",
299 "name": "skip",
300 "schema": {"title": "Skip", "type": "integer"},
301 "required": True,
302 }
303 ]
304
305
306 def test_case4():
307 response = client.get("/items_4?page=2").json()
308 assert response == {"items": ITEMS[10:20], "count": 100}
309
310 schema = api.get_openapi_schema()["paths"]["/api/items_4"]["get"]
311 # print(schema)
312 assert schema["parameters"] == [
313 {
314 "in": "query",
315 "name": "page",
316 "schema": {
317 "title": "Page",
318 "default": 1,
319 "minimum": 1,
320 "type": "integer",
321 },
322 "required": False,
323 },
324 {
325 "in": "query",
326 "name": "page_size",
327 "schema": {
328 "anyOf": [{"minimum": 1, "type": "integer"}, {"type": "null"}],
329 "title": "Page Size",
330 },
331 "required": False,
332 },
333 ]
334
335
336 def test_case4_page_size():
337 response = client.get("/items_4?page=2&page_size=20").json()
338 assert response == {"items": ITEMS[20:40], "count": 100}
339
340 schema = api.get_openapi_schema()["paths"]["/api/items_4"]["get"]
341 # print(schema)
342 assert schema["parameters"] == [
343 {
344 "in": "query",
345 "name": "page",
346 "schema": {
347 "title": "Page",
348 "default": 1,
349 "minimum": 1,
350 "type": "integer",
351 },
352 "required": False,
353 },
354 {
355 "in": "query",
356 "name": "page_size",
357 "schema": {
358 "anyOf": [{"minimum": 1, "type": "integer"}, {"type": "null"}],
359 "title": "Page Size",
360 },
361 "required": False,
362 },
363 ]
364
365
366 def test_case4_no_page_param():
367 response = client.get("/items_4?page_size=20").json()
368 assert response == {"items": ITEMS[0:20], "count": 100}
369
370 schema = api.get_openapi_schema()["paths"]["/api/items_4"]["get"]
371 # print(schema)
372 assert schema["parameters"] == [
373 {
374 "in": "query",
375 "name": "page",
376 "schema": {
377 "title": "Page",
378 "default": 1,
379 "minimum": 1,
380 "type": "integer",
381 },
382 "required": False,
383 },
384 {
385 "in": "query",
386 "name": "page_size",
387 "schema": {
388 "anyOf": [{"minimum": 1, "type": "integer"}, {"type": "null"}],
389 "title": "Page Size",
390 },
391 "required": False,
392 },
393 ]
394
395
396 def test_case4_out_of_range():
397 response = client.get("/items_4?page=2&page_size=100").json()
398 assert response == {"items": [], "count": 100}
399
400 schema = api.get_openapi_schema()["paths"]["/api/items_4"]["get"]
401 # print(schema)
402 assert schema["parameters"] == [
403 {
404 "in": "query",
405 "name": "page",
406 "schema": {
407 "title": "Page",
408 "default": 1,
409 "minimum": 1,
410 "type": "integer",
411 },
412 "required": False,
413 },
414 {
415 "in": "query",
416 "name": "page_size",
417 "schema": {
418 "anyOf": [{"minimum": 1, "type": "integer"}, {"type": "null"}],
419 "title": "Page Size",
420 },
421 "required": False,
422 },
423 ]
424
425
426 def test_case5_no_kwargs():
427 response = client.get("/items_5?page=2").json()
428 assert response == {"items": ITEMS[10:20], "count": 100}
429
430 schema = api.get_openapi_schema()["paths"]["/api/items_5"]["get"]
431
432 assert schema["parameters"] == [
433 {
434 "in": "query",
435 "name": "page",
436 "schema": {
437 "title": "Page",
438 "default": 1,
439 "minimum": 1,
440 "type": "integer",
441 },
442 "required": False,
443 },
444 {
445 "in": "query",
446 "name": "page_size",
447 "schema": {
448 "anyOf": [{"minimum": 1, "type": "integer"}, {"type": "null"}],
449 "title": "Page Size",
450 },
451 "required": False,
452 },
453 ]
454
455
456 def test_case6_pass_param_kwargs():
457 page = 11
458 response = client.get(f"/items_6?page={page}").json()
459 assert response == {"items": [{"page": 11, "page_size": None}], "count": 101}
460
461 schema = api.get_openapi_schema()["paths"]["/api/items_6"]["get"]
462
463 assert schema["parameters"] == [
464 {
465 "in": "query",
466 "name": "page",
467 "schema": {
468 "title": "Page",
469 "default": 1,
470 "minimum": 1,
471 "type": "integer",
472 },
473 "required": False,
474 },
475 {
476 "in": "query",
477 "name": "page_size",
478 "schema": {
479 "anyOf": [{"minimum": 1, "type": "integer"}, {"type": "null"}],
480 "title": "Page Size",
481 },
482 "required": False,
483 },
484 ]
485
486
487 def test_case7():
488 response = client.get("/items_7?skip=10").json()
489 assert response == [10, 11, 12, 13, 14]
490
491 schema = api.get_openapi_schema()["paths"]["/api/items_7"]["get"]
492 response = schema["responses"][200]["content"]["application/json"]["schema"]
493
494 assert response == {
495 "title": "Response",
496 "type": "array",
497 "items": {"type": "integer"},
498 }
499
500
501 def test_case8():
502 response = client.get("/items_8?skip=5").json()
503 assert response == {"results": [5, 6, 7, 8, 9], "count": 1000, "skip": 5}
504
505
506 def test_case9():
507 response = client.get("/items_9?skip=5").json()
508 assert response == {
509 "items": [5, 6, 7, 8, 9],
510 "next": "http://testlocation/?skip=10",
511 "prev": "http://testlocation/?skip=0",
512 }
513
514
515 def test_case10_max_page_size():
516 response = client.get("/items_10?page=2&page_size=30").json()
517 assert response == {"items": ITEMS[20:40], "count": 100}
518
519 schema = api.get_openapi_schema()["paths"]["/api/items_10"]["get"]
520
521 assert schema["parameters"] == [
522 {
523 "in": "query",
524 "name": "page",
525 "schema": {
526 "title": "Page",
527 "default": 1,
528 "minimum": 1,
529 "type": "integer",
530 },
531 "required": False,
532 },
533 {
534 "in": "query",
535 "name": "page_size",
536 "schema": {
537 "anyOf": [{"minimum": 1, "type": "integer"}, {"type": "null"}],
538 "title": "Page Size",
539 },
540 "required": False,
541 },
542 ]
543
544
545 @override_settings(NINJA_PAGINATION_MAX_LIMIT=1000)
546 def test_10_max_limit_set():
547 # reload to apply django settings
548 from ninja import conf, pagination
549
550 importlib.reload(conf)
551 importlib.reload(pagination)
552 new_api = NinjaAPI()
553 new_client = TestClient(new_api)
554
555 @new_api.get("/items_10", response=List[int])
556 @paginate # LimitOffsetPagination is set as default
557 def items_10(request, **kwargs):
558 return ITEMS
559
560 response = new_client.get("/items_10?limit=1000").json()
561 assert response == {"items": ITEMS[:1000], "count": 100}
562
563 schema = new_api.get_openapi_schema()["paths"]["/api/items_10"]["get"]
564 # print(schema)
565 assert schema["parameters"] == [
566 {
567 "in": "query",
568 "name": "limit",
569 "schema": {
570 "title": "Limit",
571 "default": 100,
572 "minimum": 1,
573 "maximum": 1000,
574 "type": "integer",
575 },
576 "required": False,
577 },
578 {
579 "in": "query",
580 "name": "offset",
581 "schema": {
582 "title": "Offset",
583 "default": 0,
584 "minimum": 0,
585 "type": "integer",
586 },
587 "required": False,
588 },
589 ]
590
591
592 @override_settings(NINJA_PAGINATION_MAX_LIMIT=1000)
593 def test_11_max_limit_set_and_exceeded():
594 # reload to apply django settings
595 from ninja import conf, pagination
596
597 importlib.reload(conf)
598 importlib.reload(pagination)
599 new_api = NinjaAPI()
600 new_client = TestClient(new_api)
601
602 @new_api.get("/items_11", response=List[int])
603 @paginate # LimitOffsetPagination is set as default
604 def items_11(request, **kwargs):
605 return ITEMS
606
607 response = new_client.get("/items_11?limit=1001").json()
608 assert response == {
609 "detail": [
610 {
611 "ctx": {"le": 1000},
612 "loc": ["query", "limit"],
613 "msg": "Input should be less than or equal to 1000",
614 "type": "less_than_equal",
615 }
616 ]
617 }
618
619
620 def test_case11():
621 response = client.get("/items_11").json()
622 assert response == {"results": list(range(100)), "count": 100}
623
624
625 def test_case12():
626 response = client.get("/items_12").json()
627 assert response == {"results": list(range(100)), "count": 100}
628
629
630 def test_config_error_None():
631 with pytest.raises(ConfigError):
632
633 @api.get("/invalid1", response={200: None})
634 @paginate
635 def invalid1(request):
636 pass
637
638
639 def test_config_error_NOT_SET():
640 with pytest.raises(ConfigError):
641
642 @api.get("/invalid2")
643 @paginate
644 def invalid2(request):
645 pass
646
647
648 @pytest.mark.skipif(version_info < (3, 11), reason="Not needed at this Python version")
649 def test_pagination_works_with_unnamed_classes():
650 """
651 This test lets you check that the typing.Any case handled in `ninja.pagination.make_response_paginated`
652 works for Python>=3.11, as a typing.Any does possess the __name__ attribute past that version
653 """
654 operation = Operation("/whatever", ["GET"], lambda: None, response=List[int])
655 operation.response_models[200].__annotations__["response"] = List[object()]
656 with pytest.raises(
657 PydanticSchemaGenerationError
658 ): # It does fail after we passed the logic that we are testing
659 make_response_paginated(LimitOffsetPagination, operation)
660
661
662 def test_no_pagination_without_query_params():
663 """
664 Test that NoPagination works without any query parameters.
665 Reproduces bug from https://github.com/vitalik/django-ninja/issues/1564
666
667 NoPagination doesn't define any Input fields (uses empty PaginationBase.Input),
668 so it should NOT require any query parameters.
669 """
670 response = client.get("/items_no_pagination")
671 if response.status_code != 200:
672 print(f"Status: {response.status_code}")
673 print(f"Response: {response.json()}")
674 assert response.status_code == 200
675 result = response.json()
676 assert result == {"count": 100, "items": ITEMS}
677
678 # Check OpenAPI schema - should have no required parameters
679 schema = api.get_openapi_schema()["paths"]["/api/items_no_pagination"]["get"]
680 params = schema.get("parameters", [])
681
682 # If there are any parameters, they should all be optional
683 for param in params:
684 assert (
685 param.get("required", False) is False
686 ), f"Parameter {param['name']} should not be required"
687
688
689 def test_find_collection_response_skips_none_and_not_set():
690 """Test that _find_collection_response skips None and NOT_SET response models."""
691
692 class ItemSchema(Schema):
693 id: int
694
695 # Create operation with a collection response
696 operation = Operation("/test", ["GET"], lambda: None, response=List[ItemSchema])
697
698 # Manually add None and NOT_SET response models before the collection one
699 original_200 = operation.response_models[200]
700 operation.response_models = {
701 204: None, # Should be skipped
702 404: NOT_SET, # Should be skipped
703 200: original_200, # Collection type - should be found
704 }
705
706 # Should find the collection response at 200, skipping 204 and 404
707 status_code, item_schema = _find_collection_response(operation)
708 assert status_code == 200
709 assert item_schema is ItemSchema
710
711
712 def test_find_collection_response_raises_when_no_collection():
713 """Test that _find_collection_response raises ConfigError when no collection response."""
714
715 class ItemSchema(Schema):
716 id: int
717
718 # Create operation with a non-collection response
719 operation = Operation("/test", ["GET"], lambda: None, response=ItemSchema)
720
721 # Should raise ConfigError since ItemSchema is not a collection
722 with pytest.raises(ConfigError, match="no collection response"):
723 _find_collection_response(operation)