From dca107911c6afdd6c5021e8f9b769fb9d7b654cf Mon Sep 17 00:00:00 2001 From: luyanfcp Date: Mon, 18 Nov 2024 10:52:27 -0500 Subject: [PATCH] Add auser mock support for TestClient (#1252) --- ninja/testing/client.py | 6 +++++- tests/test_auth_async.py | 31 ++++++++++++++++++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/ninja/testing/client.py b/ninja/testing/client.py index ecde0c23d..82a08e22c 100644 --- a/ninja/testing/client.py +++ b/ninja/testing/client.py @@ -1,7 +1,7 @@ from json import dumps as json_dumps from json import loads as json_loads from typing import Any, Callable, Dict, List, Optional, Tuple, Union -from unittest.mock import Mock +from unittest.mock import Mock, AsyncMock from urllib.parse import urljoin from django.http import QueryDict, StreamingHttpResponse @@ -139,8 +139,12 @@ def _build_request( request.auth = None request.user = Mock() + auser_mock = AsyncMock() + request.auser = AsyncMock(return_value=auser_mock) + if "user" not in request_params: request.user.is_authenticated = False + auser_mock.is_authenticated = False request.META = request_params.pop("META", {"REMOTE_ADDR": "127.0.0.1"}) request.FILES = request_params.pop("FILES", {}) diff --git a/tests/test_auth_async.py b/tests/test_auth_async.py index c560fbe98..31fcc6c22 100644 --- a/tests/test_auth_async.py +++ b/tests/test_auth_async.py @@ -3,7 +3,7 @@ import pytest from ninja import NinjaAPI -from ninja.security import APIKeyQuery, HttpBearer +from ninja.security import APIKeyQuery, HttpBearer, SessionAuth from ninja.testing import TestAsyncClient, TestClient @@ -176,3 +176,32 @@ async def async_view(request): res = await client.get("/async", headers={"Authorization": "Bearer secret"}) assert res.json() == {"auth": "secret"} + +@pytest.mark.asyncio +async def test_async_user_auth(): + + class AsyncSessionAuth(SessionAuth): + async def __call__(self, request): + return await self.authenticate(request, None) + + async def authenticate(self, request, key): + user = await request.auser() + return user if user.is_authenticated else None + + api = NinjaAPI(auth=AsyncSessionAuth()) + + @api.get("/foobar") + async def foobar(request) -> str: + return {"info": "foobar"} + + client = TestAsyncClient(api) + + res = await client.get("/foobar") + + assert res.json() == {"detail": "Unauthorized"} + + res = await client.get("/foobar", user='abc') + + assert res.json() == {"info": "foobar"} + +