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.

Medium Python 3.9+ Aug 9, 2026 Auth & security at scale 13 views 0 copies

Requires third-party packages — install first
pip install httpx

Python code

24 lines
Python 3.9+
import 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

stdout
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

  1. Use `respx` to mock HTTPX requests at the transport level for more realistic responses.
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Auth & security at scale

Related tutorials and quizzes for this topic.