Home > Net >  Is there a way to disable throttling while using Pytest in Django?
Is there a way to disable throttling while using Pytest in Django?

Time:05-25

Problem:

I want to figure out a way to disable throttling when running my tests with pytest -vv

Details:

I have this default throttling policy in my settings.py file:

  'DEFAULT_THROTTLE_RATES': {
        'anon': '100/day',
        'user': '1000/day'
    }

I also have this fixture in my confest.py which returns an error whenever I exceed the limit of requests:

def get_token(user, client):
    response = client.post(
        "/email-login",
        {"email":user.email, "password": "B9vX95phJDi3C4"},
    )
    return {
        "HTTP_AUTHORIZATION": f"Bearer {response.json()['token']['access']}"
    }

What I have tried:

I have attempted to use the solution in this GitHub Issue: https://github.com/encode/django-rest-framework/issues/1336, but it doesn't work in my case.

CodePudding user response:

First you need to create a way to differentiate between test env and otherwise. Like we do for PROD and DEV using settings.DEBUG config.

My recommendation is to create an env variable test=Trueand then in your settings.py write -

if os.environ.get("test", False):
   REST_FRAMEWORK = {
     'DEFAULT_THROTTLE_CLASSES': [
    'rest_framework.throttling.AnonRateThrottle',
    'rest_framework.throttling.UserRateThrottle'
  ],
  'DEFAULT_THROTTLE_RATES': {
    'anon': '100/day',
    'user': '1000/day'
   }
}

else it does nothing, and drf will not throttle.

CodePudding user response:

I was able to resolve this problem with the following steps:

  • I created a new settings file which inherited from the base settings file. i.e from settings import *
  • Then I deleted the DEFAULT_THROTTLE_RATES key i.e del REST_FRAMEWORK["DEFAULT_THROTTLE_RATES"]
  • Next thing I did was to point to the new settings file in pytest.ini i.e DJANGO_SETTINGS_MODULE="new_settings.py"

Now the tests will use the new settings file

  • Related