HTTP server for testing environments
Project description
Spoof is a simple HTTP server for test environments.
>>> import requests
... import spoof
...
... with spoof.HTTPServer() as httpd:
... httpd.responses.append([200, [], "This is Spoof 👻👋"])
... requests.get(httpd.url).text
... httpd.requests
...
'This is Spoof 👻👋'
[SpoofRequestEnv(method='GET', uri='/', protocol='HTTP/1.1', serverName='localhost', serverPort=62775, headers=<http.client.HTTPMessage object at 0x10d8a8f50>, path='/', queryString=None, content=None, contentType=None, contentEncoding=None, contentLength=0)]
A test interface for HTTP
Spoof lets you easily create HTTP servers listening on real network sockets. Designed for test environments, what responses to return can be configured while an HTTP server is running, and requests can be inspected live or after a response is sent.
Unlike a traditional HTTP server, where specific methods and paths are configured in advance, Spoof accepts and captures all requests, sending whatever responses are queued, or a default response if the queue is empty.
Why would I want this?
Spoof is all about enabling test-driven development (and refactoring) of HTTP client code. Have you ever felt icky patching a client library to write tests? Ever been burned by this? Ever wanted to refactor a client library, but had no way to prove functionality apart from doing live integration testing? If you answered yes to any of the above, Spoof might be for you.
Spoof HTTP servers run in a single background thread, so request and response order should be predictable. Tests using Spoof should be able to use the same fixtures, in the same order, and get the same results.
Installation and Compatibility
Spoof is available on PyPI:
$ python -m pip install spoof
Spoof is tested on Python 3.10 to 3.14, leverages the http.server module included in the Python standard library, and has no external dependencies. It may work on older versions of Python, but this is not supported.
Multiple Spoof HTTP servers can be run concurrently, and by default, the port number is the next available unused port. With OpenSSL installed, Spoof can also provide an SSL/TLS HTTP server. HTTP proxying and IPv6 are also supported.
Request instances
Spoof captures each request as a namedtuple with the following properties:
Property |
Description |
|---|---|
content |
bytes object of request content |
contentEncoding |
Value of Content-Encoding header, if present |
contentLength |
Value of Content-Length header, if present |
contentType |
Value of Content-Type header, if present |
headers |
http.client.HTTPMessage object of headers |
json() |
Convenience to call json.loads on content |
method |
Request method (e.g. GET, POST, HEAD) |
path |
Decoded URI path, without query string |
protocol |
Protocol version (e.g. HTTP/1.0) |
queryString |
Anything in URI after ? |
serverName |
Host name of HTTP server |
serverPort |
Port number of HTTP server |
uri |
Raw URI path and query string, if present |
Example with request properties:
>>> import requests
... import spoof
...
... with spoof.HTTPServer() as httpd:
... httpd.defaultResponse = [200, [], None]
... [requests.get(httpd.url + path) for path in ["/a", "/b", "/c"]]
... [f"{r.method} {r.path} {r.protocol}" for r in httpd.requests]
...
[<Response [200]>, <Response [200]>, <Response [200]>]
['GET /a HTTP/1.1', 'GET /b HTTP/1.1', 'GET /c HTTP/1.1']
Response format
Spoof expects responses to have the following format:
[httpStatus, [(headerName1, value1), (headerName2, value2)], content]
# no content (Content-Length header is *not* sent if content is None)
[200, [], None]
# utf-8 content
[200, [], "This is Spoof 👻👋"]
# bytes content
[200, [("Content-Type", "application/json")], b'{"success": true }']
Queued responses
Queue multiple responses, verify content, and request paths:
import requests
import spoof
with spoof.HTTPServer() as httpd:
httpd.responses.extend([
[200, [("Content-Type", "application/json")], b'{"id": 1111}'],
[200, [("Content-Type", "application/json")], b'{"id": 2222}'],
])
httpd.defaultResponse = [404, [], "Not found"]
assert requests.get(httpd.url + "/path").json() == {"id": 1111}
assert requests.get(httpd.url + "/alt/path").json() == {"id": 2222}
assert requests.get(httpd.url + "/oops").status_code == 404
assert [r.path for r in httpd.requests] == ["/path", "/alt/path", "/oops"]
Callback response
Set a callback as the default response (callbacks can also be queued):
import requests
import spoof
with spoof.HTTPServer() as httpd:
httpd.defaultResponse = lambda request: [200, [], request.path]
assert requests.get(httpd.url + "/alt").content == b"/alt"
SSL/TLS Mode
Test queued response with a self-signed SSL/TLS certificate:
import requests
import spoof
with spoof.SelfSignedSSLContext() as selfSigned:
with spoof.HTTPServer(sslContext=selfSigned.sslContext) as httpd:
httpd.responses.append([200, [], "No self-signed cert warning!"])
response = requests.get(httpd.url, verify=selfSigned.certFile)
assert response.text == "No self-signed cert warning!"
If setting the verify option in requests isn’t workable, the REQUESTS_CA_BUNDLE or CURL_CA_BUNDLE environment variables can be set to the path of the self-signed certificate to silence SSL/TLS errors:
import os
import requests
import spoof
with spoof.SelfSignedSSLContext() as selfSigned:
with spoof.HTTPServer(sslContext=selfSigned.sslContext) as httpd:
os.environ["REQUESTS_CA_BUNDLE"] = selfSigned.certFile
httpd.responses.append([200, [], "No self-signed cert warning!"])
response = requests.get(httpd.url)
assert response.text == "No self-signed cert warning!"
If OpenSSL 3.5.0 or later is installed, Post-Quantum Cryptography (PQC) key algorithms can be used:
import requests
import spoof
with spoof.SelfSignedSSLContext(keyAlgorithm="mldsa65") as selfSigned:
with spoof.HTTPServer(sslContext=selfSigned.sslContext) as httpd:
httpd.responses.append([200, [], "TLS with PQC Key Algorithm"])
response = requests.get(httpd.url, verify=selfSigned.certFile)
assert response.text == "TLS with PQC Key Algorithm"
Proxy Mode
Spoof supports proxying HTTP requests by setting the upstream attribute to another Spoof instance. By design, Spoof won’t connect to any external services. Proxy requests will only connect to other Spoof instances.
Note that, as per Section 4.3.6 of RFC 7231, a proxy MUST not return return any content in response to a CONNECT request. Be sure to set any responses for proxy requests to an empty payload.
import requests
import spoof
with spoof.SelfSignedSSLContext(commonName="example.spoof") as ssl:
with spoof.HTTPServer(sslContext=ssl.sslContext) as proxy:
with spoof.HTTPServer(sslContext=ssl.sslContext) as upstream:
proxy.upstream = upstream
proxy.defaultResponse = [200, [], None]
upstream.defaultResponse = [200, [], "I'm here!"]
response = requests.get(
"https://example.spoof/ayt",
proxies={"https": proxy.url},
verify=ssl.certFile
)
assert proxy.requests[0].method == "CONNECT"
assert proxy.requests[0].path == "example.spoof:443"
assert upstream.requests[0].method == "GET"
assert upstream.requests[0].path == "/ayt"
assert response.content == b"I'm here!"
HTTP on IPv6
Setting the host attribute to an IPv6 address will work as expected. There is also an IPv6-only spoof.HTTPServer6 class that can be used if needed to only listen on IPv6 sockets.
>>> import requests
... import spoof
...
... with spoof.HTTPServer(host="::1") as httpd:
... httpd.responses.append([200, [], "This is Spoof on IPv6 👀"])
... requests.get(httpd.url).text
... httpd.url
...
'This is Spoof on IPv6 👀'
'http://[::1]:51324'
>>> import requests
... import spoof
...
... with spoof.HTTPServer6(host="localhost") as httpd:
... httpd.responses.append([200, [], "This is also Spoof on IPv6 👀"])
... requests.get(httpd.url).text
... httpd.url
...
'This is also Spoof on IPv6 👀'
'http://[::1]:54296'
Using a debugger
Setting a callback with a breakpoint() can allow for live HTTP request debugging, including setting custom responses and inspecting requests. Note that callbacks can also be queued.
>>> import requests
... import spoof
...
... def debugCallback(request):
... response = [200, [], ""]
... breakpoint()
... return response
...
... with spoof.HTTPServer() as httpd:
... httpd.defaultResponse = debugCallback
... requests.get(httpd.url).text
...
> <python-input-0>(6)debugCallback()
(Pdb) request
SpoofRequestEnv(content=None, contentEncoding=None, contentLength=0, contentType=None, headers=<http.client.HTTPMessage object at 0x10e16bd90>, method='GET', path='/', protocol='HTTP/1.1', queryString=None, serverName='localhost', serverPort=51612, uri='/')
(Pdb) response[2] = "content set from pdb"
(Pdb) c
'content set from pdb'
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file spoof-2.1.0.tar.gz.
File metadata
- Download URL: spoof-2.1.0.tar.gz
- Upload date:
- Size: 23.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ae12751c0f63c3b285648c42144784d12eecf70e52e49b36190c4faab52ffbf7
|
|
| MD5 |
9780bce6afe275dbb5c84ac68a5d40cd
|
|
| BLAKE2b-256 |
b573622a1a0608c402b6123eed540ea4307d87c0048487740608cd69aea16512
|
Provenance
The following attestation bundles were made for spoof-2.1.0.tar.gz:
Publisher:
release.yml on lexsca/spoof
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
spoof-2.1.0.tar.gz -
Subject digest:
ae12751c0f63c3b285648c42144784d12eecf70e52e49b36190c4faab52ffbf7 - Sigstore transparency entry: 1280235314
- Sigstore integration time:
-
Permalink:
lexsca/spoof@e589d9f39e2b46f41fff8f8e38edd0183481305d -
Branch / Tag:
refs/tags/v2.1.0 - Owner: https://github.com/lexsca
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@e589d9f39e2b46f41fff8f8e38edd0183481305d -
Trigger Event:
release
-
Statement type:
File details
Details for the file spoof-2.1.0-py3-none-any.whl.
File metadata
- Download URL: spoof-2.1.0-py3-none-any.whl
- Upload date:
- Size: 11.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1d08c13e286ecfe084bbeb09d36be7af6ce4a325c650a56f6fc3440f195d7dd7
|
|
| MD5 |
9da8bbb153d92fc1938ef35fab343367
|
|
| BLAKE2b-256 |
ed3fa19c7cfc9668cddab38be87f458f2dc1941d1d0f7a4f146e9b125ff9e17f
|
Provenance
The following attestation bundles were made for spoof-2.1.0-py3-none-any.whl:
Publisher:
release.yml on lexsca/spoof
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
spoof-2.1.0-py3-none-any.whl -
Subject digest:
1d08c13e286ecfe084bbeb09d36be7af6ce4a325c650a56f6fc3440f195d7dd7 - Sigstore transparency entry: 1280235317
- Sigstore integration time:
-
Permalink:
lexsca/spoof@e589d9f39e2b46f41fff8f8e38edd0183481305d -
Branch / Tag:
refs/tags/v2.1.0 - Owner: https://github.com/lexsca
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@e589d9f39e2b46f41fff8f8e38edd0183481305d -
Trigger Event:
release
-
Statement type: