Skip to content

Commit

Permalink
Add auser mock support for TestClient (vitalik#1252)
Browse files Browse the repository at this point in the history
  • Loading branch information
LuYanFCP committed Nov 18, 2024
1 parent ee0f27b commit dca1079
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
6 changes: 5 additions & 1 deletion ninja/testing/client.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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", {})
Expand Down
31 changes: 30 additions & 1 deletion tests/test_auth_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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"}


0 comments on commit dca1079

Please sign in to comment.