Тестирование Django с использованием AsyncClient и аутентификации
У меня есть базовый 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)
И два простых теста:
@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
<
Основываясь на docs, AsyncClient
имеет все те же методы, поэтому я не понимаю, почему тест не работает. Возможно, необходимо использовать другой метод аутентификации?
Тест AsyncRequestFactory
, который используется во втором тесте, взят из пакета pytest-django.
Любая помощь будет очень признательна. Спасибо.