---
title: "How to Test Code That Uses a Proxy: Pytest and a Fake Proxy"
description: "Test proxy code by mocking the client and running a local fake proxy that records each request. Pytest examples for 407, 502, timeouts and offline CI."
url: https://proxynet.io/blog/proxy-unit-test-mock-server
date: 2026-12-02
author: "Acar Diveroli"
category: "Tutorial"
lang: en
---

# How to Test Code That Uses a Proxy: Pytest and a Fake Proxy

Unit testing proxy code means checking that each request goes to the right proxy with the right credentials, without touching the real network. Two layers do the job: mocking the client library and running a local fake proxy that records each request. A mock is fast, but it never connects to the proxy. That is why only the fake proxy shows error paths such as 407 or a timeout. This post covers both layers, the pytest fixture, testing the error paths and credentials leaking into test output.

> **Note: Short answer**
>
> Check that the proxy parameter is passed by mocking with responses or respx. Test proxy behavior with a local fake proxy that records the `CONNECT` line and the `Proxy-Authorization` header. Start and stop the fake proxy in every test with a pytest fixture.

## Two test layers

A mock intercepts the client's network call inside your code. A fake proxy accepts a real TCP connection on `127.0.0.1`. The two answer different questions.

| Question | Mock (responses, respx) | Local fake proxy |
|---|---|---|
| Was the proxy parameter passed? | ✓ (responses) | ✓ |
| Is `Proxy-Authorization` correct? | ✗ | ✓ |
| Does HTTPS open a `CONNECT`? | ✗ | ✓ |
| 407, 502, timeout | Simulated by hand | Real exception |

The code under test in the examples is the small function below. It takes the proxy URL from outside, hides the password in logs and returns JSON.

```python
# client.py
import logging
from urllib.parse import urlsplit

import requests

log = logging.getLogger(__name__)

def redact(proxy_url):
    """Hides the username and password for logging."""
    p = urlsplit(proxy_url)
    return f"{p.scheme}://***@{p.hostname}:{p.port}"

def fetch_items(base_url, proxy_url, timeout=5.0):
    proxies = {"http": proxy_url, "https": proxy_url}
    log.info("GET %s/items via %s", base_url, redact(proxy_url))
    resp = requests.get(f"{base_url}/items", proxies=proxies, timeout=timeout)
    resp.raise_for_status()
    return resp.json()
```

Setup is one line: `pip install pytest responses respx requests httpx`. Other ways to pass a proxy in Requests are covered in [Python Requests with a proxy](/blog/python-requests-proxy).

## Mocking the client

responses intercepts the send step in Requests and returns a registered response. A request to an unregistered URL gets a `ConnectionError`, so the test cannot reach the internet by accident. In our test, responses 0.26.3 kept the `proxies` dict passed to Requests in each call's `request.req_kwargs`. That is enough to check the proxy parameter.

```python
# test_mock_layer.py
import httpx
import responses
import respx

from client import fetch_items

PROXY = "http://user:pass@pr.proxynet.io:8000"

@responses.activate
def test_proxy_parameter_is_passed():
    responses.get("http://api.example.test/items", json={"items": [1, 2]})

    assert fetch_items("http://api.example.test", PROXY) == {"items": [1, 2]}

    sent = responses.calls[0].request.req_kwargs["proxies"]
    assert sent == {"http": PROXY, "https": PROXY}

@respx.mock
def test_httpx_response_is_handled():
    route = respx.get("https://api.example.test/items").mock(
        return_value=httpx.Response(200, json={"items": []})
    )
    with httpx.Client(proxy=PROXY) as client:
        resp = client.get("https://api.example.test/items")

    assert route.called
    assert resp.json() == {"items": []}
```

respx replaces the HTTPX transport layer. In our test, respx caught the request without ever connecting to the proxy, even though the client had one set. The network lock was on, and not a single connection was attempted. This test shows that the response is handled. It says nothing about the proxy. To verify the proxy in HTTPX, you need a fake proxy.

## Local fake proxy

A request to an HTTP proxy arrives in one of two forms. For an `http://` target, the client sends the full URL: `GET http://api.example.test/items HTTP/1.1`. For an `https://` target, it first asks for `CONNECT api.example.test:443` and sets up TLS inside that tunnel. In both cases the credentials arrive in a `Proxy-Authorization: Basic …` header.

The class below records the first line and the headers, then replies according to the chosen mode. Port `0` lets the operating system pick a free port. Parallel tests do not collide.

```python
# fake_proxy.py
import socketserver
import threading

OK = b'{"items": [1, 2, 3]}'

class FakeProxy:
    """Local HTTP proxy that records each request and returns the chosen reply."""

    def __init__(self, mode="ok", auth=None):
        self.mode = mode      # "ok", "502" or "hang"
        self.auth = auth      # expected Proxy-Authorization value
        self.seen = []        # each request: method, target, headers
        self._stop = threading.Event()

    def start(self):
        proxy = self

        class Handler(socketserver.StreamRequestHandler):
            def handle(self):
                line = self.rfile.readline().decode("latin-1").strip()
                if not line:
                    return
                headers = {}
                while (h := self.rfile.readline().decode("latin-1").strip()):
                    name, _, value = h.partition(":")
                    headers[name.strip().lower()] = value.strip()
                method, target, _ = line.split(" ", 2)
                proxy.seen.append(
                    {"method": method, "target": target, "headers": headers}
                )
                self.wfile.write(proxy.reply(headers))

        self._server = socketserver.ThreadingTCPServer(("127.0.0.1", 0), Handler)
        self._server.daemon_threads = True
        threading.Thread(
            target=self._server.serve_forever, args=(0.05,), daemon=True
        ).start()
        self.port = self._server.server_address[1]
        return self

    def reply(self, headers):
        if self.auth and headers.get("proxy-authorization") != self.auth:
            return (b"HTTP/1.1 407 Proxy Authentication Required\r\n"
                    b'Proxy-Authenticate: Basic realm="fake"\r\n'
                    b"Content-Length: 0\r\nConnection: close\r\n\r\n")
        if self.mode == "502":
            return (b"HTTP/1.1 502 Bad Gateway\r\n"
                    b"Content-Length: 0\r\nConnection: close\r\n\r\n")
        if self.mode == "hang":
            self._stop.wait(10)  # waits without replying
            return b""
        return (b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
                b"Content-Length: %d\r\nConnection: close\r\n\r\n" % len(OK)
                + OK)

    def url(self, user="user", password="pass"):
        return f"http://{user}:{password}@127.0.0.1:{self.port}"

    def stop(self):
        self._stop.set()
        self._server.shutdown()
        self._server.server_close()
```

The fake proxy does not open a tunnel. On the HTTPS side it tests only the `CONNECT` request and the status code it returns. For the proxy layer that is enough: the TLS handshake happens between you and the target site. A real [HTTPS Proxy](https://proxynet.io/https-proxy) does not read inside the tunnel either.

## Pytest fixture and offline CI

The fixture starts the fake proxy before each test and closes it after `yield`. The teardown code runs even when the test fails. The `offline` fixture uses `autouse=True`, so it applies to every test automatically.

```python
# conftest.py
import socket

import pytest

from fake_proxy import FakeProxy

LOCAL = ("127.0.0.1", "::1", "localhost")
PROXY_VARS = ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY")

@pytest.fixture(autouse=True)
def offline(monkeypatch):
    # keep CI proxy variables from affecting the test
    for name in PROXY_VARS + tuple(v.lower() for v in PROXY_VARS):
        monkeypatch.delenv(name, raising=False)

    real_connect = socket.socket.connect
    real_dns = socket.getaddrinfo

    def connect(sock, address):
        if address[0] not in LOCAL:
            raise RuntimeError(f"Network access blocked in tests: {address[0]}")
        return real_connect(sock, address)

    def dns(host, *args, **kwargs):
        if host not in LOCAL:
            raise RuntimeError(f"Network access blocked in tests: {host}")
        return real_dns(host, *args, **kwargs)

    monkeypatch.setattr(socket.socket, "connect", connect)
    monkeypatch.setattr(socket, "getaddrinfo", dns)

@pytest.fixture
def fake_proxy():
    proxy = FakeProxy().start()
    yield proxy
    proxy.stop()
```

`offline` does two things. First, it deletes the proxy variables from the environment. Requests reads them, and a `NO_PROXY` on the CI machine can route a request around the proxy. Then it blocks every connection and DNS lookup outside `127.0.0.1`. If the code skips the proxy, the test does not quietly reach the internet. It fails right away.

The actual tests check the request line and the header:

```python
# test_fake_proxy.py
import base64

import httpx
import pytest
import requests

from client import fetch_items
from fake_proxy import FakeProxy

def basic(user, password):
    token = base64.b64encode(f"{user}:{password}".encode()).decode()
    return f"Basic {token}"

def test_request_goes_through_proxy(fake_proxy):
    data = fetch_items("http://api.example.test", fake_proxy.url())

    assert data == {"items": [1, 2, 3]}
    req = fake_proxy.seen[0]
    assert req["method"] == "GET"
    assert req["target"] == "http://api.example.test/items"
    assert req["headers"]["proxy-authorization"] == basic("user", "pass")

def test_httpx_goes_through_proxy(fake_proxy):
    with httpx.Client(proxy=fake_proxy.url()) as client:
        resp = client.get("http://api.example.test/items")

    assert resp.json() == {"items": [1, 2, 3]}
    assert fake_proxy.seen[0]["target"] == "http://api.example.test/items"

def test_https_opens_connect_tunnel():
    proxy = FakeProxy(auth=basic("user", "pass")).start()
    try:
        with pytest.raises(requests.exceptions.ProxyError, match="407"):
            fetch_items("https://api.example.test", proxy.url(password="wrong"))
    finally:
        proxy.stop()

    req = proxy.seen[0]
    assert req["method"] == "CONNECT"
    assert req["target"] == "api.example.test:443"
    assert req["headers"]["proxy-authorization"] == basic("user", "wrong")
```

The name `api.example.test` is never resolved. The tests passed with the DNS lock on, because with an HTTP proxy the proxy resolves the target name.

## Testing the error paths

The same proxy error shows up as a different exception in Requests, depending on the target's scheme. For an `http://` target, the proxy's reply is an ordinary HTTP response, and `raise_for_status()` turns it into `HTTPError`. For an `https://` target, the error happens at the `CONNECT` step and you get `ProxyError`.

| Case | Fake proxy | `http://` target | `https://` target |
|---|---|---|---|
| 407 | Different `auth` | `HTTPError` | `ProxyError` |
| 502 | `mode="502"` | `HTTPError` | `ProxyError` |
| Connection refused | Closed port | `ProxyError` | `ProxyError` |
| Timeout | `mode="hang"` | `ReadTimeout` | `ReadTimeout` |

If your error handling only looks at `HTTPError`, it misses a 407 on an HTTPS target. We collected the production causes of 407 in [HTTP 407 Proxy Authentication Required](/blog/http-407-proxy-authentication-required). In tests, try both schemes:

```python
# test_errors.py
import socket

import pytest
import requests

from client import fetch_items
from fake_proxy import FakeProxy

API = "http://api.example.test"

@pytest.fixture
def proxy_with(request):
    proxy = FakeProxy(**request.param).start()
    yield proxy
    proxy.stop()

@pytest.mark.parametrize("proxy_with", [{"auth": "Basic eA=="}], indirect=True)
def test_407_on_http(proxy_with):
    with pytest.raises(requests.HTTPError, match="407"):
        fetch_items(API, proxy_with.url())

@pytest.mark.parametrize("proxy_with", [{"mode": "502"}], indirect=True)
def test_502_on_connect(proxy_with):
    with pytest.raises(requests.exceptions.ProxyError, match="502"):
        fetch_items("https://api.example.test", proxy_with.url())

def closed_port():
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]

def test_connection_refused():
    url = f"http://user:pass@127.0.0.1:{closed_port()}"
    with pytest.raises(requests.exceptions.ProxyError) as exc:
        fetch_items(API, url, timeout=2)
    assert ":pass@" not in str(exc.value)

@pytest.mark.parametrize("proxy_with", [{"mode": "hang"}], indirect=True)
def test_read_timeout(proxy_with):
    with pytest.raises(requests.exceptions.ReadTimeout):
        fetch_items(API, proxy_with.url(), timeout=0.5)
```

`closed_port()` takes a port and releases it at once. A request to that port finds no server listening. In our test, Windows did not refuse the connection immediately, and the request waited until the 2-second timeout. The result was still `ProxyError`. So give this test a short `timeout`.

Without a `timeout`, the timeout test hangs. The difference between connect and read timeouts is explained in [Proxy timeouts explained](/blog/proxy-timeouts-explained).

## Credential leaks

pytest prints values in plain text when a test fails. In a test we failed on purpose, the proxy URL showed up in three places: the test ID (`test_leak[http://user:pass@…]`), the argument line and the `assert` diff. In most teams, CI logs are open to a wide group.

Three rules are enough:

- Unit tests never read the real proxy password. The fake proxy accepts any password or expects the fake value you give it.
- If you use URLs inside `parametrize`, give them a short name with `ids=`.
- The code writes the proxy URL to logs only through `redact()`. Pin this with a test.

```python
import logging

def test_password_not_in_logs(fake_proxy, caplog):
    caplog.set_level(logging.INFO)
    fetch_items("http://api.example.test", fake_proxy.url())
    assert ":pass@" not in caplog.text
    assert "***@127.0.0.1" in caplog.text
```

We saw no problem in Requests' exception messages. None of the six error cases put the password in the message. Leaks mostly come from your own log lines and from test output.

## Debugging

When tests fail unexpectedly, the symptom usually names the cause:

- **`RuntimeError: Network access blocked in tests: api.example.test`.** The request skipped the proxy. The `proxies` dict was not passed, or it was passed with the wrong key.
- **`fake_proxy.seen` is empty.** The request went to a mock or was never sent. Do not use responses and the fake proxy in the same test.
- **A test that passes locally fails differently in CI.** `HTTP_PROXY` or `NO_PROXY` in the CI environment is active. Check that the `offline` fixture is loaded.
- **The test never finishes.** The client got no `timeout` in `hang` mode.
- **responses raises `ConnectionError`.** The registered URL and the requested URL are not identical. Scheme, port and the trailing `/` all count.

## How we tested

We ran the tests on December 2, 2026 on Windows 11, in a separate virtual environment. Versions: Python 3.13.17, pytest 9.2.0, Requests 2.34.2, HTTPX 0.29.0, responses 0.26.3 and respx 0.23.1. All the code in this post ran in a suite of twelve tests, and all of them passed. No test connected outside the local machine.

To see the lock work, we emptied the `proxies` dict inside `fetch_items`. Nine of the twelve tests failed. Eight hit the network lock, and the responses test caught the empty `proxies` dict. The three that passed were the HTTPX and network-lock tests, which was the expected result. For the password leak, we also ran a `parametrize` test that failed on purpose.

## The bottom line

Test the proxy parameter with a mock, proxy behavior with a local fake proxy and error paths with both URL schemes. Go to the real network only in a separate smoke test, for example a single request with a [Residential Proxy](https://proxynet.io/residential-proxy) account. Above all, never put a real password in tests: pytest prints it when a test fails.

## Sources

- [responses, README: github.com](https://github.com/getsentry/responses)
- [RESPX documentation: lundberg.github.io](https://lundberg.github.io/respx/)
- [pytest, How to use fixtures: docs.pytest.org](https://docs.pytest.org/en/stable/how-to/fixtures.html)
- [RFC 9110, §9.3.6 CONNECT: rfc-editor.org](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.3.6)

## Frequently asked questions

### Can I test proxy code without a real proxy?

Yes. A unit test does not need a real proxy. You mock the client with responses or respx, and for proxy behavior you run a small fake proxy on `127.0.0.1`. The real proxy is used only in a separate smoke test. That test runs apart from the unit tests and is the only one that reads the real credentials.

### Does responses verify the proxy setting?

Partly. responses catches the request at the send step in Requests and never connects to the proxy. In our test, responses 0.26.3 kept the `proxies` dict in each call's `request.req_kwargs`. That lets you check that the parameter was passed. You cannot see the `Proxy-Authorization` header or the `CONNECT` request. Those need a fake proxy. Do not combine the two layers in one test, because responses cuts the request off before it reaches the fake proxy.

### How do I test that HTTPX uses the proxy?

With a fake proxy. Send a request with `httpx.Client(proxy=fake_proxy.url())` and look at the request line the fake proxy recorded. respx is not the right tool here. In our test, respx caught the request without connecting to the proxy, even on a client with a proxy set. So it tests how the response is handled, not whether the proxy is used.

### How do I test an HTTPS request with a fake proxy?

Through the `CONNECT` line. For an HTTPS target, the client first asks for `CONNECT host:443`. The fake proxy records that line and the `Proxy-Authorization` header, then returns a status code such as 407 or 502. The inside of the tunnel is not tested. The TLS handshake happens between the client and the target, and it is not the proxy layer's job.

### How do I stop tests from reaching the internet in CI?

With a fixture that has `autouse=True`. The fixture replaces `socket.socket.connect` and `socket.getaddrinfo` through `monkeypatch`. It raises an error for every connection outside `127.0.0.1`. The same fixture also deletes `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY`. That way, CI settings do not change the test result. If the code skips the proxy, the test fails right away instead of reaching the internet, and it names the problem.

### Can the proxy password appear in test output?

Yes, it can. When a test fails, pytest prints the test ID, the argument values and the `assert` diff. If the proxy URL is in any of them, the password lands in the CI log too. Use only fake credentials in tests, give `parametrize` an `ids=` value and pass the code's log lines through a function that hides the password.
