Search code examples
djangodjango-testingdjango-middleware

Disable a specific Django middleware during tests


How can I disable a specific middleware (a custom middleware I wrote) only during tests?


Solution

  • There are several options:

    • create a separate test_settings settings file for testing and then run tests via:

      python manage.py test --settings=test_settings 
      
    • modify your settings.py on the fly if test is in sys.argv

      if 'test' in sys.argv:
           # modify MIDDLEWARE_CLASSES
            MIDDLEWARE_CLASSES = list(MIDDLEWARE_CLASSES)
            MIDDLEWARE_CLASSES.remove(<middleware_to_disable>)
      

    Hope that helps.