File: test_permissions_combination.py

package info (click to toggle)
djangorestframework-api-key 3.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 392 kB
  • sloc: python: 926; makefile: 53; sh: 3
file content (46 lines) | stat: -rw-r--r-- 1,448 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import pytest
from django.contrib.auth import get_user_model
from django.test import RequestFactory
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.test import force_authenticate

from rest_framework_api_key.models import APIKey
from rest_framework_api_key.permissions import HasAPIKey

pytestmark = pytest.mark.django_db


@api_view()
@permission_classes([HasAPIKey | IsAuthenticated])
def view(request: Request) -> Response:
    return Response()


def test_if_authenticated_and_no_api_key_then_permission_granted(
    rf: RequestFactory,
) -> None:
    user = get_user_model().objects.create_user(username="foo", password="bar")

    request = rf.get("/test/")
    force_authenticate(request, user)

    response = view(request)
    assert response.status_code == 200, response.data


def test_if_authenticated_and_revoked_api_key_then_permission_granted(
    rf: RequestFactory,
) -> None:
    user = get_user_model().objects.create_user(username="foo", password="bar")

    _, key = APIKey.objects.create_key(name="test", revoked=True)
    authorization = f"Api-Key {key}"

    request = rf.get("/test/", HTTP_AUTHORIZATION=authorization)
    force_authenticate(request, user)

    response = view(request)
    assert response.status_code == 200, response.data