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

Improve type hints for test client response.context #1100

Merged
merged 2 commits into from
Aug 26, 2022

Conversation

adamchainz
Copy link
Contributor

I have made things!

Adding django-stubs to a project with a number of tests that make assertions against the test client's response.context like:

class FolderListViewTest(TestCase):
    def test_search_filter(self, url, category):
        ...
        response = self.client.get("/example"/)
        ...
        assert response.context["page_obj"] == []

This was resulting in errors like:

example/tests/test_views.py:110: error: No overload variant of "__getitem__" of "list" matches argument type "str"  [call-overload]
example/tests/test_views.py:110: note: Possible overload variants:
example/tests/test_views.py:110: note:     def __getitem__(self, SupportsIndex) -> Dict[str, Any]
example/tests/test_views.py:110: note:     def __getitem__(self, slice) -> List[Dict[str, Any]]

context is gathered in store_rendered_templates and attached in Client.request() / AsyncClient.request(), with possible flattening. It’s always a ContextList.

This PR improves the type hints for ContextList to handle all the types it accepts, and updates _MonkeyPatchedWSGIResponse / _MonkeyPatchedASGIResponse. I used these hints with that project and many issues are fixed.

Related issues

n/a

@adamchainz adamchainz force-pushed the client_response_context branch 2 times, most recently from f50ef17 to d557451 Compare August 12, 2022 17:23
@adamchainz adamchainz force-pushed the client_response_context branch from d557451 to 2001235 Compare August 26, 2022 09:18
@adamchainz adamchainz force-pushed the client_response_context branch from 2001235 to 4fd93f2 Compare August 26, 2022 09:54
@sobolevn sobolevn merged commit 8b5509b into typeddjango:master Aug 26, 2022
@adamchainz adamchainz deleted the client_response_context branch August 26, 2022 10:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants