[Django]-Is there a way to disable throttling while using Pytest in Django?

1πŸ‘

βœ…

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

πŸ‘€PercySherlock

1πŸ‘

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.

πŸ‘€anonDuck

1πŸ‘

@ra123 has the right idea in general. As another approach, with all Django projects I add something like this to my settings/__init__.py (or just settings.py if you do a one file thing). It looks at argv to see if its in test mode

IS_TESTING = bool(set(sys.argv[:2]) & {"pytest", "test", "jenkins"})

REST_FRAMEWORK = { "YOUR_CONFIG": "..." }

# at the very very end, AFTER your settings are loaded:
if IS_TESTING:
    # override your rest framework settings in test mode
    REST_FRAMEWORK["DEFAULT_THROTTLE_CLASSES"] = []

    # some other handy things, for making tests faster/easier
    PASSWORD_HASHERS = ("django.contrib.auth.hashers.MD5PasswordHasher",)
    EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
    DEFAULT_FILE_STORAGE = "inmemorystorage.InMemoryStorage"

I ended up with it this way so we don’t have to worry about it ever getting the wrong settings. It also helps keep things centralized, so (for example) you don’t call sentry.init in testing mode, even if there is a sentry_url in the environment.

πŸ‘€Andrew

Leave a comment