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

TestClient request mock HttpRequest is missing SessionStore session attribute #1321

Open
picturedots opened this issue Oct 18, 2024 · 0 comments

Comments

@picturedots
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant