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

Add auser mock support for TestClient (#1252) #1339

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"}


Loading