Complete worked example
python
from drf_lab import setup
setup()
from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.models import Token, TokenProxy
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.test import APIRequestFactory
from rest_framework.views import APIView
from drf_lab import reset_fixture
class Profile(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
return Response({"user": request.user.username})
def inspect_example(payload):
alice, _, _ = reset_fixture()
token = Token.objects.create(user=alice, key="owned-fixture-token-not-a-real-credential")
if payload.get("revoked"):
TokenProxy.objects.get(key=token.key).delete()
headers = {} if not payload.get("token") else {"HTTP_AUTHORIZATION": "Token " + payload["token"]}
response = Profile.as_view()(APIRequestFactory().get("/profile/", **headers))
body = {"error": response.data["detail"].code} if response.status_code >= 400 else dict(response.data)
return {"status": response.status_code, "body": body}- Reasoning
- The Authorization header uses the Token scheme. A missing or unknown token produces an authentication failure under the declared class order. The test also deletes the token through TokenProxy and verifies that the old credential no longer grants access. Current DRF security patches corrected TokenProxy deletion behavior. The fixture exercises the actual database effect instead of assuming that invoking delete always revokes access. Identity resolution and the token record state remain observable through real DRF dispatch.