mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-29 22:37:29 +00:00
Merge branch 'feature/variant-split' into feature/store-i18n
variant_split and variant_tree tools with their i8 skills. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
f6debb01e7
28 files changed
+4048
No files matched your search
@@ -0,0 +1,94 @@
|
||||
"""Snapshot builders shared by the variant-split tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable
|
||||
|
||||
SEED = "42305502796"
|
||||
|
||||
|
||||
def edge(
|
||||
consumer: str,
|
||||
key: str,
|
||||
provider: str,
|
||||
*,
|
||||
cv: int = 0,
|
||||
pv: int = 0,
|
||||
shared: str = "shared",
|
||||
) -> list:
|
||||
return [consumer, cv, key, provider, pv, shared]
|
||||
|
||||
|
||||
def record(
|
||||
include: Iterable[str],
|
||||
edges: Iterable[list] = (),
|
||||
*,
|
||||
active: dict[str, int] | None = None,
|
||||
dark: Iterable[str] = (),
|
||||
dictated: dict[str, str] | None = None,
|
||||
error: str | None = None,
|
||||
) -> dict:
|
||||
members = list(include)
|
||||
return {
|
||||
"include": members,
|
||||
"active": {role: (active or {}).get(role, 0) for role in members},
|
||||
"edges": sorted(edges),
|
||||
"dark_pins": list(dark),
|
||||
"dictated": dict(dictated or {}),
|
||||
"error": error,
|
||||
}
|
||||
|
||||
|
||||
def entry(tok: str, mode: str = "compose", network: str = "clearnet") -> dict:
|
||||
name, variant = tok.rsplit("#", 1)
|
||||
return {
|
||||
"apps": name,
|
||||
"variant": variant,
|
||||
"mode": mode,
|
||||
"network": network,
|
||||
"distro": "debian",
|
||||
"priority": "false",
|
||||
"covered": "0",
|
||||
"clone": "false",
|
||||
}
|
||||
|
||||
|
||||
def row(tok: str, rid: int, covered_by: int = 0) -> dict:
|
||||
name, variant = tok.rsplit("#", 1)
|
||||
return {
|
||||
"token": tok,
|
||||
"name": name,
|
||||
"variant": int(variant),
|
||||
"id": rid,
|
||||
"covered_by": covered_by,
|
||||
"clone": False,
|
||||
"priority": False,
|
||||
}
|
||||
|
||||
|
||||
def snapshot(
|
||||
rows: list[dict],
|
||||
rounds: dict[str, dict],
|
||||
*,
|
||||
head: Iterable[dict],
|
||||
jobs: Iterable[str],
|
||||
budget: int = 208,
|
||||
pins: Iterable[dict] = (),
|
||||
counts: dict[str, int] | None = None,
|
||||
) -> dict:
|
||||
head_entries = list(head)
|
||||
return {
|
||||
"digest": "x",
|
||||
"seed": SEED,
|
||||
"budget": {"available": budget},
|
||||
"rows": rows,
|
||||
"rounds": rounds,
|
||||
"sweeps": {
|
||||
"0": {"entries": head_entries, "jobs": list(jobs), "head": head_entries}
|
||||
},
|
||||
"variant_counts": counts or {},
|
||||
"pins": list(pins),
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from cli.meta.ci.variant_split import compare
|
||||
|
||||
from . import edge, entry, record, row, snapshot
|
||||
|
||||
HEAVY = [edge("app", "a", "pa"), edge("app", "b", "pb"), edge("pa", "c", "pc")]
|
||||
|
||||
|
||||
def _before() -> dict:
|
||||
rows = [row("app#0", 1), row("other#0", 2)]
|
||||
rounds = {
|
||||
"app#0": record(["pa", "pb", "pc", "app"], HEAVY),
|
||||
"other#0": record(["other"], []),
|
||||
}
|
||||
return snapshot(
|
||||
rows,
|
||||
rounds,
|
||||
head=[entry("app#0"), entry("other#0")],
|
||||
jobs=["app#0", "other#0"],
|
||||
budget=2,
|
||||
)
|
||||
|
||||
|
||||
def _after(*, keep_c: bool = True, budget: int = 3, pin: dict | None = None) -> dict:
|
||||
rows = [row("app#0", 1), row("app#3", 2), row("other#0", 3)]
|
||||
split = [edge("app", "b", "pb")] + ([edge("pa", "c", "pc")] if keep_c else [])
|
||||
rounds = {
|
||||
"app#0": record(["pa", "app"], [edge("app", "a", "pa")]),
|
||||
"app#3": record(["pa", "pb", "pc", "app"], split, active={"app": 3}),
|
||||
"other#0": record(["other"], []),
|
||||
}
|
||||
tokens = ["app#0", "app#3", "other#0"][:budget]
|
||||
return snapshot(
|
||||
rows,
|
||||
rounds,
|
||||
head=[entry(t) for t in tokens],
|
||||
jobs=["app#0", "app#3", "other#0"],
|
||||
budget=budget,
|
||||
pins=[pin] if pin else [],
|
||||
)
|
||||
|
||||
|
||||
class TestVerdict(unittest.TestCase):
|
||||
def test_a_snapshot_against_itself_keeps_everything(self) -> None:
|
||||
self.assertTrue(
|
||||
compare.verdict(_before(), _before(), old=["app#0"], split=["app#0"])[
|
||||
"kept"
|
||||
]
|
||||
)
|
||||
|
||||
def test_a_split_that_carries_every_edge_inside_the_budget_is_kept(self) -> None:
|
||||
result = compare.verdict(
|
||||
_before(), _after(), old=["app#0"], split=["app#0", "app#3"]
|
||||
)
|
||||
self.assertEqual(result["edges"]["local"]["keys"], [])
|
||||
self.assertTrue(result["kept"], compare.render(result))
|
||||
|
||||
def test_negative_control_a_dep_edge_left_behind_is_reported(self) -> None:
|
||||
result = compare.verdict(
|
||||
_before(), _after(keep_c=False), old=["app#0"], split=["app#0", "app#3"]
|
||||
)
|
||||
lost = [("pa", "pc", frozenset({("c", "shared")}))]
|
||||
self.assertEqual(result["edges"]["head"]["keys"], lost)
|
||||
self.assertEqual(result["invariant"]["edges_lost"], lost)
|
||||
self.assertFalse(result["kept"])
|
||||
|
||||
def test_a_row_pushed_past_the_budget_stays_covered(self) -> None:
|
||||
result = compare.verdict(
|
||||
_before(), _after(budget=2), old=["app#0"], split=["app#0", "app#3"]
|
||||
)
|
||||
self.assertEqual(result["axes"]["per_sweep"]["0"]["head_lost"], ["other#0"])
|
||||
self.assertEqual(result["invariant"]["newly_uncovered"], [])
|
||||
self.assertTrue(result["kept"], compare.render(result))
|
||||
|
||||
def test_negative_control_one_false_credit_fails_the_invariant(self) -> None:
|
||||
after = _after()
|
||||
after["rows"].append(row("lone#0", 4, covered_by=1))
|
||||
result = compare.verdict(
|
||||
_before(), after, old=["app#0"], split=["app#0", "app#3"]
|
||||
)
|
||||
self.assertEqual(
|
||||
result["invariant"]["introduced_false_credits"],
|
||||
["lone#0: app#0 does not deploy lone"],
|
||||
)
|
||||
self.assertEqual(result["invariant"]["newly_uncovered"], ["lone#0"])
|
||||
self.assertFalse(result["kept"])
|
||||
|
||||
def test_negative_control_a_child_no_job_row_deploys_fails(self) -> None:
|
||||
after = _after()
|
||||
after["rows"].append({**row("app#5", 5), "clone": True})
|
||||
result = compare.verdict(
|
||||
_before(), after, old=["app#0"], split=["app#0", "app#3"]
|
||||
)
|
||||
self.assertEqual(result["invariant"]["newly_uncovered"], ["app#5"])
|
||||
self.assertFalse(result["kept"])
|
||||
|
||||
def test_a_credit_to_a_coverer_outside_the_job_list_is_false(self) -> None:
|
||||
after = _after()
|
||||
after["rows"].append(row("pb#0", 4, covered_by=2))
|
||||
after["sweeps"]["0"]["jobs"].remove("app#3")
|
||||
result = compare.verdict(
|
||||
_before(), after, old=["app#0"], split=["app#0", "app#3"]
|
||||
)
|
||||
self.assertEqual(
|
||||
result["invariant"]["introduced_false_credits"],
|
||||
["pb#0: app#3 is not in the job list"],
|
||||
)
|
||||
self.assertFalse(result["kept"])
|
||||
|
||||
def test_negative_control_a_new_pin_without_reciprocity_fails(self) -> None:
|
||||
pin = {
|
||||
"carrier": "app#3",
|
||||
"partner": "pa",
|
||||
"target": "1",
|
||||
"key": "a",
|
||||
"reciprocal": "error: no gate",
|
||||
}
|
||||
result = compare.verdict(
|
||||
_before(), _after(pin=pin), old=["app#0"], split=["app#0", "app#3"]
|
||||
)
|
||||
self.assertEqual(result["pins"]["unreciprocated"], [pin])
|
||||
self.assertFalse(result["kept"])
|
||||
|
||||
def test_a_reciprocal_new_pin_passes(self) -> None:
|
||||
pin = {
|
||||
"carrier": "app#3",
|
||||
"partner": "pa",
|
||||
"target": "1",
|
||||
"key": "a",
|
||||
"reciprocal": 1,
|
||||
}
|
||||
result = compare.verdict(
|
||||
_before(), _after(pin=pin), old=["app#0"], split=["app#0", "app#3"]
|
||||
)
|
||||
self.assertEqual(result["pins"]["unreciprocated"], [])
|
||||
|
||||
def test_the_render_names_the_verdict(self) -> None:
|
||||
text = compare.render(
|
||||
compare.verdict(
|
||||
_before(), _after(keep_c=False), old=["app#0"], split=["app#0", "app#3"]
|
||||
)
|
||||
)
|
||||
self.assertIn("coverage kept: NO", text)
|
||||
|
||||
|
||||
def _gate(
|
||||
*,
|
||||
jobs: list[str],
|
||||
big_include: list[str],
|
||||
dark: tuple[str, ...] = (),
|
||||
error: str | None = None,
|
||||
) -> dict:
|
||||
rows = [row("big#0", 1), row("dep#0", 2, covered_by=1), row("other#0", 3)]
|
||||
rounds = {
|
||||
"big#0": record(big_include),
|
||||
"dep#0": record(["dep"]),
|
||||
"other#0": record(["dep", "big", "other"], dark=dark, error=error),
|
||||
}
|
||||
return snapshot(rows, rounds, head=[entry(t) for t in jobs], jobs=jobs)
|
||||
|
||||
|
||||
def _gate_verdict(before: dict, after: dict) -> dict:
|
||||
return compare.verdict(before, after, old=["big#0"], split=["big#0"])
|
||||
|
||||
|
||||
class TestEachGateAlone(unittest.TestCase):
|
||||
def test_a_coverer_leaving_the_job_list_fails_on_the_invariant_alone(self) -> None:
|
||||
before = _gate(jobs=["big#0", "other#0"], big_include=["dep", "big"])
|
||||
after = _gate(jobs=["other#0"], big_include=["dep", "big"])
|
||||
result = _gate_verdict(before, after)
|
||||
self.assertEqual(
|
||||
result["invariant"]["introduced_false_credits"],
|
||||
["dep#0: big#0 is not in the job list"],
|
||||
)
|
||||
self.assertEqual(result["coverage"]["introduced"], [])
|
||||
self.assertFalse(result["kept"])
|
||||
|
||||
def test_a_coverer_dropping_the_role_fails_on_the_credit_check_alone(self) -> None:
|
||||
before = _gate(jobs=["other#0"], big_include=["dep", "big"])
|
||||
after = _gate(jobs=["other#0"], big_include=["big"])
|
||||
result = _gate_verdict(before, after)
|
||||
self.assertEqual(result["invariant"]["introduced_false_credits"], [])
|
||||
self.assertEqual(
|
||||
result["coverage"]["introduced"], ["dep#0: big#0 does not deploy dep"]
|
||||
)
|
||||
self.assertFalse(result["kept"])
|
||||
|
||||
def test_a_new_dark_pin_fails_alone(self) -> None:
|
||||
before = _gate(jobs=["big#0", "other#0"], big_include=["dep", "big"])
|
||||
after = _gate(
|
||||
jobs=["big#0", "other#0"],
|
||||
big_include=["dep", "big"],
|
||||
dark=("other#0 pins dep above k",),
|
||||
)
|
||||
result = _gate_verdict(before, after)
|
||||
self.assertEqual(
|
||||
result["pins"]["new_dark_pins"], ["other#0: other#0 pins dep above k"]
|
||||
)
|
||||
self.assertFalse(result["kept"])
|
||||
|
||||
def test_a_new_round_error_fails_alone(self) -> None:
|
||||
before = _gate(jobs=["big#0", "other#0"], big_include=["dep", "big"])
|
||||
after = _gate(
|
||||
jobs=["big#0", "other#0"], big_include=["dep", "big"], error="pins cycle"
|
||||
)
|
||||
result = _gate_verdict(before, after)
|
||||
self.assertEqual(result["pins"]["new_errors"], ["other#0: pins cycle"])
|
||||
self.assertFalse(result["kept"])
|
||||
|
||||
def test_the_gate_fixture_alone_keeps_everything(self) -> None:
|
||||
snap = _gate(jobs=["big#0", "other#0"], big_include=["dep", "big"])
|
||||
self.assertTrue(_gate_verdict(snap, snap)["kept"])
|
||||
|
||||
|
||||
def _moved(coverer: int) -> dict:
|
||||
rows = [
|
||||
row("app-a#0", 1),
|
||||
row("app-c#0", 3),
|
||||
row("app-r#0", 4, covered_by=coverer),
|
||||
]
|
||||
rounds = {
|
||||
"app-a#0": record(["app-a", "app-r"], active={"app-r": 1}),
|
||||
"app-c#0": record(["app-c"]),
|
||||
"app-r#0": record(["app-r"]),
|
||||
}
|
||||
jobs = ["app-a#0", "app-c#0", "app-r#0"]
|
||||
return snapshot(rows, rounds, head=[entry(t) for t in jobs], jobs=jobs)
|
||||
|
||||
|
||||
class TestFalseCreditIdentity(unittest.TestCase):
|
||||
def test_negative_control_a_false_credit_moved_to_another_coverer_is_new(
|
||||
self,
|
||||
) -> None:
|
||||
result = compare.verdict(
|
||||
_moved(1), _moved(3), old=["app-a#0"], split=["app-a#0"]
|
||||
)
|
||||
self.assertEqual(
|
||||
result["invariant"]["introduced_false_credits"],
|
||||
["app-r#0: app-c#0 does not deploy app-r"],
|
||||
)
|
||||
self.assertFalse(result["kept"])
|
||||
|
||||
def test_an_unchanged_false_credit_is_not_blamed_on_the_split(self) -> None:
|
||||
result = compare.verdict(
|
||||
_moved(1), _moved(1), old=["app-a#0"], split=["app-a#0"]
|
||||
)
|
||||
self.assertEqual(result["invariant"]["introduced_false_credits"], [])
|
||||
self.assertTrue(result["kept"])
|
||||
|
||||
|
||||
def _variant(other_edges: list, big_edges: list) -> dict:
|
||||
rows = [row("big#0", 1), row("dep#0", 2), row("other#0", 3)]
|
||||
rounds = {
|
||||
"big#0": record(["dep", "big"], big_edges),
|
||||
"dep#0": record(["dep"]),
|
||||
"other#0": record(
|
||||
["dep", "big", "other"],
|
||||
other_edges,
|
||||
active={"dep": other_edges[0][4] if other_edges else 0},
|
||||
),
|
||||
}
|
||||
jobs = ["other#0", "dep#0"]
|
||||
return snapshot(
|
||||
rows,
|
||||
rounds,
|
||||
head=[entry(t) for t in jobs],
|
||||
jobs=jobs,
|
||||
counts={"dep": 2},
|
||||
)
|
||||
|
||||
|
||||
class TestVariantEdges(unittest.TestCase):
|
||||
OWN = (edge("big", "k", "dep"),)
|
||||
|
||||
def test_negative_control_a_declared_edge_at_a_lost_variant_pair_fails(
|
||||
self,
|
||||
) -> None:
|
||||
before = _variant([edge("big", "k", "dep")], list(self.OWN))
|
||||
after = _variant([edge("big", "k", "dep", pv=1)], list(self.OWN))
|
||||
result = compare.verdict(before, after, old=["other#0"], split=["other#0"])
|
||||
self.assertEqual(result["invariant"]["edges_lost"], [])
|
||||
self.assertEqual(
|
||||
result["invariant"]["variant_edges_lost"],
|
||||
[["big", 0, "k", "dep", 0, "shared"]],
|
||||
)
|
||||
self.assertFalse(result["kept"])
|
||||
|
||||
def test_an_edge_the_consumer_no_longer_declares_is_retired(self) -> None:
|
||||
before = _variant([edge("big", "k", "dep")], list(self.OWN))
|
||||
after = _variant([], [])
|
||||
result = compare.verdict(before, after, old=["other#0"], split=["other#0"])
|
||||
self.assertEqual(result["invariant"]["variant_edges_lost"], [])
|
||||
self.assertEqual(result["invariant"]["variant_edges_retired"], 1)
|
||||
|
||||
|
||||
class TestEdgeCheckPerRound(unittest.TestCase):
|
||||
def test_keys_of_two_old_rounds_are_never_merged_into_one_identity(self) -> None:
|
||||
rows = [row("app#0", 1), row("app#1", 2)]
|
||||
rounds = {
|
||||
"app#0": record(["kc", "app"], [edge("app", "sso", "kc")]),
|
||||
"app#1": record(["kc", "app"], [edge("app", "oidc", "kc", cv=1)]),
|
||||
}
|
||||
snap = snapshot(rows, rounds, head=[], jobs=["app#0", "app#1"])
|
||||
result = compare.edge_check(
|
||||
snap, snap, old=["app#0", "app#1"], split=["app#0", "app#1"]
|
||||
)
|
||||
self.assertEqual(result["total"]["keys"], 2)
|
||||
self.assertEqual(result["local"]["keys"], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,72 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from cli.meta.ci.variant_split import cost
|
||||
|
||||
from . import entry, record, row, snapshot
|
||||
|
||||
SEGMENTS = {
|
||||
"passes": {"1": {"app": 100.0, "heavy": 900.0}, "2": {"app": 10.0, "heavy": 20.0}},
|
||||
"fixed": {
|
||||
"prep": 0,
|
||||
"container": 0,
|
||||
"backup": 0,
|
||||
"reset_post": 0,
|
||||
"infra_per_pass": 0,
|
||||
"dr_drill_variant0": 50,
|
||||
},
|
||||
"runner": "r1",
|
||||
}
|
||||
|
||||
|
||||
class TestRowCost(unittest.TestCase):
|
||||
def test_a_row_sums_its_apps_per_pass_plus_its_fixed_cost(self) -> None:
|
||||
seconds, unpriced = cost.row_cost(["app", "heavy"], 0, SEGMENTS)
|
||||
self.assertEqual(seconds, 50 + 110 + 920)
|
||||
self.assertEqual(unpriced, [])
|
||||
|
||||
def test_only_variant_0_pays_the_dr_drill(self) -> None:
|
||||
self.assertEqual(cost.row_cost(["app"], 3, SEGMENTS)[0], 110)
|
||||
|
||||
def test_negative_control_an_unmeasured_app_is_listed_not_hidden(self) -> None:
|
||||
seconds, unpriced = cost.row_cost(["app", "new"], 3, SEGMENTS)
|
||||
self.assertEqual(seconds, 110)
|
||||
self.assertEqual(unpriced, ["new"])
|
||||
|
||||
def test_the_default_fixed_cost_is_the_measured_per_row_overhead(self) -> None:
|
||||
seconds, _ = cost.row_cost([], 0, {"passes": {"1": {}, "2": {}}})
|
||||
self.assertEqual(seconds, 273 + 204 + 340 + 170 + 2 * 540 + 152)
|
||||
|
||||
|
||||
class TestDelta(unittest.TestCase):
|
||||
def test_a_split_reports_the_saving_and_the_added_runner_time(self) -> None:
|
||||
before = snapshot(
|
||||
[row("app#0", 1)],
|
||||
{"app#0": record(["heavy", "app"])},
|
||||
head=[entry("app#0")],
|
||||
jobs=["app#0"],
|
||||
)
|
||||
after = snapshot(
|
||||
[row("app#0", 1), row("app#3", 2)],
|
||||
{"app#0": record(["app"]), "app#3": record(["heavy", "app"])},
|
||||
head=[entry("app#0"), entry("app#3")],
|
||||
jobs=["app#0", "app#3"],
|
||||
)
|
||||
result = cost.delta(
|
||||
before, after, SEGMENTS, old=["app#0"], split=["app#0", "app#3"]
|
||||
)
|
||||
self.assertEqual(result["rows"]["app#0"]["saving"], 920)
|
||||
self.assertEqual(result["net"]["jobs"]["delta"], (160 + 1030) - 1080)
|
||||
self.assertIn("app#3", cost.render(result))
|
||||
|
||||
def test_the_render_names_the_runner_the_segments_came_from(self) -> None:
|
||||
snap = snapshot(
|
||||
[row("app#0", 1)], {"app#0": record(["app"])}, head=[], jobs=["app#0"]
|
||||
)
|
||||
result = cost.delta(snap, snap, SEGMENTS, old=["app#0"], split=["app#0"])
|
||||
self.assertIn("on runner r1", cost.render(result))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,111 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from cli.meta.ci.variant_split.coverage import children, credit_findings, declared
|
||||
from cli.meta.ci.variant_split.edges import Edge
|
||||
|
||||
from . import edge, record, row, snapshot
|
||||
|
||||
|
||||
def _snap(coverer_round: dict) -> dict:
|
||||
rows = [row("big#0", 1), row("dep#0", 2, covered_by=1)]
|
||||
rounds = {
|
||||
"big#0": coverer_round,
|
||||
"dep#0": record(["db", "dep"], [edge("dep", "db", "db")]),
|
||||
}
|
||||
return snapshot(rows, rounds, head=[], jobs=["big#0"])
|
||||
|
||||
|
||||
HONOURED = record(
|
||||
["db", "dep", "big"], [edge("dep", "db", "db"), edge("big", "dep", "dep")]
|
||||
)
|
||||
|
||||
|
||||
class TestCreditFindings(unittest.TestCase):
|
||||
def test_an_unchanged_honoured_credit_has_no_finding(self) -> None:
|
||||
found = credit_findings(_snap(HONOURED), _snap(HONOURED))
|
||||
self.assertEqual(
|
||||
found["introduced"] + found["thinner"] + found["preexisting"], []
|
||||
)
|
||||
|
||||
def test_negative_control_a_coverer_that_drops_the_role_is_a_false_credit(
|
||||
self,
|
||||
) -> None:
|
||||
after = _snap(record(["big"], []))
|
||||
found = credit_findings(_snap(HONOURED), after)
|
||||
self.assertEqual(found["introduced"], ["dep#0: big#0 does not deploy dep"])
|
||||
|
||||
def test_negative_control_a_pin_that_moves_the_role_off_variant_0_is_caught(
|
||||
self,
|
||||
) -> None:
|
||||
pinned = record(
|
||||
["db", "dep", "big"], [edge("dep", "db", "db", cv=2)], active={"dep": 2}
|
||||
)
|
||||
found = credit_findings(_snap(HONOURED), _snap(pinned))
|
||||
self.assertEqual(
|
||||
found["introduced"], ["dep#0: big#0 runs dep#2, not the credited #0"]
|
||||
)
|
||||
|
||||
def test_negative_control_a_coverer_that_switches_a_key_off_thins_the_credit(
|
||||
self,
|
||||
) -> None:
|
||||
lean = record(["db", "dep", "big"], [edge("big", "dep", "dep")])
|
||||
found = credit_findings(_snap(HONOURED), _snap(lean))
|
||||
self.assertEqual(len(found["thinner"]), 1)
|
||||
self.assertIn("db", found["thinner"][0])
|
||||
|
||||
def test_a_credit_that_was_already_false_stays_pre_existing(self) -> None:
|
||||
broken = _snap(record(["big"], []))
|
||||
found = credit_findings(broken, broken)
|
||||
self.assertEqual(found["introduced"], [])
|
||||
self.assertEqual(len(found["preexisting"]), 1)
|
||||
|
||||
def test_negative_control_a_credit_broken_another_way_is_introduced(self) -> None:
|
||||
dropped = _snap(record(["big"], []))
|
||||
pinned = _snap(record(["db", "dep", "big"], [], active={"dep": 2}))
|
||||
found = credit_findings(dropped, pinned)
|
||||
self.assertEqual(found["preexisting"], [])
|
||||
self.assertEqual(
|
||||
found["introduced"], ["dep#0: big#0 runs dep#2, not the credited #0"]
|
||||
)
|
||||
|
||||
def test_negative_control_a_coverer_that_dictates_the_roles_config_is_false(
|
||||
self,
|
||||
) -> None:
|
||||
dictated = record(
|
||||
["db", "dep", "big"], list(HONOURED["edges"]), dictated={"dep": "big#0"}
|
||||
)
|
||||
found = credit_findings(_snap(HONOURED), _snap(dictated))
|
||||
self.assertEqual(
|
||||
found["introduced"], ["dep#0: big#0 dictates the config of dep in big#0"]
|
||||
)
|
||||
|
||||
def test_a_dictated_member_does_not_cover_its_child(self) -> None:
|
||||
dictated = record(["db", "dep", "big"], dictated={"dep": "big#0"})
|
||||
self.assertIn("dep#0", children(_snap(dictated))["uncovered"])
|
||||
|
||||
def test_a_row_that_starts_running_itself_is_reported(self) -> None:
|
||||
after = _snap(HONOURED)
|
||||
after["rows"][1]["covered_by"] = 0
|
||||
self.assertEqual(
|
||||
credit_findings(_snap(HONOURED), after)["newly_uncovered"], ["dep#0"]
|
||||
)
|
||||
|
||||
|
||||
class TestDeclared(unittest.TestCase):
|
||||
EDGE = Edge("ghost", 1, "db", "db", 0, "shared")
|
||||
|
||||
def test_negative_control_an_edge_without_its_row_still_counts_as_declared(
|
||||
self,
|
||||
) -> None:
|
||||
snap = {"rounds": {}, "variant_counts": {"ghost": 2}}
|
||||
self.assertTrue(declared(snap, self.EDGE))
|
||||
|
||||
def test_an_edge_of_a_variant_the_role_no_longer_has_is_retired(self) -> None:
|
||||
snap = {"rounds": {}, "variant_counts": {"ghost": 1}}
|
||||
self.assertFalse(declared(snap, self.EDGE))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,128 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from cli.meta.ci.variant_split.edges import (
|
||||
Edge,
|
||||
identities,
|
||||
is_active,
|
||||
missing,
|
||||
round_edges,
|
||||
sharing,
|
||||
union,
|
||||
)
|
||||
|
||||
PROVIDERS = {"sso": "keycloak", "db": "postgres", "matrix": "matrix"}
|
||||
|
||||
|
||||
def _edges(maps, include, active=None, mcp=()):
|
||||
return round_edges(
|
||||
include=include,
|
||||
maps=maps,
|
||||
active_index=active or {},
|
||||
provider_of=PROVIDERS.get,
|
||||
mcp_pairs=mcp,
|
||||
)
|
||||
|
||||
|
||||
class TestActivity(unittest.TestCase):
|
||||
def test_a_literal_false_or_empty_flag_is_off(self) -> None:
|
||||
self.assertFalse(is_active({"enabled": False}))
|
||||
self.assertFalse(is_active({"enabled": "false"}))
|
||||
self.assertFalse(is_active({"enabled": ""}))
|
||||
self.assertFalse(is_active("not a mapping"))
|
||||
|
||||
def test_a_presence_gate_or_a_missing_flag_counts_as_on(self) -> None:
|
||||
self.assertTrue(is_active({"enabled": "{{ 'x' in group_names }}"}))
|
||||
self.assertTrue(is_active({"shared": True}))
|
||||
|
||||
def test_sharing_is_normalised(self) -> None:
|
||||
self.assertEqual(sharing({"shared": True}), "shared")
|
||||
self.assertEqual(sharing({"shared": False}), "dedicated")
|
||||
self.assertEqual(sharing({"enabled": True}), "unset")
|
||||
|
||||
|
||||
class TestRoundEdges(unittest.TestCase):
|
||||
def test_only_active_keys_to_deployed_providers_become_edges(self) -> None:
|
||||
maps = {
|
||||
"app": {
|
||||
"sso": {"enabled": True, "shared": True},
|
||||
"db": {"enabled": False},
|
||||
"matrix": {"enabled": True, "shared": True},
|
||||
}
|
||||
}
|
||||
edges = _edges(maps, ["app", "keycloak", "postgres"])
|
||||
self.assertEqual(edges, {Edge("app", 0, "sso", "keycloak", 0, "shared")})
|
||||
|
||||
def test_mcp_pairs_count_only_when_both_ends_are_deployed(self) -> None:
|
||||
edges = _edges(
|
||||
{}, ["client", "server"], mcp=[("client", "server"), ("client", "gone")]
|
||||
)
|
||||
self.assertEqual(
|
||||
{(e.consumer, e.key, e.provider) for e in edges},
|
||||
{("client", "mcp", "server")},
|
||||
)
|
||||
|
||||
|
||||
OLD = frozenset(
|
||||
{
|
||||
Edge("app", 0, "sso", "keycloak", 0, "shared"),
|
||||
Edge("app", 0, "db", "postgres", 0, "shared"),
|
||||
}
|
||||
)
|
||||
OIDC = Edge("app", 0, "oidc", "keycloak", 0, "shared")
|
||||
|
||||
|
||||
class TestMissing(unittest.TestCase):
|
||||
def test_a_carrier_with_the_same_edges_leaves_nothing_missing(self) -> None:
|
||||
self.assertEqual(missing([OLD], [OLD], "strict"), set())
|
||||
|
||||
def test_negative_control_an_extra_key_breaks_the_keys_level_only(self) -> None:
|
||||
carrier = OLD | {OIDC}
|
||||
self.assertEqual(missing([OLD], [carrier], "pair"), set())
|
||||
self.assertEqual(
|
||||
missing([OLD], [carrier], "keys"),
|
||||
{("app", "keycloak", frozenset({("sso", "shared")}))},
|
||||
)
|
||||
|
||||
def test_negative_control_a_moved_variant_breaks_the_strict_level_only(
|
||||
self,
|
||||
) -> None:
|
||||
carrier = {
|
||||
Edge(c, cv, k, p, 2 if p == "postgres" else pv, s)
|
||||
for c, cv, k, p, pv, s in OLD
|
||||
}
|
||||
self.assertEqual(missing([OLD], [carrier], "keys"), set())
|
||||
self.assertEqual(len(missing([OLD], [carrier], "strict")), 1)
|
||||
|
||||
def test_edges_split_over_two_carriers_are_all_held(self) -> None:
|
||||
first, second = sorted(OLD)
|
||||
self.assertEqual(missing([OLD], [{first}, {second}], "keys"), set())
|
||||
|
||||
def test_negative_control_a_carrier_missing_one_edge_leaves_it_missing(
|
||||
self,
|
||||
) -> None:
|
||||
first, _second = sorted(OLD)
|
||||
self.assertEqual(len(missing([OLD], [{first}], "keys")), 1)
|
||||
|
||||
def test_two_old_rounds_keep_their_key_sets_apart(self) -> None:
|
||||
sso = {e for e in OLD if e.key == "sso"}
|
||||
self.assertEqual(missing([sso, {OIDC}], [sso, {OIDC}], "keys"), set())
|
||||
|
||||
def test_the_union_collapses_each_round_on_its_own(self) -> None:
|
||||
sso = {e for e in OLD if e.key == "sso"}
|
||||
self.assertEqual(
|
||||
union([sso, {OIDC}], "keys"),
|
||||
{
|
||||
("app", "keycloak", frozenset({("sso", "shared")})),
|
||||
("app", "keycloak", frozenset({("oidc", "shared")})),
|
||||
},
|
||||
)
|
||||
|
||||
def test_an_unknown_level_is_rejected(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
identities(OLD, "loose")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,171 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from cli.meta.ci.variant_split import __main__ as cli
|
||||
from cli.meta.ci.variant_split import snapshot as snapshot_module
|
||||
from utils.cache.files import read_text
|
||||
|
||||
from . import entry, record, row, snapshot
|
||||
|
||||
LOG = (
|
||||
"2026-11-06T10:00:00.0Z TASK [prepare the host] ***\n"
|
||||
"2026-11-06T10:00:10.0Z TASK [web-app-a : first] ***\n"
|
||||
"2026-11-06T10:01:00.0Z TASK [web-app-b : first] ***\n"
|
||||
"2026-11-06T10:02:00.0Z TASK [test-e2e-playwright : run] ***\n"
|
||||
)
|
||||
|
||||
|
||||
def _snap(*, with_b: bool = True, seed: str | None = None) -> dict:
|
||||
include = ["web-app-b", "web-app-a"] if with_b else ["web-app-a"]
|
||||
snap = snapshot(
|
||||
[row("web-app-a#0", 1), row("web-app-b#0", 2)],
|
||||
{"web-app-a#0": record(include), "web-app-b#0": record(["web-app-b"])},
|
||||
head=[entry("web-app-a#0")],
|
||||
jobs=["web-app-a#0"],
|
||||
)
|
||||
if seed is not None:
|
||||
snap["seed"] = seed
|
||||
return snap
|
||||
|
||||
|
||||
def _json(path: str | Path) -> dict:
|
||||
return json.loads(read_text(str(path)))
|
||||
|
||||
|
||||
class TestMain(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.tmp = Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
|
||||
def _write(self, name: str, data: dict) -> str:
|
||||
path = self.tmp / name
|
||||
path.write_text(json.dumps(data))
|
||||
return str(path)
|
||||
|
||||
def _run(self, *argv: str) -> tuple[int, str, str]:
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with redirect_stdout(out), redirect_stderr(err):
|
||||
rc = cli.main(list(argv))
|
||||
return rc, out.getvalue(), err.getvalue()
|
||||
|
||||
def _compare(self, before: dict, after: dict) -> tuple[int, str, str]:
|
||||
return self._run(
|
||||
"compare",
|
||||
self._write("before.json", before),
|
||||
self._write("after.json", after),
|
||||
"--old",
|
||||
"web-app-a#0",
|
||||
"--split",
|
||||
"web-app-a#0",
|
||||
)
|
||||
|
||||
def test_compare_of_a_snapshot_with_itself_exits_0(self) -> None:
|
||||
rc, out, _ = self._compare(_snap(), _snap())
|
||||
self.assertEqual((rc, out.splitlines()[0]), (0, "coverage kept: yes"))
|
||||
|
||||
def test_negative_control_compare_exits_1_when_coverage_is_lost(self) -> None:
|
||||
rc, out, _ = self._compare(_snap(), _snap(with_b=False))
|
||||
self.assertEqual((rc, out.splitlines()[0]), (1, "coverage kept: NO"))
|
||||
|
||||
def test_negative_control_compare_refuses_snapshots_of_two_seeds(self) -> None:
|
||||
rc, _, err = self._compare(_snap(), _snap(seed="7"))
|
||||
self.assertEqual(rc, 2)
|
||||
self.assertIn("must be one run id", err)
|
||||
|
||||
def test_compare_writes_the_verdict_when_asked(self) -> None:
|
||||
out_path = self.tmp / "verdict.json"
|
||||
self._run(
|
||||
"compare",
|
||||
self._write("before.json", _snap()),
|
||||
self._write("after.json", _snap()),
|
||||
"--old",
|
||||
"web-app-a#0",
|
||||
"--split",
|
||||
"web-app-a#0",
|
||||
"--out",
|
||||
str(out_path),
|
||||
)
|
||||
self.assertTrue(_json(out_path)["kept"])
|
||||
|
||||
def test_snapshot_passes_the_seed_and_records_it(self) -> None:
|
||||
out_path = self.tmp / "snap.json"
|
||||
with mock.patch.object(
|
||||
snapshot_module, "take", return_value=_snap(seed="42")
|
||||
) as take:
|
||||
rc, _, _ = self._run(
|
||||
"snapshot", "--out", str(out_path), "--seed", "42", "--sweeps", "0,1"
|
||||
)
|
||||
take.assert_called_once_with([0, 1], seed="42")
|
||||
self.assertEqual((rc, _json(out_path)["seed"]), (0, "42"))
|
||||
|
||||
def test_negative_control_snapshot_without_a_seed_is_a_usage_error(self) -> None:
|
||||
with self.assertRaises(SystemExit), redirect_stderr(io.StringIO()):
|
||||
cli.main(["snapshot", "--out", str(self.tmp / "snap.json")])
|
||||
|
||||
def _segments(self, runner: str, name: str) -> str:
|
||||
out_path = self.tmp / name
|
||||
self._run(
|
||||
"segments",
|
||||
self._write("snap.json", _snap()),
|
||||
"--row",
|
||||
"web-app-a#0",
|
||||
"--runner",
|
||||
runner,
|
||||
"--pass",
|
||||
"1=1:",
|
||||
"--log",
|
||||
str(self._log()),
|
||||
"--out",
|
||||
str(out_path),
|
||||
)
|
||||
return str(out_path)
|
||||
|
||||
def _log(self) -> Path:
|
||||
path = self.tmp / "deploy.log"
|
||||
path.write_text(LOG)
|
||||
return path
|
||||
|
||||
def test_segments_from_a_log_record_the_runner_and_the_seen_apps(self) -> None:
|
||||
data = _json(self._segments("fast", "seg.json"))
|
||||
self.assertEqual(data["runner"], "fast")
|
||||
self.assertEqual(data["passes"]["1"], {"web-app-a": 50.0, "web-app-b": 60.0})
|
||||
|
||||
def test_negative_control_merge_of_two_runners_fails(self) -> None:
|
||||
fast = self._segments("fast", "fast.json")
|
||||
slow = self._segments("slow", "slow.json")
|
||||
rc, _, err = self._run("merge", fast, slow, "--out", str(self.tmp / "m.json"))
|
||||
self.assertEqual(rc, 2)
|
||||
self.assertIn("cannot be merged", err)
|
||||
|
||||
def test_merge_of_one_runner_writes_the_joined_file(self) -> None:
|
||||
first = self._segments("fast", "a.json")
|
||||
second = self._segments("fast", "b.json")
|
||||
merged = self.tmp / "m.json"
|
||||
rc, _, _ = self._run("merge", first, second, "--out", str(merged))
|
||||
self.assertEqual((rc, _json(merged)["runner"]), (0, "fast"))
|
||||
|
||||
def test_cost_prints_the_saving_per_row(self) -> None:
|
||||
seg = self._segments("fast", "seg.json")
|
||||
rc, out, _ = self._run(
|
||||
"cost",
|
||||
self._write("before.json", _snap()),
|
||||
self._write("after.json", _snap(with_b=False)),
|
||||
"--segments",
|
||||
seg,
|
||||
"--old",
|
||||
"web-app-a#0",
|
||||
"--split",
|
||||
"web-app-a#0",
|
||||
)
|
||||
self.assertEqual(rc, 0)
|
||||
self.assertIn("web-app-a#0: ", out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,113 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from cli.meta.ci.variant_split import rounds
|
||||
from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_VARIANTS
|
||||
|
||||
CARRIER = """\
|
||||
- services:
|
||||
# variant-pin: web-app-b#TARGET
|
||||
b:
|
||||
enabled: true
|
||||
shared: true
|
||||
"""
|
||||
PARTNER = """\
|
||||
a:
|
||||
enabled: "{{ 'web-app-a' in group_names }}"
|
||||
shared: "{{ 'web-app-a' in group_names }}"
|
||||
"""
|
||||
|
||||
|
||||
def _tree(tmp: str, target: str, gate: bool = True) -> str:
|
||||
root = Path(tmp)
|
||||
(root / "web-app-a" / "meta").mkdir(parents=True)
|
||||
(root / "web-app-b" / "meta").mkdir(parents=True)
|
||||
(root / "web-app-a" / ROLE_FILE_META_VARIANTS).write_text(
|
||||
CARRIER.replace("TARGET", target)
|
||||
)
|
||||
(root / "web-app-b" / ROLE_FILE_META_SERVICES).write_text(
|
||||
PARTNER if gate else "c: {}\n"
|
||||
)
|
||||
return tmp
|
||||
|
||||
|
||||
VARIANTS = {
|
||||
"web-app-b": [
|
||||
{"services": {"a": {"enabled": False}}},
|
||||
{"services": {"a": {"enabled": True}}},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
class TestPins(unittest.TestCase):
|
||||
def test_a_pin_is_read_with_the_key_it_stands_above(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
self.assertEqual(
|
||||
rounds.pinned_keys("web-app-a", _tree(tmp, "1")),
|
||||
{0: {"web-app-b": ("1", "b")}},
|
||||
)
|
||||
|
||||
def test_a_reciprocating_pin_names_its_partner_variant(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
[finding] = rounds.pin_findings(
|
||||
"web-app-a", roles_dir=_tree(tmp, "1"), variants_per_app=VARIANTS
|
||||
)
|
||||
self.assertEqual((finding["target"], finding["reciprocal"]), ("1", 1))
|
||||
|
||||
def test_negative_control_a_pin_at_the_wrong_index_is_visible(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
[finding] = rounds.pin_findings(
|
||||
"web-app-a", roles_dir=_tree(tmp, "0"), variants_per_app=VARIANTS
|
||||
)
|
||||
self.assertEqual((finding["target"], finding["reciprocal"]), ("0", 1))
|
||||
|
||||
def test_negative_control_a_partner_without_a_back_gate_cannot_reciprocate(
|
||||
self,
|
||||
) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
[finding] = rounds.pin_findings(
|
||||
"web-app-a",
|
||||
roles_dir=_tree(tmp, "1", gate=False),
|
||||
variants_per_app=VARIANTS,
|
||||
)
|
||||
self.assertTrue(str(finding["reciprocal"]).startswith("error:"))
|
||||
|
||||
|
||||
class TestToken(unittest.TestCase):
|
||||
def test_a_whole_role_row_is_variant_0(self) -> None:
|
||||
self.assertEqual(rounds.token("web-app-a", None), "web-app-a#0")
|
||||
|
||||
def test_a_variant_row_keeps_its_index(self) -> None:
|
||||
self.assertEqual(rounds.token("web-app-a", 3), "web-app-a#3")
|
||||
|
||||
|
||||
class TestDictated(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
rounds._dictating.cache_clear()
|
||||
self.addCleanup(rounds._dictating.cache_clear)
|
||||
|
||||
def _dictated(self, include: list[str], active: dict[str, int]) -> dict:
|
||||
found = {("web-app-a", 1): {"web-app-b", "web-app-gone"}}
|
||||
with mock.patch.object(rounds, "overridden_providers", return_value=found):
|
||||
return rounds.dictated(include, active, roles_dir="/roles")
|
||||
|
||||
def test_a_member_whose_config_a_variant_dictates_names_that_variant(
|
||||
self,
|
||||
) -> None:
|
||||
found = self._dictated(["web-app-b", "web-app-a"], {"web-app-a": 1})
|
||||
self.assertEqual(found, {"web-app-b": "web-app-a#1"})
|
||||
|
||||
def test_negative_control_another_variant_of_the_carrier_dictates_nothing(
|
||||
self,
|
||||
) -> None:
|
||||
self.assertEqual(
|
||||
self._dictated(["web-app-b", "web-app-a"], {"web-app-a": 0}), {}
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,131 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from cli.meta.ci.variant_split import segments
|
||||
|
||||
TSV = (
|
||||
"500\t0\tTOTAL\n"
|
||||
"100\t1\tweb-app-a : own task\n"
|
||||
"40\t1\tsys-svc-compose : Ensure instance dir for 'web-app-b' is up\n"
|
||||
"30\t1\tsys-svc-compose : Render /opt/compose/b/compose.yml\n"
|
||||
"60\t3\tsys-svc-compose : swarm: wait until stack tasks converge\n"
|
||||
"20\t1\tsetup roles in run_after order\n"
|
||||
"10\t1\tsys-x : touches 'web-app-a' and 'web-app-b'"
|
||||
)
|
||||
LOG = [
|
||||
"2026-11-06T10:00:00.0Z TASK [prepare the host] ***",
|
||||
"2026-11-06T10:00:10.0Z TASK [web-app-a : first] ***",
|
||||
"secret=hunter2 must never surface",
|
||||
"2026-11-06T10:00:40.0Z TASK [sys-svc-compose : helper for b] ***",
|
||||
"2026-11-06T10:01:00.0Z TASK [web-app-b : first] ***",
|
||||
"2026-11-06T10:01:05.5Z RUNNING HANDLER [web-app-a : late handler] ***",
|
||||
"2026-11-06T10:02:00.0Z TASK [test-e2e-playwright : run] ***",
|
||||
"2026-11-06T10:05:00.0Z TASK [test-e2e-playwright : collect] ***",
|
||||
]
|
||||
APPS = ["web-app-a", "web-app-b", "web-app-c"]
|
||||
|
||||
|
||||
def _entity(app: str) -> str:
|
||||
return app.rsplit("-", 1)[1]
|
||||
|
||||
|
||||
def _file(runner: str, passes: dict, source: str = "s", cut: bool = False) -> dict:
|
||||
return {"source": source, "runner": runner, "lower_bound": cut, "passes": passes}
|
||||
|
||||
|
||||
class TestSegments(unittest.TestCase):
|
||||
def test_parse_skips_the_total_line(self) -> None:
|
||||
self.assertEqual(len(segments.parse_tsv(TSV)), 6)
|
||||
|
||||
def test_tasks_are_attributed_by_prefix_mention_spread_or_fixed(self) -> None:
|
||||
result = segments.attribute(segments.parse_tsv(TSV), APPS, entity_of=_entity)
|
||||
self.assertEqual(
|
||||
result["apps"], {"web-app-a": 125.0, "web-app-b": 95.0, "web-app-c": 20.0}
|
||||
)
|
||||
self.assertEqual(result["fixed"], 20.0)
|
||||
self.assertEqual(result["total"], 260.0)
|
||||
|
||||
def test_negative_control_another_apps_task_never_lands_on_this_app(self) -> None:
|
||||
result = segments.attribute(
|
||||
segments.parse_tsv(TSV), ["web-app-c"], entity_of=_entity
|
||||
)
|
||||
self.assertEqual(result["apps"], {"web-app-c": 60.0})
|
||||
self.assertEqual(result["fixed"], 200.0)
|
||||
|
||||
def test_an_app_no_task_reaches_stays_unpriced_in_a_tsv(self) -> None:
|
||||
tasks = segments.parse_tsv("100\t1\tweb-app-a : own task")
|
||||
result = segments.attribute(
|
||||
tasks, ["web-app-a", "web-app-z"], entity_of=_entity
|
||||
)
|
||||
self.assertEqual(result["apps"], {"web-app-a": 100.0})
|
||||
|
||||
def test_a_log_pass_is_cut_at_each_apps_first_task(self) -> None:
|
||||
result = segments.first_task_segments(LOG, APPS)
|
||||
self.assertEqual(result["apps"], {"web-app-a": 50.0, "web-app-b": 60.0})
|
||||
|
||||
def test_a_log_pass_splits_fixed_app_and_e2e_time(self) -> None:
|
||||
result = segments.first_task_segments(LOG, APPS)
|
||||
self.assertEqual(
|
||||
(result["fixed"], result["e2e"], result["total"]), (10.0, 180.0, 300.0)
|
||||
)
|
||||
|
||||
def test_negative_control_an_app_the_pass_never_reached_is_not_priced_at_zero(
|
||||
self,
|
||||
) -> None:
|
||||
result = segments.first_task_segments(LOG, APPS)
|
||||
self.assertNotIn("web-app-c", result["apps"])
|
||||
self.assertEqual(result["unseen"], ["web-app-c"])
|
||||
|
||||
def test_no_log_text_leaves_the_segments(self) -> None:
|
||||
self.assertNotIn("hunter2", repr(segments.first_task_segments(LOG, APPS)))
|
||||
|
||||
def test_negative_control_a_log_without_headers_prices_nothing(self) -> None:
|
||||
result = segments.first_task_segments(["no header here"], ["web-app-a"])
|
||||
self.assertEqual((result["apps"], result["total"]), ({}, 0.0))
|
||||
self.assertEqual(result["unseen"], ["web-app-a"])
|
||||
|
||||
def test_a_cut_pass_marks_the_file_a_lower_bound(self) -> None:
|
||||
data = segments.build(
|
||||
{"1": TSV, "2": TSV},
|
||||
["web-app-a"],
|
||||
entity_of=_entity,
|
||||
runner="r1",
|
||||
cut=["2"],
|
||||
source="run 1",
|
||||
)
|
||||
self.assertTrue(data["lower_bound"])
|
||||
self.assertIn("lower bound", data["source"])
|
||||
|
||||
def test_a_file_names_its_runner(self) -> None:
|
||||
data = segments.build_from_log(LOG, {"1": (1, None)}, APPS, runner="r1")
|
||||
self.assertEqual(data["runner"], "r1")
|
||||
|
||||
|
||||
class TestMerge(unittest.TestCase):
|
||||
def test_a_later_file_prices_only_the_gaps_of_its_runner(self) -> None:
|
||||
merged = segments.merge(
|
||||
[
|
||||
_file("r1", {"2": {"web-app-a": 10.0}}),
|
||||
_file("r1", {"2": {"web-app-a": 99.0, "web-app-b": 20.0}}),
|
||||
]
|
||||
)
|
||||
self.assertEqual(
|
||||
merged["passes"], {"2": {"web-app-a": 10.0, "web-app-b": 20.0}}
|
||||
)
|
||||
|
||||
def test_negative_control_files_of_two_runners_are_never_mixed(self) -> None:
|
||||
with self.assertRaisesRegex(ValueError, "cannot be merged"):
|
||||
segments.merge([_file("fast", {}), _file("slow", {})])
|
||||
|
||||
def test_a_lower_bound_file_makes_the_merge_a_lower_bound(self) -> None:
|
||||
merged = segments.merge([_file("r1", {}), _file("r1", {}, cut=True)])
|
||||
self.assertTrue(merged["lower_bound"])
|
||||
|
||||
def test_nothing_to_merge_is_refused(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
segments.merge([])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,120 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from cli.meta.ci.variant_split import snapshot
|
||||
from utils.roles.mapping import ROLE_FILE_META_VARIANTS
|
||||
|
||||
|
||||
def _candidates() -> list[dict]:
|
||||
return [
|
||||
{"name": "app", "variant": 0, "id": 1, "covered_by": 0, "clone": False},
|
||||
{"name": "dep", "variant": None, "id": 2, "covered_by": 1, "clone": False},
|
||||
]
|
||||
|
||||
|
||||
def _assign(rows: list, sweep: int) -> list[dict]:
|
||||
return [
|
||||
{
|
||||
"apps": r["name"],
|
||||
"variant": "" if r["variant"] is None else str(r["variant"]),
|
||||
"mode": "compose" if (i + sweep) % 2 == 0 else "swarm",
|
||||
"priority": "false",
|
||||
"covered": str(r["covered_by"]),
|
||||
"clone": "false",
|
||||
"id": str(r["id"]),
|
||||
}
|
||||
for i, r in enumerate(rows)
|
||||
]
|
||||
|
||||
|
||||
class TestAssemble(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.resolved = []
|
||||
self.snap = snapshot.assemble(
|
||||
candidates=_candidates(),
|
||||
sweeps=[0, 1],
|
||||
assign=_assign,
|
||||
head_of=lambda entries: entries[:1],
|
||||
is_regular=lambda e: e["covered"] == "0",
|
||||
resolve=lambda name, variant: (
|
||||
self.resolved.append((name, variant)) or {"include": [name]}
|
||||
),
|
||||
budget={"available": 1},
|
||||
variant_counts={"app": 1},
|
||||
pins=[],
|
||||
digest="d",
|
||||
seed="42",
|
||||
)
|
||||
|
||||
def test_every_candidate_is_resolved_once(self) -> None:
|
||||
self.assertEqual(self.resolved, [("app", 0), ("dep", None)])
|
||||
self.assertEqual(sorted(self.snap["rounds"]), ["app#0", "dep#0"])
|
||||
|
||||
def test_each_sweep_keeps_its_own_rotation_head(self) -> None:
|
||||
self.assertEqual(self.snap["sweeps"]["0"]["head"][0]["mode"], "compose")
|
||||
self.assertEqual(self.snap["sweeps"]["1"]["head"][0]["mode"], "swarm")
|
||||
|
||||
def test_the_job_list_keeps_only_regular_entries(self) -> None:
|
||||
self.assertEqual(self.snap["sweeps"]["0"]["jobs"], ["app#0"])
|
||||
|
||||
def test_rows_keep_their_coverage_credit(self) -> None:
|
||||
self.assertEqual(self.snap["rows"][1]["covered_by"], 1)
|
||||
|
||||
def test_the_snapshot_records_its_seed(self) -> None:
|
||||
self.assertEqual(self.snap["seed"], "42")
|
||||
|
||||
|
||||
class TestSeeds(unittest.TestCase):
|
||||
def test_two_snapshots_of_one_run_id_share_it(self) -> None:
|
||||
self.assertEqual(snapshot.check_seeds({"seed": "7"}, {"seed": "7"}), "7")
|
||||
|
||||
def test_negative_control_different_seeds_are_refused(self) -> None:
|
||||
with self.assertRaisesRegex(ValueError, "must be one run id"):
|
||||
snapshot.check_seeds({"seed": "7"}, {"seed": "8"})
|
||||
|
||||
def test_negative_control_an_unseeded_snapshot_is_refused(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
snapshot.check_seeds({}, {})
|
||||
|
||||
def test_an_empty_seed_never_takes_a_snapshot(self) -> None:
|
||||
with (
|
||||
mock.patch.object(snapshot, "pipeline") as pipeline,
|
||||
self.assertRaises(ValueError),
|
||||
):
|
||||
snapshot.take([0], seed=" ")
|
||||
pipeline.assert_not_called()
|
||||
|
||||
def test_the_seed_is_exported_before_the_pipeline_ranks(self) -> None:
|
||||
seen = []
|
||||
|
||||
def pipeline() -> dict:
|
||||
seen.append(os.environ[snapshot.SEED_ENV])
|
||||
raise RuntimeError
|
||||
|
||||
with (
|
||||
mock.patch.dict(os.environ, {}),
|
||||
mock.patch.object(snapshot, "pipeline", pipeline),
|
||||
self.assertRaises(RuntimeError),
|
||||
):
|
||||
snapshot.take([0], seed="42305502796")
|
||||
self.assertEqual(seen, ["42305502796"])
|
||||
|
||||
|
||||
class TestDigest(unittest.TestCase):
|
||||
def test_negative_control_an_edited_variants_file_changes_the_digest(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "role" / ROLE_FILE_META_VARIANTS
|
||||
path.parent.mkdir(parents=True)
|
||||
path.write_text("- {}\n")
|
||||
first = snapshot.variants_digest(tmp)
|
||||
path.write_text("- {}\n- {}\n")
|
||||
self.assertNotEqual(first, snapshot.variants_digest(tmp))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Whitespace-only changes.
@@ -0,0 +1,81 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import unittest
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from unittest import mock
|
||||
|
||||
from cli.meta.ci.variant_tree import __main__ as cli
|
||||
from cli.meta.ci.variant_tree import tree
|
||||
|
||||
FOUR = {"web-app-a": [{}, {}, {}, {}]}
|
||||
BUILT = {
|
||||
"primary": "web-app-a#1",
|
||||
"round_index": 1,
|
||||
"include_count": 1,
|
||||
"error": None,
|
||||
"nodes": [
|
||||
{
|
||||
"role": "web-app-a",
|
||||
"variant": 1,
|
||||
"variants": 4,
|
||||
"reason": "primary",
|
||||
"services": [],
|
||||
"children": [],
|
||||
}
|
||||
],
|
||||
}
|
||||
AXES = {"0": {"entries": [], "job_position": 3, "in_budget_head": True, "covered": "0"}}
|
||||
|
||||
|
||||
class TestMain(unittest.TestCase):
|
||||
def _run(
|
||||
self, *argv: str, built: dict | None = None
|
||||
) -> tuple[int, str, str, mock.Mock]:
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with (
|
||||
mock.patch("utils.cache.applications.get_variants", return_value=FOUR),
|
||||
mock.patch.object(tree, "build", wraps=tree.build) as build,
|
||||
mock.patch(
|
||||
"cli.meta.ci.variant_split.snapshot.row_axes", return_value=AXES
|
||||
) as axes,
|
||||
redirect_stdout(out),
|
||||
redirect_stderr(err),
|
||||
):
|
||||
if built is not None:
|
||||
build.side_effect = None
|
||||
build.return_value = built
|
||||
rc = cli.main(list(argv))
|
||||
return rc, out.getvalue(), err.getvalue(), axes
|
||||
|
||||
def test_negative_control_a_variant_past_the_last_fails_naming_the_range(
|
||||
self,
|
||||
) -> None:
|
||||
rc, out, err, _ = self._run("web-app-a#9")
|
||||
self.assertEqual((rc, out), (2, ""))
|
||||
self.assertIn("must be 0..3", err)
|
||||
|
||||
def test_the_json_form_carries_the_axes_of_each_sweep(self) -> None:
|
||||
rc, out, _, _ = self._run("web-app-a#1", "--json", built=dict(BUILT))
|
||||
self.assertEqual((rc, json.loads(out)["axes"]), (0, AXES))
|
||||
|
||||
def test_an_empty_sweep_list_skips_the_axes(self) -> None:
|
||||
_, _, _, axes = self._run("web-app-a#1", "--sweeps", "", built=dict(BUILT))
|
||||
axes.assert_not_called()
|
||||
|
||||
def test_the_text_form_leads_with_the_row(self) -> None:
|
||||
rc, out, _, _ = self._run("web-app-a#1", built=dict(BUILT))
|
||||
self.assertEqual(rc, 0)
|
||||
self.assertTrue(out.startswith("web-app-a#1: include 1"))
|
||||
|
||||
def test_negative_control_a_pin_error_exits_1(self) -> None:
|
||||
failed = {**BUILT, "error": "pins cycle", "nodes": []}
|
||||
rc, out, _, axes = self._run("web-app-a#1", built=failed)
|
||||
self.assertEqual(rc, 1)
|
||||
self.assertIn("error: pins cycle", out)
|
||||
axes.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,117 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from cli.meta.ci.variant_tree import tree
|
||||
|
||||
PINNED = {"b": "a#0"}
|
||||
GATE = "{{ 'x' in group_names }}"
|
||||
TREE = {
|
||||
"primary": "a#0",
|
||||
"round_index": 0,
|
||||
"include_count": 2,
|
||||
"error": None,
|
||||
"nodes": [
|
||||
{
|
||||
"role": "b",
|
||||
"variant": 1,
|
||||
"variants": 2,
|
||||
"reason": "pin by a#0",
|
||||
"services": [],
|
||||
"children": [],
|
||||
},
|
||||
{
|
||||
"role": "a",
|
||||
"variant": 0,
|
||||
"variants": 1,
|
||||
"reason": "primary",
|
||||
"services": [
|
||||
{"key": "k", "provider": "b", "state": "required", "deployed": True}
|
||||
],
|
||||
"children": ["b"],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _reason(role: str, index: int, count: int) -> str:
|
||||
return tree.reason(role, primary="a", index=index, count=count, pinned=PINNED)
|
||||
|
||||
|
||||
class TestReason(unittest.TestCase):
|
||||
def test_the_primary_is_named_first(self) -> None:
|
||||
self.assertEqual(_reason("a", 0, 3), "primary")
|
||||
|
||||
def test_a_pin_in_force_names_its_carrier(self) -> None:
|
||||
self.assertEqual(_reason("b", 0, 3), "pin by a#0")
|
||||
|
||||
def test_a_role_with_that_many_variants_follows_the_round_index(self) -> None:
|
||||
self.assertEqual(_reason("c", 2, 3), "round index")
|
||||
|
||||
def test_a_round_past_the_roles_variants_falls_back_to_0(self) -> None:
|
||||
self.assertEqual(_reason("c", 5, 3), "default 0: round past its variants")
|
||||
|
||||
def test_a_single_variant_role_past_round_0_falls_back_to_0(self) -> None:
|
||||
self.assertEqual(_reason("d", 1, 1), "default 0: round past its variants")
|
||||
|
||||
|
||||
class TestState(unittest.TestCase):
|
||||
def test_a_literal_false_is_off(self) -> None:
|
||||
self.assertEqual(tree.state({"enabled": False}, None), "off")
|
||||
|
||||
def test_a_key_true_in_both_maps_is_required(self) -> None:
|
||||
self.assertEqual(tree.state({"enabled": True}, {"enabled": True}), "required")
|
||||
|
||||
def test_a_key_true_only_in_the_round_is_forced_by_override(self) -> None:
|
||||
self.assertEqual(
|
||||
tree.state({"enabled": True}, {"enabled": GATE}), "forced by override"
|
||||
)
|
||||
|
||||
def test_a_group_names_gate_is_presence_gated(self) -> None:
|
||||
self.assertEqual(tree.state({"enabled": GATE}, None), "presence-gated")
|
||||
|
||||
def test_a_key_without_enabled_is_implicit(self) -> None:
|
||||
self.assertEqual(tree.state({"shared": True}, None), "implicit")
|
||||
|
||||
|
||||
class TestRender(unittest.TestCase):
|
||||
def test_the_header_names_the_closure_size(self) -> None:
|
||||
lines = tree.render_text(TREE).splitlines()
|
||||
self.assertEqual(lines[0], "a#0: include 2 (resolve_round), round index 0")
|
||||
|
||||
def test_the_primary_leads_and_its_providers_nest_below(self) -> None:
|
||||
lines = tree.render_text(TREE).splitlines()
|
||||
self.assertEqual(
|
||||
(lines[1], lines[3]), ("a#0/1 [primary]", " b#1/2 [pin by a#0]")
|
||||
)
|
||||
|
||||
def test_an_error_replaces_the_tree(self) -> None:
|
||||
text = tree.render_text({**TREE, "error": "pins cycle", "nodes": []})
|
||||
self.assertIn("error: pins cycle", text)
|
||||
|
||||
|
||||
class TestToken(unittest.TestCase):
|
||||
def test_a_bare_role_is_variant_0(self) -> None:
|
||||
self.assertEqual(tree.parse_token("web-app-a"), ("web-app-a", 0))
|
||||
|
||||
def test_a_token_keeps_its_variant(self) -> None:
|
||||
self.assertEqual(tree.parse_token("web-app-a#7"), ("web-app-a", 7))
|
||||
|
||||
|
||||
FOUR = {"web-app-a": [{}, {}, {}, {}]}
|
||||
|
||||
|
||||
class TestBuildRange(unittest.TestCase):
|
||||
def test_negative_control_a_variant_past_the_last_names_the_valid_range(
|
||||
self,
|
||||
) -> None:
|
||||
with self.assertRaisesRegex(ValueError, r"4 variant\(s\).*must be 0\.\.3"):
|
||||
tree.build("web-app-a#9", roles_dir="/roles", variants_per_app=FOUR)
|
||||
|
||||
def test_negative_control_an_unknown_role_is_refused(self) -> None:
|
||||
with self.assertRaisesRegex(ValueError, "no role 'web-app-z'"):
|
||||
tree.build("web-app-z#0", roles_dir="/roles", variants_per_app=FOUR)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user