I have a basic Asynchronous Class Based View:
class AsyncAuthenticationView(View):
async def post(self, request, *args, **kwargs):
authenticated: bool = await sync_to_async(lambda: request.user.is_authenticated)()
if not authenticated:
return HttpResponse('Unauthorized', status=401)
return HttpResponse('Success', status=200)
And two simple tests:
@pytest.fixture
def authenticated_async_client(user) -> AsyncClient:
client = AsyncClient()
client.force_login(user)
return client
class TestAsyncAuthenticationView:
@pytest.mark.asyncio
async def test_with_async_client(self, authenticated_async_client: AsyncClient):
"""This test fails, with response code 401 instead of 200"""
response = await authenticated_async_client.post(
reverse('auth-test'),
'abc',
content_type="text/html",
)
assert 200 == response.status_code # fails with 401
@pytest.mark.asyncio
async def test_with_async_request_factory(self, async_rf: AsyncRequestFactory, user):
"""This test succeeds correctly with response code 200"""
r = async_rf.post('/fake-url', 'abc', content_type='text/html')
r.user = user
r.session = {}
response = await AsyncAuthenticationView().post(r)
assert 200 == response.status_code
The first test which uses the AsyncClient
always fails to authenticate returning status code 401
while the second test is passing just fine with status code 200
.
Based on the docs the AsyncClient
has all the same methods, so I am not not why the test is failing. Perhaps there is a different authentication method that needs to be used?
The AsyncRequestFactory
that is being used in the second test is from the pytest-django package.
Any help would be much appreciated. Thank you.