dns-blocklist-mirror/tests/_support.py
XLion 7d99d7e4e8
All checks were successful
Checks / checks (push) Successful in 45s
Deploy Pages / deploy (push) Successful in 20s
Split tests by responsibility
2026-08-15 22:34:31 +08:00

119 lines
3.3 KiB
Python

from __future__ import annotations
import os
import ssl
import subprocess
import sys
import threading
from collections.abc import Iterator, Mapping
from contextlib import contextmanager
from dataclasses import dataclass, field
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import trustme
@dataclass(frozen=True)
class Response:
body: bytes
status: int = 200
headers: dict[str, str] = field(default_factory=dict)
include_content_length: bool = True
class RouteServer(ThreadingHTTPServer):
routes: dict[str, Response | list[Response]]
class RouteHandler(BaseHTTPRequestHandler):
server: RouteServer
def do_GET(self) -> None:
configured_response = self.server.routes.get(
self.path,
Response(body=b"not found\n", status=404),
)
if isinstance(configured_response, list):
response = configured_response.pop(0)
else:
response = configured_response
self.send_response(response.status)
for name, value in response.headers.items():
self.send_header(name, value)
if response.include_content_length and "Content-Length" not in response.headers:
self.send_header("Content-Length", str(len(response.body)))
self.end_headers()
self.wfile.write(response.body)
def log_message(self, format: str, *args: object) -> None:
pass
@contextmanager
def serve_http(
routes: Mapping[str, Response | list[Response]],
) -> Iterator[str]:
server = RouteServer(("127.0.0.1", 0), RouteHandler)
server.routes = dict(routes)
thread = threading.Thread(target=server.serve_forever)
thread.start()
try:
port = server.server_address[1]
yield f"http://localhost:{port}"
finally:
server.shutdown()
thread.join()
server.server_close()
@contextmanager
def serve_https(
tmp_path: Path,
routes: Mapping[str, Response | list[Response]],
) -> Iterator[tuple[str, Path]]:
certificate_authority = trustme.CA()
certificate = certificate_authority.issue_cert("localhost")
ca_path = tmp_path / "ca.pem"
certificate_authority.cert_pem.write_to_path(ca_path)
server = RouteServer(("127.0.0.1", 0), RouteHandler)
server.routes = dict(routes)
tls_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
certificate.configure_cert(tls_context)
server.socket = tls_context.wrap_socket(server.socket, server_side=True)
thread = threading.Thread(target=server.serve_forever)
thread.start()
try:
port = server.server_address[1]
yield f"https://localhost:{port}", ca_path
finally:
server.shutdown()
thread.join()
server.server_close()
def run_cli(
config_path: Path,
output_path: Path,
ca_path: Path | None = None,
) -> subprocess.CompletedProcess[str]:
environment = os.environ.copy()
if ca_path is not None:
environment["SSL_CERT_FILE"] = str(ca_path)
return subprocess.run(
[
sys.executable,
"-m",
"dns_blocklist_mirror",
"--config",
str(config_path),
"--output",
str(output_path),
],
check=False,
capture_output=True,
env=environment,
text=True,
)