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 · May be fixed by #1339
Open

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

Xdynix opened this issue Aug 4, 2024 · 0 comments · May be fixed by #1339

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
LuYanFCP added a commit to LuYanFCP/django-ninja that referenced this issue Nov 18, 2024
@LuYanFCP LuYanFCP linked a pull request Nov 18, 2024 that will close this issue
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

Successfully merging a pull request may close this issue.

1 participant