Last active
December 22, 2025 19:14
-
-
Save codingjoe/59197f8922adf544c76776d26ae368d4 to your computer and use it in GitHub Desktop.
TestNoIO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import itertools | |
| from django.conf import settings | |
| from django.http import HttpResponse | |
| from django.template import engines | |
| from django.utils.module_loading import import_string | |
| import pytest | |
| @pytest.mark.django_db | |
| @pytest.mark.parametrize( | |
| "fn", | |
| itertools.chain( | |
| *(backend.engine.template_context_processors for backend in engines.all()) | |
| ), | |
| ) | |
| def test_no_io(fn, rf, admin_user, django_db_blocker): | |
| """ | |
| Requests to redirect views MUST NOT perform any I/O operations. | |
| Ensure no middleware or other part of the request handling stack | |
| performs any I/O operations, thereby slowing down the request processing. | |
| A common culprit is a middleware or context_processor eagerly accessing request.user. | |
| """ | |
| request = rf.get("/") | |
| response = HttpResponse(b"", status=200) | |
| with django_db_blocker.block(): | |
| for middleware_path in settings.MIDDLEWARE: | |
| middleware = import_string(middleware_path) | |
| try: | |
| response = middleware(get_response=lambda req: response)(request) # noqa: B023 | |
| except RuntimeError: | |
| pytest.fail( | |
| f"Middleware {middleware_path} performed I/O during request processing" | |
| ) | |
| try: | |
| fn(request) | |
| except RuntimeError: | |
| pytest.fail( | |
| f"Context processor {fn.__module__}.{fn.__name__} performed I/O" | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment