288 lines
8.9 KiB
Python
Executable File
288 lines
8.9 KiB
Python
Executable File
"""Shared test doubles: an in-memory HTTP transport and file/command runner."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import urllib.parse
|
|
from dataclasses import dataclass
|
|
from typing import Any, Callable
|
|
|
|
from proxdomain.config import Config, parse_config
|
|
from proxdomain.http import Response
|
|
from proxdomain.runner import CommandResult
|
|
|
|
|
|
@dataclass
|
|
class Call:
|
|
method: str
|
|
url: str
|
|
path: str
|
|
query: dict[str, list[str]]
|
|
body: Any
|
|
|
|
def param(self, name: str, default: str | None = None) -> str | None:
|
|
values = self.query.get(name)
|
|
return values[0] if values else default
|
|
|
|
|
|
@dataclass
|
|
class Route:
|
|
method: str
|
|
path: str
|
|
handler: Callable[[Call], Any] | Any
|
|
status: int = 200
|
|
raw: bool = False
|
|
|
|
|
|
class FakeTransport:
|
|
def __init__(self) -> None:
|
|
self.routes: list[Route] = []
|
|
self.calls: list[Call] = []
|
|
|
|
def add(self, method: str, path: str, response: Any, *, status: int = 200) -> "FakeTransport":
|
|
self.routes.append(Route(method.upper(), path, response, status))
|
|
return self
|
|
|
|
def add_text(
|
|
self, method: str, path: str, text: str, *, status: int = 200
|
|
) -> "FakeTransport":
|
|
self.routes.append(Route(method.upper(), path, text, status, raw=True))
|
|
return self
|
|
|
|
# -- Transport protocol --------------------------------------------
|
|
def request(self, method, url, headers, body, timeout) -> Response:
|
|
split = urllib.parse.urlsplit(url)
|
|
call = Call(
|
|
method=method,
|
|
url=url,
|
|
path=split.path or "/",
|
|
query=urllib.parse.parse_qs(split.query),
|
|
body=json.loads(body.decode("utf-8")) if body else None,
|
|
)
|
|
self.calls.append(call)
|
|
for route in reversed(self.routes):
|
|
if route.method == method and route.path == (split.path or "/"):
|
|
payload = route.handler(call) if callable(route.handler) else route.handler
|
|
status = route.status
|
|
if isinstance(payload, tuple) and len(payload) == 2:
|
|
status, payload = payload
|
|
body = (
|
|
payload.encode("utf-8")
|
|
if route.raw
|
|
else json.dumps(payload).encode("utf-8")
|
|
)
|
|
return Response(
|
|
status=status,
|
|
body=body,
|
|
headers={"content-type": "text/plain" if route.raw else "application/json"},
|
|
)
|
|
return Response(
|
|
status=404,
|
|
body=json.dumps(
|
|
{"success": False, "errors": [{"code": 0, "message": "no route in fake"}]}
|
|
).encode("utf-8"),
|
|
headers={"content-type": "application/json"},
|
|
)
|
|
|
|
# -- helpers --------------------------------------------------------
|
|
def calls_to(self, method: str, path: str) -> list[Call]:
|
|
return [c for c in self.calls if c.method == method and c.path == path]
|
|
|
|
def count(self, method: str, path: str) -> int:
|
|
return len(self.calls_to(method, path))
|
|
|
|
|
|
def cf(payload: Any) -> dict:
|
|
return {"success": True, "errors": [], "result": payload}
|
|
|
|
|
|
def pve(payload: Any) -> dict:
|
|
return {"data": payload}
|
|
|
|
|
|
class FakeRunner:
|
|
"""In-memory stand-in for LocalRunner/SSHRunner."""
|
|
|
|
def __init__(
|
|
self,
|
|
files: dict[str, str] | None = None,
|
|
*,
|
|
failures: list[tuple[str, int, str]] | None = None,
|
|
) -> None:
|
|
self.files = dict(files or {})
|
|
self.dirs: set[str] = set()
|
|
self.commands: list[tuple[str, ...]] = []
|
|
self.failures = list(failures or [])
|
|
|
|
def run(self, argv, *, input_text=None, timeout: float = 120.0) -> CommandResult:
|
|
argv = tuple(argv)
|
|
self.commands.append(argv)
|
|
joined = " ".join(argv)
|
|
for needle, code, stderr in self.failures:
|
|
if needle in joined:
|
|
return CommandResult(argv, code, "", stderr)
|
|
if argv and argv[0] == "grep":
|
|
return self._grep(argv)
|
|
return CommandResult(argv, 0, "ok", "")
|
|
|
|
def _grep(self, argv: tuple[str, ...]) -> CommandResult:
|
|
needle = argv[-2]
|
|
directory = argv[-1].rstrip("/")
|
|
prefix = directory + "/"
|
|
for path, content in self.files.items():
|
|
if path.startswith(prefix) and "/" not in path[len(prefix):] and needle in content:
|
|
return CommandResult(argv, 0, path, "")
|
|
return CommandResult(argv, 1, "", "no match")
|
|
|
|
def write_text(self, path: str, content: str, mode: int = 0o644) -> bool:
|
|
current = self.files.get(path)
|
|
if current == content:
|
|
return False
|
|
self.files[path] = content
|
|
return True
|
|
|
|
def read_text(self, path: str) -> str | None:
|
|
return self.files.get(path)
|
|
|
|
def remove(self, path: str) -> bool:
|
|
return self.files.pop(path, None) is not None
|
|
|
|
def exists(self, path: str) -> bool:
|
|
path = path.rstrip("/")
|
|
return path in self.files or path in self.dirs or any(
|
|
name.startswith(path + "/") for name in self.files
|
|
)
|
|
|
|
def mkdir(self, path: str) -> None:
|
|
self.dirs.add(path.rstrip("/"))
|
|
|
|
def describe(self) -> str:
|
|
return "fake"
|
|
|
|
|
|
def make_config(
|
|
*,
|
|
proxmox: dict[str, Any] | None = None,
|
|
general: dict[str, Any] | None = None,
|
|
cloudflare: dict[str, Any] | None = None,
|
|
dns: dict[str, Any] | None = None,
|
|
state: dict[str, Any] | None = None,
|
|
**webserver: Any,
|
|
) -> Config:
|
|
raw: dict[str, Any] = {
|
|
"general": {"base_domain": "example.com"},
|
|
"proxmox": {
|
|
"api_url": "https://pve.example.com:8006/api2/json",
|
|
"token_id": "automation@pve!proxdomain",
|
|
"token_secret": "pve-secret",
|
|
},
|
|
"cloudflare": {"api_token": "cf-token", "proxied": True},
|
|
"dns": {"target": "guest"},
|
|
"webserver": {
|
|
"kind": "nginx",
|
|
"mode": "local",
|
|
},
|
|
"state": {"path": ":memory:"},
|
|
}
|
|
for section, values in (
|
|
("general", general),
|
|
("proxmox", proxmox),
|
|
("cloudflare", cloudflare),
|
|
("dns", dns),
|
|
("state", state),
|
|
):
|
|
if values:
|
|
raw[section].update(values)
|
|
raw["webserver"].update(webserver)
|
|
return parse_config(raw)
|
|
|
|
|
|
def add_proxmox_routes(
|
|
transport: FakeTransport,
|
|
*,
|
|
guests: list[dict] | None = None,
|
|
agent_ips: list[str] | None = None,
|
|
node: str = "pve",
|
|
guest_config: dict | None = None,
|
|
) -> None:
|
|
transport.add(
|
|
"GET",
|
|
"/api2/json/cluster/resources",
|
|
pve(guests if guests is not None else []),
|
|
)
|
|
if agent_ips is not None:
|
|
transport.add(
|
|
"GET",
|
|
f"/api2/json/nodes/{node}/qemu/101/agent/network-get-interfaces",
|
|
pve(
|
|
{
|
|
"result": [
|
|
{
|
|
"name": "eth0",
|
|
"ip-addresses": [
|
|
{"ip-address": ip, "ip-address-type": "ipv4"}
|
|
for ip in agent_ips
|
|
],
|
|
}
|
|
]
|
|
}
|
|
),
|
|
)
|
|
transport.add(
|
|
"GET",
|
|
f"/api2/json/nodes/{node}/qemu/101/config",
|
|
pve(dict(guest_config or {})),
|
|
)
|
|
|
|
|
|
def add_cloudflare_routes(
|
|
transport: FakeTransport,
|
|
*,
|
|
zone_id: str = "zone-1",
|
|
zone_name: str = "example.com",
|
|
existing: list[dict] | None = None,
|
|
) -> FakeTransport:
|
|
transport.add("GET", "/client/v4/zones", cf([{"id": zone_id, "name": zone_name}]))
|
|
transport.add(
|
|
"GET",
|
|
f"/client/v4/zones/{zone_id}/dns_records",
|
|
cf(list(existing or [])),
|
|
)
|
|
|
|
def create(call: Call):
|
|
return cf(
|
|
{
|
|
"id": "rec-created",
|
|
"name": call.body["name"],
|
|
"type": call.body["type"],
|
|
"content": call.body["content"],
|
|
"proxied": call.body.get("proxied", False),
|
|
"ttl": call.body.get("ttl", 1),
|
|
}
|
|
)
|
|
|
|
def update(call: Call):
|
|
return cf(
|
|
{
|
|
"id": call.path.rsplit("/", 1)[-1],
|
|
"name": call.body["name"],
|
|
"type": call.body["type"],
|
|
"content": call.body["content"],
|
|
"proxied": call.body.get("proxied", False),
|
|
"ttl": call.body.get("ttl", 1),
|
|
}
|
|
)
|
|
|
|
transport.add("POST", f"/client/v4/zones/{zone_id}/dns_records", create)
|
|
for record in existing or []:
|
|
transport.add(
|
|
"PATCH", f"/client/v4/zones/{zone_id}/dns_records/{record['id']}", update
|
|
)
|
|
transport.add(
|
|
"DELETE",
|
|
f"/client/v4/zones/{zone_id}/dns_records/{record['id']}",
|
|
cf({"id": record["id"]}),
|
|
)
|
|
transport.add("DELETE", f"/client/v4/zones/{zone_id}/dns_records/rec-created", cf({"id": "rec-created"}))
|
|
return transport
|