How to Test X-Content-Type-Options nosniff in Python with Mocks
Mock httpx responses and verify that a server's X-Content-Type-Options header includes nosniff to prevent MIME sniffing.
pip install httpx
Python code
24 linesimport httpx
from unittest.mock import Mock, patch
def fetch_headers(url: str) -> dict:
response = httpx.get(url)
return dict(response.headers)
def mock_nosniff_check(response) -> bool:
content_type = response.headers.get("content-type", "")
x_content_type_options = response.headers.get("x-content-type-options", "")
return "nosniff" in x_content_type_options and content_type.startswith("text/")
if __name__ == "__main__":
mock_response = Mock()
mock_response.headers = {
"content-type": "text/html; charset=utf-8",
"x-content-type-options": "nosniff"
}
with patch("httpx.get", return_value=mock_response):
headers = fetch_headers("https://example.com")
is_safe = mock_nosniff_check(mock_response)
print(f"Headers: {headers}")
print(f"Nosniff check passed: {is_safe}")
Output
Headers: {'content-type': 'text/html; charset=utf-8', 'x-content-type-options': 'nosniff'}
Nosniff check passed: True
How it works
The Mock object replaces a real HTTP response, letting you simulate headers without a network call. patch swaps httpx.get with a lambda that returns the mock, so fetch_headers works as if it received a live response. The mock_nosniff_check function reads both required headers and returns True only when nosniff is present and the content type starts with text/. This pattern lets you test security-aware parsing logic rapidly and deterministically.
Common mistakes
- Checking headers on the mock response instead of the one returned by `fetch_headers`.
- Forgetting that header keys are case-insensitive; httpx normalizes them to lowercase.
- Not resetting mocks between tests, causing false positives or cross-test pollution.
Variations
- Use `respx` to mock HTTPX requests at the transport level for more realistic responses.
- Parse the actual response body via `httpx.Response(200, headers={...})` instead of `Mock`.
Real-world use cases
- Verifying that a legacy service sets the nosniff header before allowing file uploads.
- Testing a security middleware that adds security headers to API responses.
- Writing regression tests for a website to ensure nosniff is never removed during refactors.
Sponsored
More from Auth & security at scale
- ACME LetsEncrypt Mock Challenge Server in Python medium
- AES GCM encryption and decryption in Python medium
- Build a Mock OIDC Userinfo Endpoint in Python with Flask easy
- ChaCha20-Poly1305 mock in Python medium
- ECDH key agreement in Python with cryptography medium
- Enforce TLS 1.2 Minimum in Python easy
Keep learning
Related tutorials and quizzes for this topic.