Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Xdynix opened this issue Aug 4, 2024 · 0 comments
Open

Comments

@Xdynix
Copy link

Xdynix commented Aug 4, 2024

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):

  • Python version: 3.12
  • Django version: 5.0.7
  • Django-Ninja version: 1.2.2
  • Pydantic version: 2.8.2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant