djangopython-decoratorsdjango-testing

Build a pre-decorated class with override_settings for faster client.login?


This makes a Django test using the test client run very much faster, where login security is not an important part of the test

from django.test import TestCase, Client, override_settings

@override_settings(
    PASSWORD_HASHERS = [ "django.contrib.auth.hashers.MD5PasswordHasher"  ])
class Test2(TestCase):
    ...

Is there any way to create my own TestCase subclass with the decorator built in, so I can code like this? (I keep having to look up that setting to override when I find my new test running slow! )

from myproject.utils import FastLoginTestCase

class Test2( FastLoginTestCase):
    ...

Solution

  • You can apply the decorator to a subclass in an __init_subclass__ method:

    class FastLoginTestCase(TestCase):
        def __init_subclass__(cls, **kwargs):
            super().__init_subclass__(**kwargs)
            override_settings(
                PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]
            )(cls)