Test Suite Architecture
Relevant source files
The following files were used as context for generating this wiki page:
The Uvicorn test suite is designed to validate the server's performance, protocol compliance, and process management capabilities. It utilizes pytest as the primary test runner and leverages asynchronous testing via the anyio plugin to handle the non-blocking nature of the ASGI server implementation.
The architecture is divided into specialized layers targeting different components: protocol implementations (HTTP/1.1 and WebSockets), middleware logic, configuration management, and supervisor behaviors (reloading and multiprocessing). This modular approach ensures that each layer of the server stack is verified in isolation and through integrated end-to-end scenarios.
Sources: pyproject.toml:98-111, tests/protocols/test_http.py:38
Core Test Configuration and Execution
Uvicorn's testing infrastructure is configured primarily through pyproject.toml. The project uses a strict configuration that treats all warnings as errors, except for specific deprecations related to WSGI and third-party libraries.
Execution Environment
Tests are executed using pytest with the pytest-xdist plugin enabled by default to run tests in parallel across 8 workers. Coverage is tracked using the coverage tool, with a high threshold (100% fail-under) for the core package and tests.
| Configuration Option | Value | Purpose |
|---|---|---|
addopts | -rxXs --strict-config -n 8 | Configures report verbosity and parallel execution. |
xfail_strict | true | Ensures tests marked as xfail that pass are reported as errors. |
fail_under | 100 | Mandatory code coverage percentage for successful builds. |
Sources: pyproject.toml:133-146, pyproject.toml:156-159
Protocol Testing Architecture
Protocol tests focus on the low-level handling of byte streams and their conversion into ASGI-compliant scopes and events.
Mock Transport and Loop
To test protocol logic without actual network overhead, the suite employs MockTransport and MockLoop classes. These components simulate the asyncio.Protocol interface, allowing tests to manually feed data into parsers and verify the resulting output buffers.
The diagram above shows the relationship between mock infrastructure and the protocol implementations during a test execution.
Sources: tests/protocols/test_http.py:165-212
HTTP Protocol Validation
HTTP tests cover a wide range of scenarios including GET/POST requests, keep-alive timeouts, pipelined requests, and error handling (e.g., 400 Bad Request for invalid headers). Specific tests ensure that headers are correctly parsed and that oversized or undersized bodies trigger appropriate transport closures.
Sources: tests/protocols/test_http.py:233-400
WebSocket Protocol Validation
WebSocket tests utilize the websockets client library to perform handshakes against the Uvicorn server. They verify:
- Handshake acceptance and rejection.
- Binary and text data frame exchange.
- Support for extensions like
permessage-deflate. - Connection closure codes (e.g., 1000 for normal closure, 1012 for server shutdown).
Sources: tests/protocols/test_websocket.py:101-200, tests/protocols/test_websocket.py:448-470
Supervisor and Process Management Tests
These tests evaluate Uvicorn's ability to manage worker lifecycles and react to file system changes.
Reloading Logic
The suite tests both StatReload and WatchFilesReload. Tests simulate file changes (using path.touch()) and verify that the reloader correctly identifies modified Python files while ignoring excluded directories or patterns.
This flow illustrates the sequence of verifying a reload event triggered by a file modification.
Sources: tests/supervisors/test_reload.py:73-120
Multiprocess Management
Multiprocess tests verify the coordination between the master supervisor and worker processes. Key areas include:
- Signal Handling: Verifying that
SIGINT,SIGTERM, andSIGHUPare propagated correctly to workers. - Worker Health: Ensuring the supervisor restarts a worker if it is killed.
- Scaling: Testing
SIGTTINandSIGTTOUto dynamically increase or decrease worker counts.
Sources: tests/supervisors/test_multiprocess.py:65-150
Middleware and Integration Testing
Uvicorn uses httpx.ASGITransport to test middleware in a way that simulates an ASGI lifecycle without a full network stack.
Proxy Headers and Trust Logic
The ProxyHeadersMiddleware is tested extensively with a variety of IP network shapes and header combinations. The _TrustedHosts internal class is validated against IPv4/IPv6 addresses and CIDR networks to ensure correct identification of trusted proxies.
Sources: tests/middleware/test_proxy_headers.py:60-350
Logging Integration
Tests for the logging system verify that:
- Access logs correctly format request details (e.g.,
"GET / HTTP/1.1" 200). - Trace logs capture internal protocol events like
HTTP connection made. - Colorized output is correctly toggled based on configuration.
Sources: tests/middleware/test_logging.py:70-130
Configuration and CLI Testing
The configuration layer is validated for its ability to load settings from environment variables, .env files, and various logging configuration formats (JSON, YAML, INI).
| Test Component | Target | Key Assertions |
|---|---|---|
test_env_file | .env loading | Environment variables are correctly populated into the Config object. |
test_log_config | JSON/YAML configs | logging.config.dictConfig is called with the expected structure. |
test_cli_headers | CLI --header | Custom headers are parsed and passed to the server runner. |
test_app_factory | --factory flag | The server correctly invokes a callable to retrieve the ASGI app. |
Sources: tests/test_config.py:345-420, tests/test_cli.py:53-75
Summary
The architecture of the Uvicorn test suite provides a comprehensive safety net through its use of protocol-level mocks, process-level signal verification, and middleware integration tests. By enforcing 100% coverage and treating warnings as errors, the suite ensures that the server remains compliant with ASGI specifications across all supported Python versions and platforms.