Debian Codegraph @

tests/test_pagination_async.py

raw symbols SCIP
1 import asyncio
2 from typing import Any, List
3
4 import django
5 import pytest
6 from django.db.models import QuerySet
7 from someapp.models import Category
8
9 from ninja import NinjaAPI, Schema
10 from ninja.errors import ConfigError
11 from ninja.pagination import (
12 AsyncPaginationBase,
13 PageNumberPagination,
14 PaginationBase,
15 paginate,
16 )
17 from ninja.testing import TestAsyncClient
18
19 api = NinjaAPI()
20
21 ITEMS = list(range(100))
22
23
24 class NoAsyncPagination(PaginationBase):
25 # only offset param, defaults to 5 per page
26 class Input(Schema):
27 skip: int
28
29 class Output(Schema):
30 items: List[Any]
31 count: str
32 skip: int
33
34 def paginate_queryset(self, items, pagination: Input, **params):
35 skip = pagination.skip
36 return {
37 "items": items[skip : skip + 5],
38 "count": "many",
39 "skip": skip,
40 }
41
42
43 class AsyncNoOutputPagination(AsyncPaginationBase):
44 # Outputs items without count attribute
45 class Input(Schema):
46 skip: int
47
48 Output = None
49
50 def paginate_queryset(self, items, pagination: Input, **params):
51 skip = pagination.skip
52 return items[skip : skip + 5]
53
54 async def apaginate_queryset(self, items, pagination: Input, **params):
55 await asyncio.sleep(0)
56 skip = pagination.skip
57 return items[skip : skip + 5]
58
59 async def _items_count(self, queryset: QuerySet) -> int:
60 try:
61 # forcing to find queryset.count instead of list.count:
62 return queryset.all().count()
63 except AttributeError:
64 await asyncio.sleep(0)
65 return len(queryset)
66
67
68 class AsyncNoPagination(AsyncPaginationBase):
69 """
70 Async pagination class that returns all records without slicing.
71 Does not define its own Input - uses empty PaginationBase.Input.
72 This tests the bug fix from https://github.com/vitalik/django-ninja/issues/1564
73 """
74
75 async def apaginate_queryset(
76 self, items, pagination: PaginationBase.Input, **params
77 ):
78 await asyncio.sleep(0)
79 return {
80 "count": await self._aitems_count(items),
81 "items": items,
82 }
83
84 def paginate_queryset(self, items, pagination: PaginationBase.Input, **params):
85 return {
86 "count": self._items_count(items),
87 "items": items,
88 }
89
90
91 @pytest.mark.asyncio
92 async def test_async_config_error():
93 api = NinjaAPI()
94
95 with pytest.raises(
96 ConfigError, match="Pagination class not configured for async requests"
97 ):
98
99 @api.get("/items_async_undefined", response=List[int])
100 @paginate(NoAsyncPagination)
101 async def items_async_undefined(request, **kwargs):
102 return ITEMS
103
104
105 @pytest.mark.asyncio
106 async def test_async_custom_pagination():
107 api = NinjaAPI()
108
109 @api.get("/items_async", response=List[int])
110 @paginate(AsyncNoOutputPagination)
111 async def items_async(request):
112 return ITEMS
113
114 client = TestAsyncClient(api)
115
116 response = await client.get("/items_async?skip=10")
117 assert response.json() == [10, 11, 12, 13, 14]
118
119
120 @pytest.mark.asyncio
121 async def test_async_default():
122 api = NinjaAPI()
123
124 @api.get("/items_default", response=List[int])
125 @paginate # WITHOUT brackets (should use default pagination)
126 async def items_default(request, someparam: int = 0, **kwargs):
127 await asyncio.sleep(0)
128 return ITEMS
129
130 client = TestAsyncClient(api)
131
132 response = await client.get("/items_default?limit=10")
133 assert response.json() == {"items": ITEMS[:10], "count": 100}
134
135
136 @pytest.mark.asyncio
137 async def test_async_page_number():
138 api = NinjaAPI()
139
140 @api.get("/items_page_number", response=List[Any])
141 @paginate(PageNumberPagination, page_size=10, pass_parameter="page_info")
142 async def items_page_number(request, **kwargs):
143 return ITEMS + [kwargs["page_info"]]
144
145 client = TestAsyncClient(api)
146
147 response = await client.get("/items_page_number?page=11")
148 assert response.json() == {"items": [{"page": 11, "page_size": None}], "count": 101}
149
150
151 @pytest.mark.skipif(django.VERSION[:2] < (5, 0), reason="Requires Django 5.0+")
152 @pytest.mark.django_db
153 @pytest.mark.asyncio
154 async def test_test_async_pagination():
155 await Category.objects.acreate(title="cat1")
156 await Category.objects.acreate(title="cat2")
157 assert await Category.objects.acount() == 2
158
159 class CatSchema(Schema):
160 title: str
161
162 api = NinjaAPI()
163
164 @api.get("/cats", response=list[CatSchema])
165 @paginate
166 async def cats_paginated_limit_offset(request):
167 return Category.objects.order_by("id")
168
169 @api.get("/cats-pages", response=list[CatSchema])
170 @paginate(PageNumberPagination)
171 async def cats_paginated_page_number(request):
172 return Category.objects.order_by("id")
173
174 client = TestAsyncClient(api)
175
176 response = await client.get("/cats")
177 assert response.status_code == 200
178 assert response.json() == {
179 "items": [{"title": "cat1"}, {"title": "cat2"}],
180 "count": 2,
181 }
182
183 response = await client.get("/cats?offset=1")
184 assert response.status_code == 200
185 print(response.json())
186 assert response.json() == {
187 "items": [{"title": "cat2"}],
188 "count": 2,
189 }
190
191 response = await client.get("/cats-pages")
192 assert response.status_code == 200
193 assert response.json() == {
194 "items": [{"title": "cat1"}, {"title": "cat2"}],
195 "count": 2,
196 }
197
198 response = await client.get("/cats-pages?page=1")
199 assert response.status_code == 200
200 assert response.json() == {
201 "items": [{"title": "cat1"}, {"title": "cat2"}],
202 "count": 2,
203 }
204
205
206 @pytest.mark.asyncio
207 async def test_async_no_pagination_without_query_params():
208 """
209 Test that AsyncNoPagination works without any query parameters.
210 Tests the async branch of the bug fix from https://github.com/vitalik/django-ninja/issues/1564
211
212 AsyncNoPagination doesn't define any Input fields (uses empty PaginationBase.Input),
213 so it should NOT require any query parameters.
214 """
215 api = NinjaAPI()
216
217 @api.get("/items_no_pagination_async", response=List[int])
218 @paginate(AsyncNoPagination)
219 async def items_no_pagination_async(request):
220 await asyncio.sleep(0)
221 return ITEMS
222
223 client = TestAsyncClient(api)
224
225 response = await client.get("/items_no_pagination_async")
226 assert response.status_code == 200
227 result = response.json()
228 assert result == {"count": 100, "items": ITEMS}
229
230 # Check OpenAPI schema - should have no required parameters
231 schema = api.get_openapi_schema()["paths"]["/api/items_no_pagination_async"]["get"]
232 params = schema.get("parameters", [])
233
234 # If there are any parameters, they should all be optional
235 for param in params:
236 assert (
237 param.get("required", False) is False
238 ), f"Parameter {param['name']} should not be required"