File: test_permissions_custom.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,483 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.test import RequestFactory
from rest_framework.decorators import api_view, permission_classes
from rest_framework.request import Request
from rest_framework.response import Response
from test_project.heroes.models import Hero, HeroAPIKey
from test_project.heroes.permissions import HasHeroAPIKey

from rest_framework_api_key.models import APIKey

pytestmark = pytest.mark.django_db


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


def test_non_hero_api_key_denied(rf: RequestFactory) -> None:
    _, key = APIKey.objects.create_key(name="test")
    authorization = f"Api-Key {key}"
    request = rf.get("/test/", HTTP_AUTHORIZATION=authorization)

    response = view(request)
    assert response.status_code == 403


def test_hero_api_key_granted(rf: RequestFactory) -> None:
    hero = Hero.objects.create()
    _, key = HeroAPIKey.objects.create_key(name="test", hero=hero)
    authorization = f"Api-Key {key}"
    request = rf.get("/test/", HTTP_AUTHORIZATION=authorization)

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


def test_retired_hero_denied(rf: RequestFactory) -> None:
    hero = Hero.objects.create(retired=True)
    _, key = HeroAPIKey.objects.create_key(name="test", hero=hero)
    authorization = f"Api-Key {key}"
    request = rf.get("/test/", HTTP_AUTHORIZATION=authorization)

    response = view(request)
    assert response.status_code == 403