vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
7.22k stars 429 forks source link

TestClient request mock HttpRequest is missing SessionStore session attribute #1321

Open picturedots opened 2 weeks ago

picturedots commented 2 weeks ago

AttributeError: Mock object has no attribute 'session' This error is raised when using TestClient to test a login endpoint that uses django.contrib.auth.login because the mock request object as defined here https://github.com/vitalik/django-ninja/blob/master/ninja/testing/client.py#L128-L138 is missing a session attribute.

Possible Solution I was able to solve this issue on my own by monkey patching the test client by defining a function like

from django.contrib.sessions.backends.db import SessionStore
def _new_build_request(self, *args, **kwargs) -> Mock:
    """Method to be monkey patched into the TestClient to add session store to the request mock"""
    mock = self._old_build_request(*args, **kwargs)
    mock.session = SessionStore()
    return mock

and then using this new function to replace the _build_request function in my TestClient instance like

client._old_build_request = client._build_request
client._build_request = _new_build_request.__get__(client)

Maybe a better solution would be to use a SessionStore mock?

idkosilov commented 1 week ago

You might consider using Django’s standard django.test.client.Client for your tests.

Additionally, Django now supports an asynchronous client django.test.client.AsyncClient that can be beneficial for testing async views.