Change page limit in test case

975 Views Asked by At

Question in short: how do I override the PAGE_SIZE setting of REST_FRAMEWORK in a test case in Django?

Details about question: I have the following settings in my project's base.py:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'Masterdata.authentication.FashionExchangeAuthentication',
    ),
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework.filters.DjangoFilterBackend',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 100
}

Now I want to create a test case, in which I change the page size to 10. However, I cannot override this particular setting while keeping the rest of the dictionary intact. Does anyone know how to do so?

This is what I tried:

1) Adding the modify_settings decorator above the test method:

@modify_settings(REST_FRAMEWORK={
    'remove': 'PAGE_SIZE',
    'append': {'PAGE_SIZE': 10}
})

This does not change the setting.

2) Using override_settings as context manager:

test_settings = settings.REST_FRAMEWORK
test_settings['PAGE_SIZE'] = 10
with override_settings(REST_FRAMEWORK = test_settings):
    # do stuff

However, the line with test_settings['PAGE_SIZE']=10 fails because apparently the variable settings.REST_FRAMEWORK is a list instead of a dictionary.

print(settings.REST_FRAMEWORK)

['DEFAULT_PERMISSION_CLASSES', 'DEFAULT_AUTHENTICATION_CLASSES', 'DEFAULT_FILTER_BACKENDS', 'DEFAULT_PAGINATION_CLASS', 'DEFAULT_RENDERER_CLASSES']

How come this setting is a list here? I have verified that the variable is not overwritten anywhere else in the project.

1

There are 1 best solutions below

2
On

Beneath your rest_framework settings, you can check for if this is test environment. This should work:

if 'test' in sys.argv:
    REST_FRAMEWORK['PAGE_SIZE'] = 10

Otherwise you can create separate settings file for test cases:

# settings_tests.py
from settings import *

# Override your changes.
REST_FRAMEWORK['PAGE_SIZE'] = 10