Hey everyone, I’ve been using Django DRF and I’m facing some issues creating unit tests to make sure my pagination is working properly.
I tried using the RequestFactory and the Client to generate a request to pass to the pagination function but the requests created don’t come with a query_params making the unit-tests fail.
from django.test import TestCase
from django.test.client import Client
from django.contrib.sessions.middleware import SessionMiddleware
from rest_framework.test import APIRequestFactory, APIClient
from rest_framework.authtoken.models import Token
from trends.common.pagination import StandardPagination
class StandardPaginationTestCase(TestCase):
def setUp(self):
self.pagination = StandardPagination()
self.factory = APIRequestFactory()
def test_pagination(self):
# Create a request
request = self.factory.get("/query", query_params={"page": 1, "page_size": 10})
# Create a dummy queryset
queryset = [
"item1",
"item2",
"item3",
"item4",
"item5",
"item6",
"item7",
"item8",
"item9",
"item10",
]
# Paginate the queryset
paginated_queryset = self.pagination.paginate_queryset(queryset, request)
# Check if pagination is working correctly
self.assertEqual(len(paginated_queryset), 10)
self.assertEqual(paginated_queryset[0], "item1")
Error:
Traceback (most recent call last):
File "/var/lib/trends_backend/tests/common/test_pagination.py", line 37, in test_pagination
paginated_queryset = self.pagination.paginate_queryset(queryset, request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/rest_framework/pagination.py", line 204, in paginate_queryset
page_size = self.get_page_size(request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/rest_framework/pagination.py", line 270, in get_page_size
request.query_params[self.page_size_query_param],
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'WSGIRequest' object has no attribute 'query_params'
from rest_framework.pagination import PageNumberPagination
class StandardPagination(PageNumberPagination):
page_size_query_param = "page_size"
max_page_size = 100
page_size = 10
I tried a bunch of different things adding a Session Middleware, using the default Client and RequestFactory functions instead of DRF ones but nothing worked