Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable a specific Django middleware during tests

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

like image 316
daveoncode Avatar asked Aug 02 '13 20:08

daveoncode


4 Answers

Also related (since this page ranks quite high in search engines for relates queries):

If you'd only like to disable a middleware for a single case, you can also use @modify_settings:

@modify_settings(MIDDLEWARE={
    'remove': 'django.middleware.cache.FetchFromCacheMiddleware',
})
def test_my_function(self):
    pass
like image 143
WhyNotHugo Avatar answered Oct 04 '22 18:10

WhyNotHugo


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
like image 41
lampslave Avatar answered Oct 04 '22 20:10

lampslave


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.

like image 23
alecxe Avatar answered Oct 04 '22 19:10

alecxe


A nice way to handle this with a single point of modification is to create a conftest.py file at the root of Django project and the put the following contents in it:

from django.conf import settings


def pytest_configure():
    """Globally remove the your_middleware_to_remove for all tests"""
    settings.MIDDLEWARE.remove(
        'your_middleware_to_remove')

like image 22
user1847 Avatar answered Oct 04 '22 18:10

user1847