---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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.client.get('/editions/2026-11-25/')"` and inspects `"response.status_code"`, `"response.templates"`, and `"response.context"`. 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`** (`django/test/client.py:RequestFactory`), **`Client`** (`django/test/client.py:Client`), and **`ClientHandler`** (`django/test/client.py: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 a `WSGIRequest` (`django/core/handlers/wsgi.py:WSGIRequest`) — nothing more. It does **not** run URL routing, does **not** run middleware (so `"request.session"`, `"request.user"`, and `"request._messages"` do 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.
- **`Client` (and `AsyncClient`, `django/test/client.py:AsyncClient`):** Subclasses `RequestFactory` to build requests, maintains a persistent cookie jar (`SimpleCookie`) and authenticated session across calls (supporting `ClientMixin.force_login` to skip PBKDF2 hashing in tests!), and dispatches every request straight into **`ClientHandler.__call__`** (`django/test/client.py:ClientHandler.__call__`) — a subclass of `BaseHandler` (Chapter 3) that executes your exact `"MIDDLEWARE"`, URLconf, view, and response hooks in-process! (`AsyncClient` runs the same flow through `AsyncClientHandler` (`django/test/client.py:AsyncClientHandler`) over ASGI scopes with `load_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:

1. **CSRF enforcement is disabled by default!** Look at line 183 of `django/test/client.py`: `ClientHandler.__call__` sets **`"request._dont_enforce_csrf_checks = not self.enforce_csrf_checks"`**, and `Client.__init__` defaults to `"enforce_csrf_checks=False"`! That means `"Client().post('/submit/', data)"` succeeds with HTTP `200` even if your template forgot `"{% csrf_token %}"` or your frontend omitted `"X-CSRFToken"`! Always write dedicated security tests using **`Client(enforce_csrf_checks=True)`** to verify CSRF rejection (`403`)!
2. **Unhandled exceptions propagate out of `Client.get()` instead of becoming HTTP `500`:** By default (`raise_request_exception=True`), `Client` connects a listener to `got_request_exception` (`store_exc_info`) and re-raises any unhandled view exception straight into your test traceback (pass `raise_request_exception=False` only when explicitly testing your custom `500.html` handler).
3. **`close_old_connections` is temporarily disconnected:** Look at lines 175–177 and 206–208 of `django/test/client.py`: `ClientHandler` disconnects `close_old_connections` around `request_started` and `request_finished` so issuing a test request does not close `TestCase`'s open outer transaction and wipe out your `setUpTestData` rows mid-test!
4. **Template and context capture via `template_rendered`:** `Client.request` listens to `django.test.signals.template_rendered` (emitted by `instrumented_test_render` enabled by `setup_test_environment()`), attaching every rendered `Template` (`django/template/base.py:Template`) and its `Context` list onto `"response.templates"` and `"response.context"`.

```text figure=client-vs-wsgi
Test ClientHandler vs production WSGIHandler differences & harness overhead on desk/ (Django 6.1.3)

1. Four subtle differences between production WSGI and Django test Client:
   Transport:  TCP socket + WSGI server         | Direct Python call (0 TCP sockets)
   CSRF check: Always enforced -> HTTP 403      | Disabled by default -> POST = 200!
   Exceptions: Caught by handler -> HTTP 500    | Re-raised directly in test by default
   DB / Tmpl:  close_old_connections() runs     | Keeps TestCase tx open; hooks templates

2. desk/ edition page harness overhead (7 trials, median us):
   RequestFactory (direct view, no MW)       2429.1 us  (1.00x)
   Client() (full MW + routing + signals)    2446.5 us  (1.01x — +17 us for full stack!)
   Client(enforce_csrf_checks=True)          2482.8 us  (1.02x)
```

*Every status code, template list, and microsecond bar is parsed directly from `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.session"`, `Client()` capturing `['newsroom/edition.html', 'newsroom/base.html']` while silently letting an un-tokenized `"POST /submit/"` return `200`, and `Client(enforce_csrf_checks=True)` rejecting the exact same `"POST"` with `403`:

```text recording=ch13-tooling
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
```

```text recording=ch13-bench
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](../leaks.md).
