vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
7.03k stars 421 forks source link

[BUG] Mock Request Generated by Test Client Doesn’t Support auser() #1252

Open Xdynix opened 1 month ago

Xdynix commented 1 month ago

Describe the bug

In Django 5.0, request.auser() is added to access the authenticated user in async style (doc). This can be helpful for use cases like async authentication callback. But Django Ninja's test client doesn't support it yet.

Example Code:

from django.contrib.auth.models import AnonymousUser, User
from django.http import HttpRequest
from ninja import NinjaAPI
from ninja.security import SessionAuth
from ninja.testing import TestClient

class AsyncSessionAuth(SessionAuth):
    async def __call__(self, request):
        return await self.authenticate(request, None)

    async def authenticate(self, request: HttpRequest, key: str | None) -> User | AnonymousUser | None:
        user = await request.auser()
        return user if user.is_authenticated else None

def test_foobar(api: NinjaAPI):
    @api.get("/foobar", auth=AsyncSessionAuth())
    def foobar(request) -> str:
        return "foobar"

    client = TestClient(api)
    response = client.get("/foobar")
    assert response.status_code == 200
    assert response.json() == "foobar"

Accessing the view in an actual API works as expected. But when running the test the following error is raised: TypeError: object Mock can't be used in 'await' expression during the line user = await request.auser().

Versions (please complete the following information):