13.6 Commands, checks, and testing
How Client bypasses the socket
How does Django’s test Client execute the full middleware, routing, view, and template stack without starting a server — and what subtle differences remain?
Every test in "desk/" calls "self and inspects "response, "response, and "response. No port is bound, no HTTP bytes traverse loopback, and no Gunicorn worker boots — yet the entire request still runs through your real "MIDDLEWARE", URL resolver, views, ORM queries, and template engine. Understanding RequestFactory, Client, and ClientHandler tells you exactly what your tests do prove — and what they silently skip!
RequestFactory vs. Client and ClientHandler
Compare the two classes side by side:
RequestFactory: Builds a synthetic WSGI"environ"dictionary and wraps it in aWSGIRequest— nothing more. It does not run URL routing, does not run middleware (so"request,.session" "request.user", and"requestdo not exist unless you attach them manually!), and does not maintain cookies across calls. Use it for pure unit tests of a single view function or middleware class.._messages" Client(andAsyncClient,AsyncClient): SubclassesRequestFactoryto build requests, maintains a persistent cookie jar (SimpleCookie) and authenticated session across calls (supportingClientMixinto skip PBKDF2 hashing in tests!), and dispatches every request straight into.force_login ClientHandler— a subclass of.__call__ BaseHandler(Chapter 3) that executes your exact"MIDDLEWARE", URLconf, view, and response hooks in-process! (AsyncClientruns the same flow throughAsyncClientHandlerover ASGI scopes withload_middleware(is_async=True).)
Four subtle ways ClientHandler differs from production WSGIHandler
Because ClientHandler lives inside a test harness rather than a live WSGI server, it intentionally diverges from production WSGIHandler in four critical places — every one of which can hide a real bug if you forget it exists:
- CSRF enforcement is disabled by default! Look at line 183 of
django/:test/ client .py ClientHandlersets.__call__ "request, and._dont_enforce_csrf_checks = not self .enforce_csrf_checks" Client.__init__defaults to"enforce_csrf_checks=False"! That means"Client().post('/succeeds with HTTPsubmit/ ', data)" 200even if your template forgot"{% csrf_token %}"or your frontend omitted"X-CSRFToken"! Always write dedicated security tests usingClient(enforce_csrf_checks=True)to verify CSRF rejection (403)! - Unhandled exceptions propagate out of
Client.get()instead of becoming HTTP500: By default (raise_request_exception=True),Clientconnects a listener togot_request_exception(store_exc_info) and re-raises any unhandled view exception straight into your test traceback (passraise_request_exception=Falseonly when explicitly testing your custom500.htmlhandler). close_old_connectionsis temporarily disconnected: Look at lines 175–177 and 206–208 ofdjango/:test/ client .py ClientHandlerdisconnectsclose_old_connectionsaroundrequest_startedandrequest_finishedso issuing a test request does not closeTestCase’s open outer transaction and wipe out yoursetUpTestDatarows mid-test!- Template and context capture via
template_rendered:Client.requestlistens todjango(emitted by.test .signals .template_rendered instrumented_test_renderenabled bysetup_test_environment()), attaching every renderedTemplateand itsContextlist onto"responseand.templates" "response..context"
ch13-tooling and ch13-bench. Notice the timing payoff: running the entire middleware stack, URL resolver, and template instrumentation via Client() adds only 17.4 us (1%) over raw RequestFactory (2,429.1 us -> 2,446.5 us ), and enabling enforce_csrf_checks=True adds another 1% — there is no performance reason to bypass middleware or skip CSRF tests!Watch RequestFactory lacking "request, Client() capturing ['newsroom/ while silently letting an un-tokenized "POST /submit/" return 200, and Client(enforce_csrf_checks=True) rejecting the exact same "POST" with 403:
6. ClientHandler CSRF bypass, RequestFactory, and template capture
request_factory: has_session_middleware=False status=200
client_get: status=200 dont_enforce_csrf=True templates=['newsroom/edition.html', 'newsroom/base.html'] has_edition_ctx=True
csrf_difference: default_client_post=200 enforce_csrf_post=403 has_async_client=True
2. RequestFactory vs Client on desk edition page (7 trials, us/request)
harness_mode median_us rel
RequestFactory (direct view, no MW) 2429.1 1.00x
Client() (full MW + routing + signals) 2446.5 1.01x
Client(enforce_csrf_checks=True) 2482.8 1.02x
We have now opened every subsystem of Django 6.1.3 from boot and WSGI/ASGI entry through routing, security, models, QuerySets, SQL compilation, transactions, migrations, templates, forms, sessions, auth, the Admin, horizontal services, and developer tooling. In the final chapter we put the entire stack back together — measuring every microsecond of one endpoint end to end, dissecting the worst cross-layer production leaks, and distilling a sharp checklist for reviewing both human and AI-written Django code in Where Django leaks.