Reputation: 529
My Django site uses the LDAP backend for authentication in production, but this is not suitable for testing (impossible to create requests from dummy users). How can I disable this backend, solely for tests?
Here is the relevant settings.py section:
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
}
Upvotes: 10
Views: 4110
Reputation: 1
For future reference, another option to look into for testing is to change the is_authenticated
property of the User
object to a lambda. For example:
user = User(...)
user.is_authenticated = lambda: True
Upvotes: 0
Reputation: 13001
If you only need/want to disable the backend for certain tests, you can also use the override_settings
decorator. You can use this decorator on the test case class:
from django.test.utils import override_settings
@override_settings(AUTHENTICATION_BACKENDS=
('django.contrib.auth.backends.ModelBackend',))
class FooTest(TestCase):
def test_bar(self):
pass
But you can also selectively use it on a test method:
from django.test.utils import override_settings
class FooTest(TestCase):
@override_settings(AUTHENTICATION_BACKENDS=
('django.contrib.auth.backends.ModelBackend',))
def test_bar(self):
pass
Upvotes: 19
Reputation: 124704
Create an alternative settings file, for example myproj/test_settings.py
, and specify that settings file when running unit tests.
Write the alternative settings file like this:
from myproj.settings import *
AUTHENTICATION_BACKENDS = (
#'your.ldap.backend',
'django.contrib.auth.backends.ModelBackend',
)
That is, the settings inherits everything from your regular settings, but overrides the AUTHENTICATION_BACKENDS
definition, with your LDAP backend commented out.
Then, run your tests like this:
python manage.py test --settings=myproj.test_settings
Upvotes: 14