Disable specific Django middleware during tests

How to disable specific middleware (my own middleware that I wrote) only during tests?

+4
source share
3 answers

There are several options:

  • create a separate test_settings settings test_settings for testing, and then run the tests with:

     python manage.py test --settings=test_settings 
  • change 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 this helps.

+2
source

https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.override_settings

 from django.test import TestCase, override_settings from django.conf import settings class MyTestCase(TestCase): @override_settings( MIDDLEWARE_CLASSES=[mc for mc in settings.MIDDLEWARE_CLASSES if mc != 'myapp.middleware.MyMiddleware'] ) def test_my_function(self): pass 
+4
source

It is also related (since this page occupies a rather large place in search engines for queries related queries):

If you want to disable middleware for one case, you can also use @modify_settings :

 @modify_settings(MIDDLEWARE={ 'remove': 'django.middleware.cache.FetchFromCacheMiddleware', }) def test_my_function(self): pass 
+2
source

Source: https://habr.com/ru/post/1495028/


All Articles