Fix issue when consulting request attributes while using mocked request #1244
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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:
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.