Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.d/1732.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
### Changed
- Tests render each committed Kubernetes kustomization once per test process and share the render. `docs/TESTING.md` and ADR 0007 now list kubectl's offline renderers, `kubectl kustomize` and `kubectl patch --local`, with git as tools tests run for real ([#1732](https://github.com/dan-petty/devops-cli/issues/1732)).
6 changes: 3 additions & 3 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ The vocabulary devops-cli's tests are designed and organised in, and the convent
### Test doubles

**Edge**:
A point where devops-cli reaches beyond its own process to something a test must not touch for real: another machine, a long-lived daemon, a program other than git or bwrap, the keyring, or the wall clock.
A point where devops-cli reaches beyond its own process to something a test must not touch for real: another machine, a long-lived daemon, a program other than git, bwrap or kubectl's offline renderers, the keyring, or the wall clock.
_Avoid_: boundary, external dependency, integration point

**Seam**:
Expand Down Expand Up @@ -63,8 +63,8 @@ Every new test follows these rules. Some of them name a path, fixture or check t
### Doubles

- A test doubles only edges. Everything inside the process runs for real.
- **Faked edges**: every program except git and bwrap (gh, kubectl, helm, minikube, the docker and podman CLIs, the scanners, and `uv run devops` calling itself), with `shutil.which` part of the process fake; all network, meaning HTTP on any client stack, raw sockets and DNS; GitHub's API, through the GitHub session or the PyGithub REST client; model and embedding providers; the Kubernetes API; the Docker engine; Valkey; Qdrant; outbound MCP servers; durable backends; OTLP export; the keyring and D-Bus.
- **Real**: the filesystem under `tmp_path`; environment and config, through the hermetic floor and the `config` fixture *(target)*; git in temporary repositories; bwrap in live tests; in-process servers, such as FastAPI's `TestClient` and loopback servers; randomness; host identity; and stdin, through `CliRunner(input=...)`.
- **Faked edges**: every program except git, bwrap and kubectl's offline renderers (gh, the rest of kubectl, helm, minikube, the docker and podman CLIs, the scanners, and `uv run devops` calling itself), with `shutil.which` part of the process fake; all network, meaning HTTP on any client stack, raw sockets and DNS; GitHub's API, through the GitHub session or the PyGithub REST client; model and embedding providers; the Kubernetes API; the Docker engine; Valkey; Qdrant; outbound MCP servers; durable backends; OTLP export; the keyring and D-Bus.
- **Real**: the filesystem under `tmp_path`; environment and config, through the hermetic floor and the `config` fixture *(target)*; git in temporary repositories; kubectl's offline renderers, `kubectl kustomize` and `kubectl patch --local`, which read only files and reach no cluster; bwrap in live tests; in-process servers, such as FastAPI's `TestClient` and loopback servers; randomness; host identity; and stdin, through `CliRunner(input=...)`.
- No test starts a real gh, which would act as the developer's own login: a gh command a test reaches goes to a fake, and the floor fails a test that starts gh *(target)*.
- Each edge has one seam in `src/devops_cli`: a Protocol, plus the one place that supplies the real implementation *(target for most edges)*. The clock's seam is the sleep and clock parameters the libraries take, with no Protocol, as [Clock](#clock) describes. A test installs the edge's fake through the seam's fixture, or through a constructor or parameter the domain code already takes.
- Each edge has one fake, in `tests/support/fakes/<edge>.py`, shared by every test that reaches the edge. A test does not build its own double of an edge.
Expand Down
4 changes: 2 additions & 2 deletions docs/adr/0007-tests-double-only-process-edges.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Tests double only process edges, through seams

Tests replace only what devops-cli reaches beyond its own process: other machines, long-lived daemons, programs other than git and bwrap, the keyring and the wall clock. Everything inside the process runs for real, and no test patches a devops-cli module, function or private name. Each edge has one seam in the source tree that supplies its real implementation, and a test installs an in-memory fake through that seam. On 2026-10-07 the suite held 3,655 patch sites, 2,770 of them aimed at devops-cli internals, and 937 imports of private names. Refactors that kept behaviour still broke tests, and product code had grown branches that detect mocks or reshape modules so tests can patch them. The roadmap package showed the alternative already works: about 470 tests over an in-memory store and an injected `runner=` need about 68 patches.
Tests replace only what devops-cli reaches beyond its own process: other machines, long-lived daemons, programs other than git, bwrap and kubectl's offline renderers, the keyring and the wall clock. Everything inside the process runs for real, and no test patches a devops-cli module, function or private name. Each edge has one seam in the source tree that supplies its real implementation, and a test installs an in-memory fake through that seam. On 2026-10-07 the suite held 3,655 patch sites, 2,770 of them aimed at devops-cli internals, and 937 imports of private names. Refactors that kept behaviour still broke tests, and product code had grown branches that detect mocks or reshape modules so tests can patch them. The roadmap package showed the alternative already works: about 470 tests over an in-memory store and an injected `runner=` need about 68 patches.

## Considered Options

Expand All @@ -15,5 +15,5 @@ Tests replace only what devops-cli reaches beyond its own process: other machine
- Every fake has a contract suite, run against the fake and against the real implementation with recorded responses or a local tool. The fakes live in `tests/support/fakes/`, one module per edge.
- The hermetic floor fails a test that reaches an edge without a fake, and resets process-wide state after every test. gh is such an edge: a test that starts a real gh would act as the developer's own login.
- Product code that detects mocks or exists only to be patched is removed, and ratchets keep internal patches, private imports and those accommodations from growing until each reaches zero.
- git and bwrap run for real inside temporary directories; bwrap tests are skipped only where bwrap is missing.
- git and bwrap run for real inside temporary directories; bwrap tests are skipped only where bwrap is missing. kubectl's offline renderers, `kubectl kustomize` and `kubectl patch --local`, also run for real: they read only files and reach no cluster, and no maintained renderer exists to fake them with (added on 2026-10-20 by #1725).
- [`docs/TESTING.md`](../TESTING.md) states the conventions that follow from this decision.
18 changes: 18 additions & 0 deletions docs/agent/tasks/task-1732-kustomize-renders-once.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Task: Committed Kustomizations Render Once per Test Process, with kubectl's Offline Renderers Run as Real Tools (#1732)

**Issue**: [#1732](https://github.com/dan-petty/devops-cli/issues/1732)
**Scope**: scope/ci
**Feasibility**: A recorder under `subprocess.Popen._execute_child` and `os.posix_spawn`, run over the 158 test files that mention kubectl, found exactly 33 tests that start `kubectl`. None reaches a cluster: the root conftest's session-wide `isolate_kubeconfig` (`tests/conftest.py`) gives every test an empty kubeconfig. Against that kubeconfig, `kubectl config get-contexts -o name` exits 0 with no output. The tests run `kubectl kustomize`, plus one `kubectl patch --local`. No maintained Python kustomize exists, so the renders stay real, as decided on #1725 on 2026-10-20.

## Description

- [x] `docs/TESTING.md` and ADR 0007 list kubectl's offline renderers, `kubectl kustomize` and `kubectl patch --local`, with git as programs tests run for real. They read only files and reach no cluster.
- [x] `tests/k8s_manifests.py` renders each committed kustomization under `k8s/` once per test process, keyed by its resolved directory, and shares the render. A kustomization a test builds under `tmp_path` renders per call.
- The Argo CD application, network policy and monitoring invariants and the overrides test read their renders through it.
- `tests/test_k8s_argocd_apps.py` parses them with libyaml's `CSafeLoader`.
- Every assertion is kept.
- [x] Measured on the 33 tests, alternating before and after runs at load 10-19:
- serially: 17.6s to 12.8s wall;
- at `-n 4`: 19.9s to 14.8s wall;
- the nine repository-render tests other than the Argo CD gate test, serially: 7.3s to 2.5s.
- The Argo CD gate test renders inside devops-cli's own `run_subprocess`, so it can't share the render without patching devops-cli. It stays at about 2s.
49 changes: 41 additions & 8 deletions tests/k8s_manifests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,60 @@
`kubectl kustomize` renders a kustomization exactly as `kubectl apply -k` applies it: nested
kustomizations, generators and the `namespace` transformer included. A manifest file is what
`kubectl apply -f` applies. Both answer with (namespace, name) for each object of one kind.

A committed kustomization under the repository's `k8s/` renders the same for the whole run, since
no test writes to the workspace, so each is rendered once per test process, keyed by its resolved
directory, and shared by every test that asks for it. A kustomization a test builds under
`tmp_path` is rendered each time it is asked for.
"""

from __future__ import annotations

import functools
import subprocess
from collections.abc import Iterable
from pathlib import Path

import yaml

from tests.support.paths import REPO_ROOT

# `kubectl kustomize` reads local files only and renders the repository's largest kustomization
# in well under a second; the bound stops a hung binary, not a slow render.
KUSTOMIZE_TIMEOUT_SECONDS = 30

COMMITTED_KUSTOMIZATIONS = REPO_ROOT / "k8s"
"""The tree of committed kustomizations, whose renders the run shares."""


def _render(directory: Path) -> subprocess.CompletedProcess[str]:
"""Run `kubectl kustomize <directory>`, keeping its exit code and output for the caller."""
return subprocess.run(
["kubectl", "kustomize", str(directory)],
check=False,
capture_output=True,
text=True,
timeout=KUSTOMIZE_TIMEOUT_SECONDS,
)


@functools.cache
def _render_committed(directory: Path) -> subprocess.CompletedProcess[str]:
"""The render of a committed kustomization, made once per test process."""
return _render(directory)


def kustomize(directory: Path, *, check: bool = True) -> subprocess.CompletedProcess[str]:
"""`kubectl kustomize <directory>`; with `check`, a failed render raises `CalledProcessError`."""
resolved = directory.resolve()
if resolved.is_relative_to(COMMITTED_KUSTOMIZATIONS):
rendered = _render_committed(resolved)
else:
rendered = _render(directory)
if check:
rendered.check_returncode()
return rendered


def _named(documents: Iterable[object], kind: str) -> set[tuple[str, str]]:
"""Return (namespace, name) of each document of this kind."""
Expand All @@ -29,14 +69,7 @@ def _named(documents: Iterable[object], kind: str) -> set[tuple[str, str]]:

def kustomized_objects(directory: Path, kind: str) -> set[tuple[str, str]]:
"""Return (namespace, name) of every `kind` object `kubectl apply -k <directory>` applies."""
rendered = subprocess.run(
["kubectl", "kustomize", str(directory)],
check=True,
capture_output=True,
text=True,
timeout=KUSTOMIZE_TIMEOUT_SECONDS,
)
return _named(yaml.load_all(rendered.stdout, Loader=yaml.CSafeLoader), kind)
return _named(yaml.load_all(kustomize(directory).stdout, Loader=yaml.CSafeLoader), kind)


def manifest_objects(path: Path, kind: str) -> set[tuple[str, str]]:
Expand Down
43 changes: 13 additions & 30 deletions tests/test_k8s_argocd_apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
_MANIFESTS_BY_STACK,
)
from devops_cli.k8s.cluster_secrets import CLUSTER_SECRETS
from tests.k8s_manifests import kustomize, kustomized_objects
from tests.support.paths import REPO_ROOT

K8S_DIR = REPO_ROOT / "k8s"
Expand Down Expand Up @@ -306,13 +307,8 @@ def test_rendered_raw_objects_single_ownership() -> None:

for app_name, dir_path in raw_leaf_apps.items():
assert app_name in apps
proc = subprocess.run(
["kubectl", "kustomize", str(dir_path)],
check=True,
capture_output=True,
text=True,
)
docs = list(yaml.safe_load_all(proc.stdout))
proc = kustomize(dir_path)
docs = list(yaml.load_all(proc.stdout, Loader=yaml.CSafeLoader))
for doc in docs:
if not doc:
continue
Expand Down Expand Up @@ -354,13 +350,8 @@ def test_namespace_and_pvc_data_safety() -> None:
raw_leaf_apps = list(discover_path_applications(REPO_ROOT, APPS_DIR).values())

for dir_path in raw_leaf_apps:
proc = subprocess.run(
["kubectl", "kustomize", str(dir_path)],
check=True,
capture_output=True,
text=True,
)
docs = list(yaml.safe_load_all(proc.stdout))
proc = kustomize(dir_path)
docs = list(yaml.load_all(proc.stdout, Loader=yaml.CSafeLoader))
for doc in docs:
if not doc:
continue
Expand Down Expand Up @@ -423,8 +414,6 @@ def test_argocd_enables_the_web_terminal() -> None:

def test_exactly_one_application_renders_argocd_default_perimeter() -> None:
"""The argocd-default-perimeter NetworkPolicy is rendered by exactly one Application (#1673)."""
from tests.k8s_manifests import kustomized_objects

apps = _all_applications()
rendering_apps: list[str] = []
for name, app in apps.items():
Expand Down Expand Up @@ -463,15 +452,10 @@ def test_applicationset_controller_disabled_with_zero_replicas() -> None:
def test_homelab_domain_overlays() -> None:
for overlay in ("devops", "ingress"):
overlay_dir = K8S_DIR / "overlays" / "homelab" / overlay
proc = subprocess.run(
["kubectl", "kustomize", str(overlay_dir)],
check=True,
capture_output=True,
text=True,
)
proc = kustomize(overlay_dir)
assert proc.returncode == 0, f"Overlay {overlay} failed to build: {proc.stderr}"

docs = [d for d in yaml.safe_load_all(proc.stdout) if d]
docs = [d for d in yaml.load_all(proc.stdout, Loader=yaml.CSafeLoader) if d]
assert len(docs) > 0, f"No documents rendered for overlay {overlay}"
for doc in docs:
assert "kind" in doc
Expand Down Expand Up @@ -658,13 +642,12 @@ def test_image_updater_keeps_only_application_devops_on_the_digest_of_service_la

def test_no_application_renders_the_devops_cli_config_map_and_no_commit_holds_it() -> None:
"""The ConfigMap is rendered from the active config at deploy time, never from git."""
rendered = subprocess.run(
["kubectl", "kustomize", str(K8S_DIR / "overlays" / "homelab" / "devops")],
check=True,
capture_output=True,
text=True,
).stdout
objects = [(d["kind"], d["metadata"]["name"]) for d in yaml.safe_load_all(rendered) if d]
rendered = kustomize(K8S_DIR / "overlays" / "homelab" / "devops").stdout
objects = [
(d["kind"], d["metadata"]["name"])
for d in yaml.load_all(rendered, Loader=yaml.CSafeLoader)
if d
]
ignored = subprocess.run(
["git", "check-ignore", "-q", "k8s/devops/configmap.yaml"],
cwd=REPO_ROOT,
Expand Down
13 changes: 4 additions & 9 deletions tests/test_k8s_argocd_overrides.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
host_patches,
render_at_revision,
)
from tests.k8s_manifests import kustomize
from tests.support.paths import REPO_ROOT

K8S_DIR = REPO_ROOT / "k8s"
Expand Down Expand Up @@ -221,12 +222,6 @@ def test_a_revision_that_cannot_render_is_refused(
)


def _kustomize(directory: Path) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["kubectl", "kustomize", str(directory)], capture_output=True, text=True, check=False
)


def _hosts(rendered: str) -> list[str]:
hosts = []
for doc in yaml.safe_load_all(rendered):
Expand All @@ -252,8 +247,8 @@ def test_kustomize_applies_the_overrides_to_every_host_the_application_renders(
) -> None:
manifest = yaml.safe_load((K8S_DIR / "argocd" / "apps" / f"{application}.yaml").read_text())
source = REPO_ROOT / manifest["spec"]["source"]["path"]
before = _kustomize(source).stdout
after = _kustomize(_overlay(tmp_path, source, host_patches(before, DOMAIN)))
before = kustomize(source, check=False).stdout
after = kustomize(_overlay(tmp_path, source, host_patches(before, DOMAIN)), check=False)
hosts = _hosts(after.stdout)
assert (
after.returncode,
Expand All @@ -277,5 +272,5 @@ def test_overrides_fail_the_build_when_git_moved_a_host_rather_than_route_it_els
(source / "ingress.yaml").write_text(swapped.replace("SWAP", "example.com"), encoding="utf-8")
overlay = tmp_path / "overlay"
overlay.mkdir()
result = _kustomize(_overlay(overlay, source, patches))
result = kustomize(_overlay(overlay, source, patches), check=False)
assert (result.returncode != 0, "test" in result.stderr.lower()) == (True, True)
Loading