我的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
}
答案 0 :(得分:15)
如果您只需要/想要禁用某些测试的后端,您也可以使用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
答案 1 :(得分:12)
创建备用设置文件,例如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
答案 2 :(得分:0)
为了将来参考,另一个要考虑测试的选项是将is_authenticated
对象的User
属性更改为lambda。例如:
user = User(...)
user.is_authenticated = lambda: True