login() in Django testing framework

前端 未结 3 500
感动是毒
感动是毒 2021-02-01 02:15

I have started using Django\'s testing framework, and everything was working fine until I started testing authenticated pages.

For the sake of simplicity, let\'s say tha

3条回答
  •  独厮守ぢ
    2021-02-01 02:43

    It can often be useful to use a custom auth backend that bypassess any sort of authentication during testing:

    from django.contrib.auth import get_user_model
    
    class TestcaseUserBackend(object):
        def authenticate(self, testcase_user=None):
            return testcase_user
    
        def get_user(self, user_id):
            User = get_user_model()
            return User.objects.get(pk=user_id)
    

    Then, during tests, add yourapp.auth_backends.TestcaseUserBackend to your AUTHENTICATION_BACKENDS:

    AUTHENTICATION_BACKENDS = [
        "akindi.testing.auth_backends.TestcaseUserBackend",
    ]
    

    Then, during tests, you can simply call:

    from django.contrib.auth import login
    user = User.objects.get(…)
    login(testcase_user=user)
    

提交回复
热议问题