Skip to content

Commit

Permalink
Allow importing the backend without loading apps
Browse files Browse the repository at this point in the history
Make it possible to monkey-patch the backend from the settings.
  • Loading branch information
francoisfreitag committed Oct 17, 2024
1 parent 1966c9e commit 943c800
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
5 changes: 4 additions & 1 deletion django_auth_ldap/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@
import django.dispatch
import ldap
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist

Expand Down Expand Up @@ -777,6 +776,8 @@ def _mirror_groups(self):
Mirrors the user's LDAP groups in the Django database and updates the
user's membership.
"""
from django.contrib.auth.models import Group

try:
target_group_names = frozenset(self._get_groups().get_group_names())
except ldap.LDAPError as e:
Expand Down Expand Up @@ -833,6 +834,8 @@ def _load_group_permissions(self):
Populates self._group_permissions based on LDAP group membership and
Django group permissions.
"""
from django.contrib.auth.models import Permission

group_names = self._get_groups().get_group_names()

perms = Permission.objects.filter(group__name__in=group_names)
Expand Down
16 changes: 16 additions & 0 deletions tests/import_test_without_django.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import os
from unittest import TestCase


class TestLoading(TestCase):
def test_django_not_ready(self):
orig_env = os.environ.copy()

def reset_env():
os.environ = orig_env

self.addCleanup(reset_env)

os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings"

import django_auth_ldap.backend # noqa: F401
4 changes: 3 additions & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ python =
3.13 = django{42,50,51,main}

[testenv]
commands = {envpython} -Wa -b -m django test --settings tests.settings
commands =
{envpython} -Wa -b -m django test --settings tests.settings
{envpython} -Wa -b -m unittest discover --pattern *_test_without_django.py
deps =
django42: Django>=4.2,<4.3
django50: Django>=5.0,<5.1
Expand Down

0 comments on commit 943c800

Please sign in to comment.