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

Fix issue when consulting request attributes while using mocked request #1244

Conversation

acuriel
Copy link
Contributor

@acuriel acuriel commented Jul 29, 2024

Problem

Fixes #1240

When using Python builtin functions for managing/consulting object attributes (getattr & hasattr for example), the mocked request always mocks and returns the mocked attribute value.
For example:

hasttr(request, "field_name")  # Will always return True during testing, even if it's expected to be False

getattr(request, "field_with_dict", {}). # Will return a Mock object if field doesn't exist, causing a non-subscriptable exception during testing.

The issue originates during the instantiation of the mocked request in ninja.testing.client._build_request. There are 3 possible ways to instantiate the Mock object.

Proposed solution

Setting django HttpRequest as spec when instantiating the Mock object, will restrict the instance to behave closer to an HttpRequest, returning real values during the execution of the code showed above, and still allowing to add and modify new fields.

Extra Note

When doing this change, mocking the user object itself becomes necessary, for provide more freedom when mocking the authenticated user

Testing

I'm not sure if there is a need of adding extra tests in this case, since the tests would be testing Mock object behavior more than the test client behavior. If it's considered necessary I can add some tests at test_test_client testing the build request function.

@vitalik vitalik merged commit f0f5547 into vitalik:master Aug 10, 2024
27 checks passed
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

Successfully merging this pull request may close these issues.

[BUG] Mocked request object not using HttpRequest as spec
2 participants