Skip to content

Commit e5c34b5

Browse files
committed
fix(test): require reliable Terraform cleanup evidence
Signed-off-by: Senol Colak <senol.colak@sap.com>
1 parent 127a822 commit e5c34b5

5 files changed

Lines changed: 161 additions & 13 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ jobs:
4949
- name: Test CLI harness reporting and coverage gates
5050
run: python3 -m unittest discover -s test/cli -p 'test_*.py' -v
5151

52+
- name: Test Terraform harness evidence gates
53+
run: python3 -m unittest discover -s test/terraform -p 'test_*.py' -v
54+
5255
- name: Upload binary artifact
5356
uses: actions/upload-artifact@v7
5457
with:

‎.gitignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,10 @@ cirros*.img
8888
# HOST_TESTING_REAL_MODE.md generates this (ideally under /tmp); guard the repo-root path too.
8989
/lightstack-real-values.yaml
9090

91+
# Keep important root docs
92+
# Python harness regression tests
93+
__pycache__/
94+
9195
# Keep important root docs
9296
!/README.md
9397
!/CLAUDE.md

‎test/terraform/README.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ bash test/terraform/run.sh
3939
The preflight prints an install hint if it is missing.
4040
- The **OpenStack CLI** for prerequisite setup (image/flavor); set `OPENSTACK_CLI` if it is not
4141
on `PATH` (e.g. `/opt/osc-venv/bin/openstack`).
42+
- **curl**, **jq**, and **timeout** (GNU coreutils) on `PATH`.
4243
- Network access to the public Terraform registry on **first** run only (provider download);
4344
afterwards the shared `TF_PLUGIN_CACHE_DIR` (default `~/.terraform.d/plugin-cache`) serves it.
4445

@@ -80,6 +81,16 @@ A **nightly workflow job** (`.github/workflows/nightly.yml`) runs `make test-ter
8081
against a fresh stub-mode Lightstack deployment with only the wrapper's own image present.
8182
The wrapper is not part of the per-PR CI gate because it needs a running server.
8283

84+
PR CI exercises the wrapper's evidence gates with fake external clients:
85+
86+
```bash
87+
python3 -m unittest discover -s test/terraform -p 'test_*.py' -v
88+
```
89+
90+
These regression tests check that failed catalog/resource listings and unreadable
91+
Terraform state fail the run, and that leaked resources (including nameless floating
92+
IPs captured from state) cannot produce a successful cleanup report.
93+
8394
## Known divergences
8495

8596
None currently. The one this wrapper used to carry — Glance ignoring the `?name=`

‎test/terraform/run.sh‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,9 @@ OSC="${OPENSTACK_CLI:-$(command -v openstack || true)}"
138138
(e.g. /opt/osc-venv/bin/openstack) or put it on PATH."
139139

140140
[ -d "$MODULE_DIR" ] || die "compat module not found at $MODULE_DIR"
141-
command -v curl >/dev/null 2>&1 || die "curl not found on PATH"
141+
for tool in curl jq timeout; do
142+
command -v "$tool" >/dev/null 2>&1 || die "$tool not found on PATH"
143+
done
142144

143145
log "terraform version"
144146
terraform version | head -1
@@ -151,11 +153,14 @@ curl -sf --max-time 10 "$OS_AUTH_URL" -o /dev/null \
151153

152154
# Every catalog endpoint must be reachable, or apply will hang creating the
153155
# resource that talks to the dead port (HOST_TESTING.md §7).
156+
catalog_endpoints="$("$OSC" catalog list -f value -c Endpoints)" \
157+
|| die "cannot list service catalog endpoints"
158+
catalog_urls="$(printf '%s\n' "$catalog_endpoints" | grep -oE 'https?://[a-zA-Z0-9.:/-]+' | sort -u)" \
159+
|| die "service catalog contains no endpoint URLs"
154160
while IFS= read -r url; do
155161
curl -s -o /dev/null --max-time 10 "$url" \
156162
|| die "catalog endpoint unreachable: $url (OS_AUTH_URL=$OS_AUTH_URL)"
157-
done < <("$OSC" catalog list -f value -c Endpoints 2>/dev/null \
158-
| grep -oE 'https?://[a-zA-Z0-9.:/-]+' | sort -u)
163+
done <<<"$catalog_urls"
159164
log "auth OK, all catalog endpoints reachable"
160165

161166
# ---------------------------------------------------------------------------
@@ -250,9 +255,14 @@ $plan_out"
250255
# Floating IPs carry no name, so the post-destroy residue sweep cannot match
251256
# them by prefix. Capture the module's own FIP ids from the state now —
252257
# before destroy empties it — and assert each is gone afterwards.
253-
FIP_IDS_BEFORE_DESTROY="$(tf state pull -no-color 2>/dev/null \
254-
| jq -r '[.resources[]? | select(.type == "openstack_networking_floatingip_v2")
255-
| .instances[]?.attributes.id] | join(" ")' 2>/dev/null || true)"
258+
# A failed pull or malformed state must not silently erase the IDs whose
259+
# absence we need to prove after destroy. pipefail preserves both failures.
260+
FIP_IDS_BEFORE_DESTROY="$(tf state pull \
261+
| jq -er '[.resources[] | select(.type == "openstack_networking_floatingip_v2")
262+
| .instances[].attributes.id]
263+
| if all(.[]; type == "string" and length > 0) then join(" ")
264+
else error("invalid floating IP ID in state") end')" \
265+
|| die "unable to capture floating IP IDs from Terraform state"
256266

257267
log "terraform destroy"
258268
tf destroy -auto-approve -input=false -no-color "${TF_VAR_ARGS[@]}" 2>&1 \
@@ -282,22 +292,22 @@ log "outputs: none"
282292
# silently stop covering the surface when it does. Floating IPs carry no
283293
# name at all — they are covered by the id-based check below.
284294
residue=0
285-
for res in "server list" "network list" "security group list" "volume list" "keypair list"; do
286-
n="$("$OSC" $res -f value -c Name 2>/dev/null | grep -c '^tf-compat-' || true)"
295+
for res in "server list" "network list" "security group list" "volume list" "keypair list" "subnet list" "router list"; do
296+
read -r -a resource_args <<<"$res"
297+
names="$("$OSC" "${resource_args[@]}" -f value -c Name)" \
298+
|| die "cannot check residue: openstack $res failed"
299+
n="$(printf '%s\n' "$names" | grep -c '^tf-compat-' || true)"
287300
residue=$((residue + n))
288301
done
289-
n="$("$OSC" subnet list -f value -c Name 2>/dev/null | grep -c '^tf-compat-' || true)"
290-
residue=$((residue + n))
291-
n="$("$OSC" router list -f value -c Name 2>/dev/null | grep -c '^tf-compat-' || true)"
292-
residue=$((residue + n))
293302
# The module's own floating IPs, captured from state before destroy — the
294303
# only precise check available for nameless resources. Resolved through the
295304
# LIST, not 'floating ip show': the pinned OSC 7.0.0 fails that command
296305
# client-side on every invocation ("Invalid formatter provided.", osc-lib
297306
# 4.7.0 vs the plain-callable port_details formatter), so a show-based probe
298307
# would report "gone" unconditionally — including for a leaked FIP.
299308
if [ -n "$FIP_IDS_BEFORE_DESTROY" ]; then
300-
fip_list="$("$OSC" floating ip list -f value -c ID 2>/dev/null || true)"
309+
fip_list="$("$OSC" floating ip list -f value -c ID)" \
310+
|| die "cannot check residue: openstack floating ip list failed"
301311
for fip in $FIP_IDS_BEFORE_DESTROY; do
302312
if printf '%s\n' "$fip_list" | grep -qx "$fip"; then
303313
residue=$((residue + 1))

‎test/terraform/test_runner.py‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
"""Exercise the real wrapper with fake clients to verify its evidence gates."""
2+
import os
3+
import subprocess
4+
import sys
5+
import tempfile
6+
import unittest
7+
from pathlib import Path
8+
9+
10+
RUNNER = Path(__file__).resolve().parent / "run.sh"
11+
LISTS = ("server list", "network list", "security group list",
12+
"volume list", "keypair list", "subnet list", "router list")
13+
14+
# Only the external clients are replaced. The wrapper still runs its full
15+
# preflight, workspace handling, apply/destroy, and clean-state assertions.
16+
CLIENT = r'''
17+
import json
18+
import os
19+
import sys
20+
from pathlib import Path
21+
22+
tool = Path(sys.argv[0]).name
23+
args = sys.argv[1:]
24+
if tool == "curl":
25+
sys.exit(0)
26+
if tool == "openstack":
27+
command = " ".join(args[:3] if args[0] in ("security", "floating") else args[:2])
28+
if command == os.environ.get("FAIL_LIST"):
29+
print("simulated API failure", file=sys.stderr)
30+
sys.exit(1)
31+
if command == "catalog list":
32+
print("http://localhost:35357/v3")
33+
elif command == "floating ip list":
34+
print("fip-owned" if os.environ.get("LEAK_LIST") == command else "fip-unrelated")
35+
elif command.endswith(" list"):
36+
print("tf-compat-leftover" if os.environ.get("LEAK_LIST") == command else "unrelated")
37+
else:
38+
print("fixture-id")
39+
sys.exit(0)
40+
41+
workspace = None
42+
if args[0].startswith("-chdir="):
43+
workspace = Path(args.pop(0).split("=", 1)[1])
44+
if args[0] == "version":
45+
print("Terraform v1.13.4")
46+
elif args[:2] == ["state", "pull"]:
47+
if os.environ.get("STATE_MODE") == "error":
48+
sys.exit(1)
49+
if os.environ.get("STATE_MODE") == "malformed":
50+
print("{")
51+
elif os.environ.get("STATE_MODE") == "no-fips":
52+
print(json.dumps({"version": 4, "resources": []}))
53+
else:
54+
print(json.dumps({"version": 4, "resources": [{
55+
"type": "openstack_networking_floatingip_v2",
56+
"instances": [{"attributes": {"id": "fip-owned"}}],
57+
}]}))
58+
elif args[0] == "output":
59+
print("{}")
60+
elif args[0] == "destroy":
61+
(workspace / "destroyed").touch()
62+
elif args[0] == "plan" and (workspace / "destroyed").exists():
63+
print("Plan: 9 to add, 0 to change, 0 to destroy.")
64+
sys.exit(2)
65+
'''
66+
67+
68+
class TerraformRunnerTests(unittest.TestCase):
69+
def setUp(self):
70+
self.directory = tempfile.TemporaryDirectory()
71+
self.addCleanup(self.directory.cleanup)
72+
self.root = Path(self.directory.name)
73+
for tool in ("terraform", "openstack", "curl"):
74+
script = self.root / tool
75+
script.write_text(f"#!{sys.executable}\n" + CLIENT)
76+
script.chmod(0o755)
77+
78+
def run_wrapper(self, **settings):
79+
env = dict(os.environ, PATH=f"{self.root}{os.pathsep}{os.environ['PATH']}",
80+
OPENSTACK_CLI=str(self.root / "openstack"),
81+
TF_PLUGIN_CACHE_DIR=str(self.root / "cache"),
82+
TF_RESULTS_DIR=str(self.root / "results"),
83+
TMPDIR=str(self.root), FAIL_LIST="", LEAK_LIST="", STATE_MODE="")
84+
env.update(settings)
85+
return subprocess.run(["bash", str(RUNNER)], env=env, text=True,
86+
capture_output=True, timeout=30, check=False)
87+
88+
def assert_failed(self, result):
89+
self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)
90+
self.assertNotIn("SUMMARY: PASS", result.stdout)
91+
92+
def test_success_requires_clean_state_and_unrelated_objects_are_ignored(self):
93+
for mode in ("", "no-fips"):
94+
with self.subTest(mode=mode):
95+
result = self.run_wrapper(STATE_MODE=mode)
96+
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
97+
self.assertIn("SUMMARY: PASS", result.stdout)
98+
self.assertFalse(list(self.root.glob("tf-compat-workspace.*")))
99+
100+
def test_failed_resource_listing_cannot_prove_no_residue(self):
101+
for command in (*LISTS, "floating ip list"):
102+
with self.subTest(command=command):
103+
self.assert_failed(self.run_wrapper(FAIL_LIST=command))
104+
105+
def test_leaked_resources_fail_including_nameless_floating_ips(self):
106+
for command in (*LISTS, "floating ip list"):
107+
with self.subTest(command=command):
108+
self.assert_failed(self.run_wrapper(LEAK_LIST=command))
109+
110+
def test_unreadable_state_cannot_hide_floating_ips(self):
111+
for mode in ("error", "malformed"):
112+
with self.subTest(mode=mode):
113+
self.assert_failed(self.run_wrapper(STATE_MODE=mode))
114+
115+
def test_catalog_failure_cannot_pass_preflight(self):
116+
self.assert_failed(self.run_wrapper(FAIL_LIST="catalog list"))
117+
118+
119+
if __name__ == "__main__":
120+
unittest.main()

0 commit comments

Comments
 (0)