【问题标题】:Change Django Authentication Backend for Testing更改 Django 身份验证后端以进行测试
【发布时间】:2013-07-05 21:40:24
【问题描述】:

我的 Django 站点在生产中使用 LDAP 后端进行身份验证,但这不适合测试(不可能从虚拟用户创建请求)。如何禁用此后端,仅用于测试?

这里是相关的 settings.py 部分:

    AUTHENTICATION_BACKENDS = (
#'crowd.backend.CrowdBackend',
# 'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend',
    )
   AUTH_LDAP_SERVER_URI = "ldap://ldap.cablelabs.com"
   import ldap
   from django_auth_ldap.config import LDAPSearch

   AUTH_LDAP_BIND_DN = "CN=CableLabs  Internal,OU=cabletest,OU=Teamwork,OU=community,DC=cablelabs,DC=com"
   AUTH_LDAP_BIND_PASSWORD = "UAq,0@ki"
   AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=community,dc=cablelabs,dc=com",ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)")
   AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn","username":"sAMAccountName","email":"mail","photo":"thumbnailPhoto"} 
   AUTH_LDAP_CONNECTION_OPTIONS = {
     ldap.OPT_REFERRALS: 0
   }

【问题讨论】:

    标签: django unit-testing ldap


    【解决方案1】:

    如果您只需要/想要为某些测试禁用后端,您也可以使用 override_settings 装饰器。你可以在测试用例类上使用这个装饰器:

    from django.test.utils import override_settings
    
    @override_settings(AUTHENTICATION_BACKENDS=
                       ('django.contrib.auth.backends.ModelBackend',))
    class FooTest(TestCase):
    
        def test_bar(self):
            pass
    

    但您也可以有选择地在测试方法上使用它:

    from django.test.utils import override_settings
    
    class FooTest(TestCase):
    
        @override_settings(AUTHENTICATION_BACKENDS=
                           ('django.contrib.auth.backends.ModelBackend',))
        def test_bar(self):
            pass
    

    【讨论】:

      【解决方案2】:

      创建一个替代设置文件,例如myproj/test_settings.py,并在运行单元测试时指定该设置文件。

      像这样编写替代设置文件:

      from myproj.settings import *
      
      AUTHENTICATION_BACKENDS = (
              #'your.ldap.backend',
              'django.contrib.auth.backends.ModelBackend',
              )
      

      也就是说,这些设置继承了常规设置的所有内容,但会覆盖 AUTHENTICATION_BACKENDS 定义,并注释掉您的 LDAP 后端。

      然后,像这样运行您的测试:

      python manage.py test --settings=myproj.test_settings
      

      【讨论】:

        【解决方案3】:

        为了将来参考,测试的另一个选项是将User 对象的is_authenticated 属性更改为 lambda。例如:

        user = User(...)
        user.is_authenticated = lambda: True
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-29
          • 2021-11-28
          • 2019-06-06
          • 1970-01-01
          • 2019-08-31
          • 2018-03-28
          相关资源
          最近更新 更多