我们有一个带有 LDAP 身份验证的 django 应用程序(django-auth-ldap)。在自定义权限中,我们检查 request.ldap_user.group_names 是否包含某个组(取决于 request.data)。手动测试表明它正在工作。现在我们想编写一个自动化测试,但我们不断收到“AttributeError:'User' object has no attribute 'ldap_user',我们无法找到如何设置 ldap_user 和 ldap_user 组名的任何地方。
这是到目前为止的测试:
import pytest
from django.urls import reverse
from django.test import Client
from django.contrib.auth.models import User
import requests
client = Client()
url_create_artifact = reverse("artifacts/create-list")
@pytest.mark.django_db()
def test_post_artifacts_create_logged_in():
component = Component()
component.id = "test_component"
component.ldap_group = "test_group"
component.save()
user = User.objects.create(username="test_user")
user.set_password("1234")
user.save()
client.login(username="test_user", password="1234")
response = client.post(
url_create_artifact,
{
"component_id": "test_component"
},
)
assert response.status_code == 200
这是自定义权限:
from rest_framework.permissions import BasePermission, SAFE_METHODS
from django.shortcuts import get_object_or_404
class CustomPermission(BasePermission):
def has_permission(self, request, view):
component_id = request.data["component_id"]
component = get_object_or_404(klass=Component, id=component_id)
user = request.user
if user.is_authenticated:
user_ldap_groups = request.user.ldap_user.group_names
component_ldap_group = component.ldap_group
return component_ldap_group in user_ldap_groups
else:
return False
我们的观点始于
from rest_framework.authentication import SessionAuthentication
from our_app.permissions import ApplicationPermission
from rest_framework import viewsets
class ArtifactSetCreate(viewsets.GenericViewSet):
authentication_classes = [SessionAuthentication]
permission_classes = [CustomPermission]
[...]
urls.py 包含
from rest_framework import routers
from our_app.views import ArtifactViewSetCreate
router = routers.DefaultRouter()
router.register(r"artifact/create", ArtifactViewSetCreate, basename="artifacts/create")