From 7d2677898810459accf06c0772ef56aa59562fbd Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:35:15 -0500 Subject: [PATCH 01/12] test: add a systemd configuration parser for property assertions tests/unit/_systemd.py reads unit files, drop-ins, .network files, presets and tmpfiles.d the way systemd does: comments and backslash continuations, repeated keys that accumulate, empty assignments that reset (all conditions for Condition*=, never for dependencies), first matching preset rule in filename order, and ExecStart= argv with Environment= expanded. configparser cannot do this: it keeps only the last of a repeated key and knows no continuation or reset rules. test_systemd_parser.py pins those semantics so a test built on the helper cannot pass vacuously because the parser misread a file. Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/unit/_systemd.py | 181 ++++++++++++++++++++++++++++++ tests/unit/test_systemd_parser.py | 103 +++++++++++++++++ 2 files changed, 284 insertions(+) create mode 100644 tests/unit/_systemd.py create mode 100644 tests/unit/test_systemd_parser.py diff --git a/tests/unit/_systemd.py b/tests/unit/_systemd.py new file mode 100644 index 00000000..9073a791 --- /dev/null +++ b/tests/unit/_systemd.py @@ -0,0 +1,181 @@ +"""Read systemd configuration the way systemd does, so tests assert meaning. + +A test built on these helpers survives comments, whitespace and key order in +the payload, and fails when a setting systemd would act on changes. +""" + +from __future__ import annotations + +import fnmatch +import re +import shlex +from collections.abc import Iterable +from pathlib import Path +from typing import NamedTuple + +# systemd cannot remove a dependency, so an empty assignment of one of these is +# ignored. An empty Condition*= or Assert*= clears every condition or assert; +# any other empty assignment resets just that key (e.g. ExecStart= in a drop-in). +_DEPENDENCIES = frozenset( + { + "After", + "Before", + "BindsTo", + "Conflicts", + "JoinsNamespaceOf", + "OnFailure", + "OnSuccess", + "PartOf", + "PropagatesReloadTo", + "PropagatesStopTo", + "ReloadPropagatedFrom", + "Requires", + "Requisite", + "StopPropagatedFrom", + "Upholds", + "Wants", + } +) +_EXEC_KEYS = ( + "ExecCondition", + "ExecStartPre", + "ExecStart", + "ExecStartPost", + "ExecReload", + "ExecStop", + "ExecStopPost", +) +_IN_WORD_VARIABLE = re.compile(r"\$\$|\$\{(\w+)\}") + + +class SystemdFile: + """A unit, drop-in, .network or other systemd.syntax(7) file. + + ``SystemdFile(unit, *dropins)`` merges the files in the order given, the + way systemd applies drop-ins after the unit. Repeated keys accumulate. + """ + + def __init__(self, *paths: Path) -> None: + self.sections: dict[str, dict[str, list[str]]] = {} + for path in paths: + self._merge(path) + + def _merge(self, path: Path) -> None: + section = None + for line in _logical_lines(path.read_text(encoding="utf-8")): + if line.startswith("[") and line.endswith("]"): + section = self.sections.setdefault(line[1:-1], {}) + continue + key, equals, value = line.partition("=") + if section is None or not equals: + raise ValueError(f"{path}: not a Key=value line in a section: {line!r}") + key, value = key.strip(), value.strip() + if value: + section.setdefault(key, []).append(value) + elif key.startswith(("Condition", "Assert")): + group = "Condition" if key.startswith("Condition") else "Assert" + for name in [name for name in section if name.startswith(group)]: + del section[name] + elif key not in _DEPENDENCIES: + section.pop(key, None) + + def values(self, section: str, key: str) -> list[str]: + """Every value *key* holds after merging, in assignment order.""" + return list(self.sections.get(section, {}).get(key, [])) + + def value(self, section: str, key: str) -> str | None: + """A single-valued setting: the last assignment wins.""" + values = self.values(section, key) + return values[-1] if values else None + + def words(self, section: str, key: str) -> list[str]: + """A space-separated list setting such as After=, Wants= or WantedBy=.""" + return [word for value in self.values(section, key) for word in value.split()] + + def commands(self, key: str = "ExecStart") -> list[list[str]]: + """Each [Service] *key* command line as argv, Environment= expanded. + + Command prefixes (``-``, ``+``, ``!``...) are dropped; ``$VAR`` as a + word splits at whitespace, ``${VAR}`` stays one word, ``$$`` is ``$``. + """ + environment = {} + for assignment in self.values("Service", "Environment"): + for pair in shlex.split(assignment): + name, _, value = pair.partition("=") + environment[name] = value + commands = [] + for line in self.values("Service", key): + argv = [] + for word in shlex.split(line.lstrip("-@:+!|")): + if re.fullmatch(r"\$\w+", word): + argv.extend(environment.get(word[1:], "").split()) + else: + argv.append( + _IN_WORD_VARIABLE.sub( + lambda m: environment.get(m[1], "") if m[1] else "$", word + ) + ) + commands.append(argv) + return commands + + def all_commands(self) -> list[list[str]]: + return [argv for key in _EXEC_KEYS for argv in self.commands(key)] + + +def _logical_lines(text: str) -> Iterable[str]: + """Non-comment lines with backslash continuations joined, as systemd does.""" + pending = None + for raw in text.splitlines(): + if raw.strip()[:1] in ("#", ";"): + continue + line = raw if pending is None else pending + raw + if (len(line) - len(line.rstrip("\\"))) % 2: + pending = line[:-1] + " " + continue + pending = None + if line.strip(): + yield line.strip() + if pending is not None and pending.strip(): + yield pending.strip() + + +def preset_rules(path: Path) -> list[tuple[str, str]]: + """``(verb, unit glob)`` for each rule of a preset file, in order.""" + rules = [] + for line in path.read_text(encoding="utf-8").splitlines(): + words = line.split() + if words and words[0][0] not in "#;": + rules.append((words[0], words[1])) + return rules + + +def preset(unit: str, files: Iterable[Path]) -> str | None: + """The verb ``systemctl preset`` applies to *unit*, or None if no rule matches. + + systemd reads preset files in filename order across all directories and the + first matching rule wins. + """ + for path in sorted(files, key=lambda path: path.name): + for verb, pattern in preset_rules(path): + if fnmatch.fnmatchcase(unit, pattern): + return verb + return None + + +class Tmpfile(NamedTuple): + type: str + path: str + mode: str = "-" + user: str = "-" + group: str = "-" + age: str = "-" + argument: str = "-" + + +def tmpfiles(path: Path) -> list[Tmpfile]: + """The rules of a tmpfiles.d file; omitted trailing fields read as ``-``.""" + return [ + Tmpfile(*line.split(None, 6)) + for line in (raw.strip() for raw in path.read_text(encoding="utf-8").splitlines()) + if line and not line.startswith("#") + ] diff --git a/tests/unit/test_systemd_parser.py b/tests/unit/test_systemd_parser.py new file mode 100644 index 00000000..e70e0232 --- /dev/null +++ b/tests/unit/test_systemd_parser.py @@ -0,0 +1,103 @@ +"""The systemd parsing helpers model systemd, so tests built on them mean something.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from _systemd import SystemdFile, Tmpfile, preset, tmpfiles + + +def write(tmp_path: Path, name: str, text: str) -> Path: + path = tmp_path / name + path.write_text(text, encoding="utf-8") + return path + + +def test_repeated_keys_accumulate_and_the_last_single_value_wins(tmp_path: Path) -> None: + unit = SystemdFile( + write( + tmp_path, + "a.service", + "[Unit]\nAfter=a.target b.target\nAfter = c.target\n" + "[Service]\nRestart=no\nRestart=on-failure\n", + ) + ) + assert unit.words("Unit", "After") == ["a.target", "b.target", "c.target"] + assert unit.value("Service", "Restart") == "on-failure" + assert unit.value("Service", "Type") is None + + +def test_comments_and_continuations_follow_systemd_syntax(tmp_path: Path) -> None: + unit = SystemdFile( + write( + tmp_path, + "a.service", + "# comment\n; comment\n[Service]\nExecStart=/usr/bin/foo \\\n" + "# comment inside a continuation\n --bar\nEnvironment=A=\\\\\n", + ) + ) + assert unit.commands() == [["/usr/bin/foo", "--bar"]] + assert unit.values("Service", "Environment") == ["A=\\\\"] + + +def test_dropins_reset_keys_but_not_dependencies(tmp_path: Path) -> None: + unit = write( + tmp_path, + "a.service", + "[Unit]\nWants=x.service\nConditionPathExists=/a\nConditionHost=h\n" + "[Service]\nExecStart=/usr/bin/old\n", + ) + dropin = write( + tmp_path, + "10-override.conf", + "[Unit]\nWants=\nConditionPathExists=\nConditionPathExists=/b\n" + "[Service]\nExecStart=\nExecStart=/usr/bin/new\n", + ) + merged = SystemdFile(unit, dropin) + assert merged.words("Unit", "Wants") == ["x.service"] + assert merged.sections["Unit"]["ConditionPathExists"] == ["/b"] + assert "ConditionHost" not in merged.sections["Unit"] + assert merged.commands() == [["/usr/bin/new"]] + + +def test_commands_expand_environment_like_systemd(tmp_path: Path) -> None: + unit = SystemdFile( + write( + tmp_path, + "a.service", + '[Service]\nEnvironment="ARGS=--one --two" ONE=x\n' + "ExecStart=-/usr/bin/foo $ARGS ${ARGS} pre${ONE} $$HOME $MISSING\n", + ) + ) + assert unit.commands() == [ + ["/usr/bin/foo", "--one", "--two", "--one --two", "prex", "$HOME"] + ] + + +def test_malformed_lines_are_errors_not_silently_dropped(tmp_path: Path) -> None: + with pytest.raises(ValueError): + SystemdFile(write(tmp_path, "a.service", "[Unit]\nAfter\n")) + with pytest.raises(ValueError): + SystemdFile(write(tmp_path, "b.service", "After=a.target\n")) + + +def test_first_matching_preset_wins_across_files_in_name_order(tmp_path: Path) -> None: + late = write(tmp_path, "90-late.preset", "enable *\n") + early = write(tmp_path, "20-early.preset", "# comment\ndisable foo*.service\n") + assert preset("foo.service", [late, early]) == "disable" + assert preset("bar.service", [late, early]) == "enable" + assert preset("bar.service", [early]) is None + + +def test_tmpfiles_fields_default_to_dash(tmp_path: Path) -> None: + conf = write( + tmp_path, + "a.conf", + "# comment\nd /var/lib/a 0755 root root\nL /etc/b - - - - ../run/b c\n", + ) + assert tmpfiles(conf) == [ + Tmpfile("d", "/var/lib/a", "0755", "root", "root"), + Tmpfile("L", "/etc/b", argument="../run/b c"), + ] From f7240756e058392ba7afdf975c74a068166a098e Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:35:27 -0500 Subject: [PATCH 02/12] test(k0s): assert parsed first-boot, preset, network and tmpfiles properties Replace substring and byte-for-byte file comparisons with parsed properties: unit ordering and conditions, the effective preset verdict, the wired [Match]/[Network] settings, where each import element lands in the image, and which tmpfiles.d rule wins for /etc/resolv.conf. The join-token role switch now runs the unit's own sh -c script against a stub systemctl (no token, empty token, token), so an inverted test or swapped branch fails; string greps passed either way. The preset order check covers every preset under files/, sysext presets included. The resolv.conf comment described Flatcar's image build. On FSDK, /etc starts empty and FSDK's systemd-resolve.conf links the 127.0.0.53 stub, so the test now also requires the Bluefin rule to sort ahead of it. Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/unit/test_k0s_first_boot.py | 308 +++++++++++++++--------------- 1 file changed, 158 insertions(+), 150 deletions(-) diff --git a/tests/unit/test_k0s_first_boot.py b/tests/unit/test_k0s_first_boot.py index 6cfab0e4..1122d3f9 100644 --- a/tests/unit/test_k0s_first_boot.py +++ b/tests/unit/test_k0s_first_boot.py @@ -1,148 +1,162 @@ """Contracts for retry-safe k0s sysext first-boot activation.""" +import posixpath +import subprocess from pathlib import Path +import pytest +import yaml + +from _systemd import SystemdFile, preset, tmpfiles + ROOT = Path(__file__).resolve().parents[2] -SERVICE = ( - ROOT / "files" / "os" / "systemd" / "system" / "k0s-first-boot.service" -) -FETCH_SERVICE = ( - ROOT - / "files" - / "os" - / "systemd" - / "system" - / "k0s-first-boot-fetch.service" -) -PRESET = ( - ROOT - / "files" - / "os" - / "systemd" - / "system-preset" - / "80-bluefin-k0s-first-boot.preset" -) +UNITS = ROOT / "files" / "os" / "systemd" / "system" +SERVICE = UNITS / "k0s-first-boot.service" +FETCH_SERVICE = UNITS / "k0s-first-boot-fetch.service" +PRESETS = sorted((ROOT / "files" / "os" / "systemd" / "system-preset").glob("*.preset")) NETWORK = ROOT / "files" / "os" / "systemd" / "network" / "20-wired.network" -NETWORK_PRESET = ( - ROOT - / "files" - / "os" - / "systemd" - / "system-preset" - / "80-bluefin-networkd.preset" -) -ELEMENT = ROOT / "elements" / "bluefin-server" / "os-k0s-first-boot.bst" -NETWORK_ELEMENT = ROOT / "elements" / "bluefin-server" / "os-networkd.bst" -K0S_UPDATE_ELEMENT = ( - ROOT / "elements" / "bluefin-server" / "os-k0s-sysupdate.bst" -) -STACK = ROOT / "elements" / "bluefin-server" / "os-stack.bst" +TMPFILES = ROOT / "files" / "os" / "tmpfiles.d" +ELEMENTS = ROOT / "elements" +ELEMENT = ELEMENTS / "bluefin-server" / "os-k0s-first-boot.bst" +NETWORK_ELEMENT = ELEMENTS / "bluefin-server" / "os-networkd.bst" +K0S_UPDATE_ELEMENT = ELEMENTS / "bluefin-server" / "os-k0s-sysupdate.bst" +RESOLV_ELEMENT = ELEMENTS / "bluefin-server" / "os-resolv-conf.bst" +STACK = ELEMENTS / "bluefin-server" / "os-stack.bst" + + +def installed_at(element: Path) -> dict[str, str]: + """Where each local source of an import element lands in the image.""" + data = yaml.safe_load(element.read_text(encoding="utf-8")) + assert data["kind"] == "import", element + config = data.get("config", {}) + assert config.get("source", "/") == "/", element + return { + source["path"]: posixpath.join(config.get("target", "/"), source.get("directory", "")) + .rstrip("/") + for source in data["sources"] + if source["kind"] == "local" + } + + +def in_os_stack(element: Path) -> bool: + depends = yaml.safe_load(STACK.read_text(encoding="utf-8"))["depends"] + return element.relative_to(ELEMENTS).as_posix() in depends + + +def words(unit: SystemdFile) -> list[str]: + return [word for argv in unit.all_commands() for word in argv] def test_seeded_install_skips_the_network_fetch() -> None: - assert FETCH_SERVICE.is_file(), "the conditional k0s fetch unit is missing" - fetch_service = FETCH_SERVICE.read_text(encoding="utf-8") - first_boot = SERVICE.read_text(encoding="utf-8") - - assert "ConditionPathExists=!/var/lib/k0s/k0s.raw" in fetch_service - assert ( - "ExecStart=/usr/bin/systemd-sysupdate --component=k0s update" - in fetch_service - ) - assert "systemd-sysupdate" not in first_boot + fetch = SystemdFile(FETCH_SERVICE) + + assert "!/var/lib/k0s/k0s.raw" in fetch.values("Unit", "ConditionPathExists") + assert fetch.commands() == [["/usr/bin/systemd-sysupdate", "--component=k0s", "update"]] + assert not [w for w in words(SystemdFile(SERVICE)) if "systemd-sysupdate" in w] def test_missing_seed_fetches_before_activation_without_blocking_activation_retry() -> None: - assert FETCH_SERVICE.is_file(), "the conditional k0s fetch unit is missing" - fetch_service = FETCH_SERVICE.read_text(encoding="utf-8") - first_boot = SERVICE.read_text(encoding="utf-8") - - assert "Type=oneshot" in fetch_service - assert "Restart=on-failure" in fetch_service - assert "ConditionPathExists=!/var/lib/k0s/k0s.raw" in fetch_service - assert "Before=k0s-first-boot.service" in fetch_service - assert "Wants=k0s-first-boot-fetch.service" in first_boot - assert "Requires=k0s-first-boot-fetch.service" not in first_boot - assert "After=k0s-first-boot-fetch.service" in first_boot - assert ( - "ExecStartPre=/usr/bin/test -e /var/lib/k0s/k0s.raw" - in first_boot - ) - assert ( - "ExecStart=/usr/bin/install -D -m 0644 " - "/var/lib/k0s/k0s.raw /run/extensions/k0s.raw" - ) in first_boot - assert "ExecStart=/usr/bin/systemd-sysext refresh" in first_boot + fetch = SystemdFile(FETCH_SERVICE) + first_boot = SystemdFile(SERVICE) + + assert fetch.value("Service", "Type") == "oneshot" + assert fetch.value("Service", "Restart") == "on-failure" + assert "!/var/lib/k0s/k0s.raw" in fetch.values("Unit", "ConditionPathExists") + assert "k0s-first-boot.service" in fetch.words("Unit", "Before") + assert "k0s-first-boot-fetch.service" in first_boot.words("Unit", "Wants") + assert "k0s-first-boot-fetch.service" in first_boot.words("Unit", "After") + for hard in ("Requires", "Requisite", "BindsTo"): + assert "k0s-first-boot-fetch.service" not in first_boot.words("Unit", hard), ( + "a failed fetch must not fail the activation job" + ) + assert ["/usr/bin/test", "-e", "/var/lib/k0s/k0s.raw"] in first_boot.commands("ExecStartPre") + start = first_boot.commands() + install = [ + "/usr/bin/install", "-D", "-m", "0644", "/var/lib/k0s/k0s.raw", "/run/extensions/k0s.raw" + ] + refresh = ["/usr/bin/systemd-sysext", "refresh"] + assert install in start and refresh in start + assert start.index(install) < start.index(refresh) def test_k0s_first_boot_retries_until_controller_starts() -> None: - service = SERVICE.read_text(encoding="utf-8") - - assert "ConditionPathExists=" not in service - assert "Wants=network-online.target" in service - assert "After=network-online.target" in service - assert "Before=multi-user.target" not in service - assert "Type=oneshot" in service - assert "StateDirectory=k0s" in service - assert "Restart=on-failure" in service - assert ( - "ExecStart=/usr/bin/systemd-sysupdate --component=k0s update" - not in service - ) - assert "ExecStart=/usr/bin/systemd-sysupdate update" not in service - assert "ExecStart=/usr/bin/systemctl enable --now systemd-sysext.service" not in service - assert "ExecStart=/usr/bin/systemd-sysext refresh" in service - assert "kubeflex" not in service, "the KubeStellar sysext seeds its own state" - assert "ExecStart=/usr/bin/systemctl daemon-reload" in service - assert "systemctl enable --now k0scontroller.service" in service - assert "[ -s /etc/k0s/token ]" in service and "k0sworker.service" in service - assert ( - "ExecStartPost=/usr/bin/touch /var/lib/k0s/.first-boot-complete" - not in service + unit = SystemdFile(SERVICE) + commands = unit.commands() + + assert unit.values("Unit", "ConditionPathExists") == [] + assert unit.values("Unit", "ConditionFirstBoot") == [] + assert "network-online.target" in unit.words("Unit", "Wants") + assert "network-online.target" in unit.words("Unit", "After") + assert "multi-user.target" not in unit.words("Unit", "Before") + assert unit.value("Service", "Type") == "oneshot" + assert unit.value("Service", "StateDirectory") == "k0s" + assert unit.value("Service", "Restart") == "on-failure" + assert ["/usr/bin/systemd-sysext", "refresh"] in commands + assert ["/usr/bin/systemctl", "daemon-reload"] in commands + for forbidden in ("systemd-sysupdate", "systemd-sysext.service", ".first-boot-complete"): + assert not [w for w in words(unit) if forbidden in w], forbidden + assert not [w for w in words(unit) if "kubeflex" in w], "the KubeStellar sysext seeds its own state" + + +@pytest.mark.parametrize( + ("token", "role"), + [ + (None, "k0scontroller.service"), + ("", "k0scontroller.service"), + ("K0S-JOIN-TOKEN", "k0sworker.service"), + ], +) +def test_join_token_selects_the_role_first_boot_enables( + tmp_path: Path, token: str | None, role: str +) -> None: + scripts = [ + argv[2] + for argv in SystemdFile(SERVICE).commands() + if posixpath.basename(argv[0]) == "sh" and argv[1:2] == ["-c"] + ] + assert len(scripts) == 1, "expected one sh -c command choosing the k0s role" + assert "/etc/k0s/token" in scripts[0] + token_file = tmp_path / "token" + if token is not None: + token_file.write_text(token, encoding="utf-8") + stubs = tmp_path / "bin" + stubs.mkdir() + (stubs / "systemctl").write_text('#!/bin/sh\necho "$@" >> "$CALLS"\n', encoding="utf-8") + (stubs / "systemctl").chmod(0o755) + calls = tmp_path / "calls" + + subprocess.run( + ["sh", "-c", scripts[0].replace("/etc/k0s/token", str(token_file))], + env={"PATH": f"{stubs}:/usr/bin:/bin", "CALLS": str(calls)}, + check=True, ) - assert "ConditionFirstBoot" not in service + + assert calls.read_text(encoding="utf-8").splitlines() == [f"enable --now {role}"] def test_k0s_first_boot_is_packaged_but_opt_in() -> None: - assert not PRESET.exists(), "k0s is opt-in: no preset may enable k0s-first-boot" - opt_in = PRESET.parent / "80-bluefin-opt-in.preset" - lines = opt_in.read_text(encoding="utf-8").splitlines() - assert "disable k0s-first-boot.service" in lines, ( - "FSDK has no 'disable *' default, so the unit must be disabled explicitly" - ) - assert "path: files/os/systemd/system" in ELEMENT.read_text(encoding="utf-8") - assert "target: /usr/lib/systemd/system" in ELEMENT.read_text(encoding="utf-8") - assert ( - "bluefin-server/os-k0s-first-boot.bst" - in STACK.read_text(encoding="utf-8") - ) + for unit in ("k0s-first-boot.service", "k0s-first-boot-fetch.service"): + assert preset(unit, PRESETS) == "disable", ( + f"k0s is opt-in: FSDK has no 'disable *' default, so {unit} must be " + "disabled explicitly and no earlier preset may enable it" + ) + assert installed_at(ELEMENT)["files/os/systemd/system"] == "/usr/lib/systemd/system" + assert in_os_stack(ELEMENT) def test_installed_os_configures_wired_dhcp_with_networkd() -> None: - assert NETWORK.read_text(encoding="utf-8") == ( - "[Match]\n" - "Name=e*\n" - "\n" - "[Network]\n" - "DHCP=ipv4\n" - ) - assert NETWORK_PRESET.read_text(encoding="utf-8") == ( - "enable systemd-networkd.service\n" - ) - network_element = NETWORK_ELEMENT.read_text(encoding="utf-8") - assert "path: files/os/systemd/network" in network_element - assert "target: /usr/lib/systemd/network" in network_element - assert "bluefin-server/os-networkd.bst" in STACK.read_text(encoding="utf-8") + network = SystemdFile(NETWORK) + + assert network.sections["Match"] == {"Name": ["e*"]}, "match every wired link, nothing narrower" + assert network.value("Network", "DHCP") == "ipv4" + assert preset("systemd-networkd.service", PRESETS) == "enable" + assert installed_at(NETWORK_ELEMENT)["files/os/systemd/network"] == "/usr/lib/systemd/network" + assert in_os_stack(NETWORK_ELEMENT) def test_k0s_sysupdate_transfer_is_packaged_as_a_component() -> None: - element = K0S_UPDATE_ELEMENT.read_text(encoding="utf-8") - assert "path: files/os/sysupdate.k0s.d" in element - assert "target: /usr/lib/sysupdate.k0s.d" in element - assert ( - "bluefin-server/os-k0s-sysupdate.bst" - in STACK.read_text(encoding="utf-8") - ) + assert installed_at(K0S_UPDATE_ELEMENT)["files/os/sysupdate.k0s.d"] == "/usr/lib/sysupdate.k0s.d" + assert in_os_stack(K0S_UPDATE_ELEMENT) def test_presets_sort_between_ignition_and_fsdk_defaults() -> None: @@ -150,11 +164,11 @@ def test_presets_sort_between_ignition_and_fsdk_defaults() -> None: # the first matching line wins. Ignition enables units through # /etc/systemd/system-preset/20-ignition.preset, so a vendor preset that # sorts before it (e.g. 20-bluefin-sshd.preset: "disable sshd.service") - # silently overrides a node config's `enabled: true`. Vendor presets must - # still sort before FSDK's 90-systemd.preset to take effect at all. - preset_dir = PRESET.parent - presets = sorted(p.name for p in preset_dir.glob("*.preset")) - assert presets, f"no presets found in {preset_dir}" + # silently overrides a node config's `enabled: true`. Vendor presets, + # including those a sysext merges into /usr, must still sort before + # FSDK's 90-systemd.preset to take effect at all. + presets = sorted(p.name for p in (ROOT / "files").rglob("*.preset")) + assert presets, "no presets found under files/" for name in presets: assert "20-ignition.preset" < name < "90-systemd.preset", ( f"{name} must sort after 20-ignition.preset (so Ignition can " @@ -163,29 +177,23 @@ def test_presets_sort_between_ignition_and_fsdk_defaults() -> None: def test_etc_resolv_conf_symlink_is_seeded_for_kubelet() -> None: - # FSDK 26.08 ships no /etc/resolv.conf rule (upstream systemd leaves the - # symlink to the distro), and this DDI boots with an empty /etc, so - # without an explicit tmpfiles.d rule the symlink never exists and - # kubelet fails every pod sandbox with - # "open /etc/resolv.conf: no such file or directory". - conf = ( - ROOT / "files" / "os" / "tmpfiles.d" / "20-bluefin-resolv.conf" - ) - assert conf.is_file(), "resolv.conf tmpfiles rule is missing" - lines = [ - line - for line in conf.read_text(encoding="utf-8").splitlines() - if line and not line.startswith("#") - ] - assert lines == [ - "L /etc/resolv.conf - - - - ../run/systemd/resolve/resolv.conf" + # /etc starts empty on every boot (bluefin-server-usr.bst moves the build's + # /etc to /usr/share/factory/etc), so /etc/resolv.conf exists only if a + # tmpfiles.d rule creates it; without it kubelet fails every pod sandbox + # with "open /etc/resolv.conf: no such file or directory". FSDK's own + # systemd-resolve.conf links the 127.0.0.53 stub, which is unreachable from + # a pod's network namespace. systemd-tmpfiles applies the first rule for a + # path in filename order, so the rule linking resolved's full upstream list + # must come first and sort before systemd-resolve.conf. + rules = [ + (conf.name, rule) + for conf in sorted(TMPFILES.glob("*.conf")) + for rule in tmpfiles(conf) + if rule.path == "/etc/resolv.conf" ] - - element = ( - ROOT / "elements" / "bluefin-server" / "os-resolv-conf.bst" - ).read_text(encoding="utf-8") - assert "path: files/os/tmpfiles.d" in element - assert "target: /usr/lib/tmpfiles.d" in element - assert ( - "bluefin-server/os-resolv-conf.bst" in STACK.read_text(encoding="utf-8") - ) + assert rules, "no tmpfiles.d rule creates /etc/resolv.conf" + name, rule = rules[0] + assert (rule.type, rule.argument) == ("L", "../run/systemd/resolve/resolv.conf") + assert name < "systemd-resolve.conf" + assert installed_at(RESOLV_ELEMENT)["files/os/tmpfiles.d"] == "/usr/lib/tmpfiles.d" + assert in_os_stack(RESOLV_ELEMENT) From 77d3e6b821624195a46024431d688053e132c198 Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:35:27 -0500 Subject: [PATCH 03/12] test(creds): assert parsed credential unit properties; drop Flatcar narrative bluefin-firstboot-credentials.service, the network-generator drop-in, the presets and 20-wired.network are now checked as parsed settings instead of exact file text: the triggering ConditionCredential= set must equal the imported set, the stamp is touched in ExecStartPost= and gates the unit, and every shipped .network file sorts after the documented 10-static credential so it can still override the DHCP fallback. The comments claimed Flatcar's /usr has no systemd-firstboot and that /bin comes from Flatcar tmpfiles. FSDK ships systemd-firstboot; the helper stays because it also sets the live kernel hostname before networkd starts, and the image contains only /usr. Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/unit/test_credentials_provisioning.py | 104 ++++++++---------- .../test_firstboot_credentials_behavior.py | 13 ++- 2 files changed, 53 insertions(+), 64 deletions(-) diff --git a/tests/unit/test_credentials_provisioning.py b/tests/unit/test_credentials_provisioning.py index 1c4366f9..b1ccfc73 100644 --- a/tests/unit/test_credentials_provisioning.py +++ b/tests/unit/test_credentials_provisioning.py @@ -6,6 +6,8 @@ import yaml +from _systemd import SystemdFile, preset + REPO_ROOT = Path(__file__).resolve().parents[2] ELEMENT = REPO_ROOT / "elements" / "bluefin-server" / "os-creds-prov.bst" STACK = REPO_ROOT / "elements" / "bluefin-server" / "os-stack.bst" @@ -18,22 +20,7 @@ / "system" / "bluefin-firstboot-credentials.service" ) -FIRSTBOOT_PRESET = ( - REPO_ROOT - / "files" - / "os" - / "systemd" - / "system-preset" - / "80-bluefin-firstboot-credentials.preset" -) -NETWORK_GENERATOR_PRESET = ( - REPO_ROOT - / "files" - / "os" - / "systemd" - / "system-preset" - / "80-bluefin-systemd-network-generator.preset" -) +PRESETS = sorted((REPO_ROOT / "files" / "os" / "systemd" / "system-preset").glob("*.preset")) NETWORK_GENERATOR_DROPIN = ( REPO_ROOT / "files" @@ -54,7 +41,7 @@ def test_creds_provisioning_element_stages_all_credential_consumers() -> None: assert data["kind"] == "manual" assert "base/base-stack.bst" in data["build-depends"] - assert "bluefin-server/os-creds-prov.bst" in STACK.read_text(encoding="utf-8") + assert "bluefin-server/os-creds-prov.bst" in yaml.safe_load(STACK.read_text(encoding="utf-8"))["depends"] sources = {source["directory"]: source["path"] for source in data["sources"]} assert sources == { @@ -73,61 +60,62 @@ def test_creds_provisioning_element_stages_all_credential_consumers() -> None: def test_firstboot_credentials_are_noninteractive_and_presence_gated() -> None: - unit = FIRSTBOOT.read_text(encoding="utf-8") - - for credential in ( + unit = SystemdFile(FIRSTBOOT) + credentials = { "firstboot.locale", "firstboot.locale-messages", "firstboot.keymap", "firstboot.timezone", "firstboot.hostname", - ): - assert f"ConditionCredential=|{credential}" in unit - assert f"ImportCredential={credential}" in unit - - # The unit must not call systemd-firstboot: Bluefin's helper applies - # firstboot.hostname unconditionally and sets the live kernel hostname, - # which systemd-firstboot does not do. It also runs before sysinit.target - # with minimal dependencies (bash + coreutils only). - assert "systemd-firstboot" not in unit - assert "ExecStart=/usr/libexec/bluefin-firstboot-credentials" in unit - assert unit.index("ExecStart=/usr/libexec/bluefin-firstboot-credentials") < unit.index( - "ExecStartPost=/usr/bin/touch /etc/.bluefin-firstboot-credentials" - ) - assert "--prompt" not in unit - assert "ConditionPathIsReadWrite=/etc" in unit - assert "ConditionPathExists=!/etc/.bluefin-firstboot-credentials" in unit - assert ( - "After=systemd-remount-fs.service systemd-sysusers.service " - "systemd-tmpfiles-setup.service" - in unit - ) - assert "WantedBy=sysinit.target" in unit - assert FIRSTBOOT_PRESET.read_text(encoding="utf-8") == ( - "enable bluefin-firstboot-credentials.service\n" - ) + } + + conditions = unit.values("Unit", "ConditionCredential") + assert all(c.startswith("|") for c in conditions), "any one credential must trigger the unit" + assert {c[1:] for c in conditions} == credentials + assert set(unit.values("Service", "ImportCredential")) == credentials + + # The bundled helper applies them, not systemd-firstboot: it also sets the + # live kernel hostname before systemd-networkd starts, so the first DHCP + # request already carries firstboot.hostname. + words = [word for argv in unit.all_commands() for word in argv] + assert not [w for w in words if "systemd-firstboot" in w or "--prompt" in w] + assert ["/usr/libexec/bluefin-firstboot-credentials"] in unit.commands() + assert "systemd-networkd.service" in unit.words("Unit", "Before") + # ExecStartPost= runs only after ExecStart= succeeded, so a failed helper + # leaves no stamp and runs again on the next boot. + assert ["/usr/bin/touch", "/etc/.bluefin-firstboot-credentials"] in unit.commands("ExecStartPost") + assert "!/etc/.bluefin-firstboot-credentials" in unit.values("Unit", "ConditionPathExists") + assert "/etc" in unit.values("Unit", "ConditionPathIsReadWrite") + assert { + "systemd-remount-fs.service", + "systemd-sysusers.service", + "systemd-tmpfiles-setup.service", + } <= set(unit.words("Unit", "After")) + assert "sysinit.target" in unit.words("Install", "WantedBy") + assert preset("bluefin-firstboot-credentials.service", PRESETS) == "enable" def test_network_credentials_override_dhcp_without_removing_fallback() -> None: - network = NETWORK.read_text(encoding="utf-8") skill = TPM2_SKILL.read_text(encoding="utf-8") - assert network == "[Match]\nName=e*\n\n[Network]\nDHCP=ipv4\n" + # networkd applies the first .network file, in filename order across + # /run and /usr, that matches a link: the documented 10-static credential + # must sort before every shipped file, which stays the DHCP fallback. + assert "10-static.network" in skill + shipped = sorted(p.name for p in NETWORK.parent.glob("*.network")) + assert shipped and all(name > "10-static.network" for name in shipped), shipped + assert SystemdFile(NETWORK).value("Network", "DHCP") == "ipv4" assert "network.network.*" in skill assert "network.netdev.*" in skill - assert NETWORK_GENERATOR_DROPIN.read_text(encoding="utf-8") == ( - "[Service]\n" - "ImportCredential=network.conf.*\n" - "ImportCredential=network.link.*\n" - "ImportCredential=network.netdev.*\n" - "ImportCredential=network.network.*\n" - ) + assert set(SystemdFile(NETWORK_GENERATOR_DROPIN).values("Service", "ImportCredential")) == { + "network.conf.*", + "network.link.*", + "network.netdev.*", + "network.network.*", + } assert "systemd-network-generator" in skill assert "/run/systemd/network/" in skill - assert "10-static.network" in skill - assert NETWORK_GENERATOR_PRESET.read_text(encoding="utf-8") == ( - "enable systemd-network-generator.service\n" - ) + assert preset("systemd-network-generator.service", PRESETS) == "enable" def test_tpm2_sealing_docs_cover_all_supported_credential_names() -> None: diff --git a/tests/unit/test_firstboot_credentials_behavior.py b/tests/unit/test_firstboot_credentials_behavior.py index 23b096cf..b989cf8f 100644 --- a/tests/unit/test_firstboot_credentials_behavior.py +++ b/tests/unit/test_firstboot_credentials_behavior.py @@ -1,9 +1,10 @@ """Executed coverage for files/os/libexec/bluefin-firstboot-credentials. -The helper replaces `systemd-firstboot --force --welcome=no` in -bluefin-firstboot-credentials.service because Flatcar's /usr is built without -systemd-firstboot. These tests drive it under bash against a scratch --root -with credentials laid out the way ImportCredential= presents them. +bluefin-firstboot-credentials.service runs this helper instead of +systemd-firstboot: it writes the same files and also applies firstboot.hostname +to the live kernel hostname before systemd-networkd starts. These tests drive +it under bash against a scratch --root with credentials laid out the way +ImportCredential= presents them. """ from __future__ import annotations @@ -41,8 +42,8 @@ def _run(tmp_path: Path, creds: dict[str, str], zoneinfo: tuple[str, ...] = ("Eu def test_helper_is_bash_that_passes_syntax() -> None: - # /usr/bin/bash, not /bin/bash: /bin is a tmpfiles-created symlink on - # Flatcar and the unit runs before sysinit.target. + # /usr/bin/bash, not /bin/bash: the image ships only /usr, and /bin is a + # symlink on the root file system that the image does not contain. assert HELPER.read_text(encoding="utf-8").startswith("#!/usr/bin/bash\n") subprocess.run(["bash", "-n", str(HELPER)], check=True) From b1596013455b5829b24487d89b8ae12029ce35e9 Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:39:43 -0500 Subject: [PATCH 04/12] test(k0s): check the k0s units, seed and manifests as parsed settings k0scontroller.service is now checked on its effective command line, with K0S_CONTROLLER_ARGS expanded from Environment=: the old grep still passed if ExecStart= stopped referencing the variable. The worker's join-token argv and condition, the manifest tmpfiles rules, the seed unit's generators and ordering, and the Argo CD manifest's namespace are parsed rather than grepped. Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/unit/test_k0s_manifests.py | 69 ++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 25 deletions(-) diff --git a/tests/unit/test_k0s_manifests.py b/tests/unit/test_k0s_manifests.py index 238d13c3..68f5d2bd 100644 --- a/tests/unit/test_k0s_manifests.py +++ b/tests/unit/test_k0s_manifests.py @@ -1,42 +1,63 @@ from pathlib import Path import os +import posixpath import subprocess import yaml +from _systemd import SystemdFile, Tmpfile, tmpfiles + ROOT = Path(__file__).resolve().parents[2] +SEED = ROOT / "files" / "kubestellar" / "sysext" / "kubestellar-seed.service" def test_k0s_service_unit(): unit = ROOT / "files" / "k0s" / "sysext" / "k0scontroller.service" assert unit.is_file(), "k0scontroller.service missing" - text = unit.read_text() - assert "--disable-components=helm,autopilot" in text - assert "--enable-worker" in text - assert "--single" in text - assert "ConditionPathExists=!/etc/k0s/token" in text + controller = SystemdFile(unit) + # The default command line, K0S_CONTROLLER_ARGS from Environment= expanded: + # a single-node controller that also runs the workloads. + commands = controller.commands() + assert len(commands) == 1 + argv = commands[0] + assert posixpath.basename(argv[0]) == "k0s" and argv[1] == "controller" + assert {"--enable-worker", "--single", "--disable-components=helm,autopilot"} <= set(argv[2:]) + assert "!/etc/k0s/token" in controller.values("Unit", "ConditionPathExists") def test_k0s_worker_unit_joins_with_the_token_file(): - text = (ROOT / "files" / "k0s" / "sysext" / "k0sworker.service").read_text() - assert "ConditionPathExists=/etc/k0s/token" in text - assert "k0s worker --token-file /etc/k0s/token" in text + worker = SystemdFile(ROOT / "files" / "k0s" / "sysext" / "k0sworker.service") + commands = worker.commands() + assert len(commands) == 1 + argv = commands[0] + assert posixpath.basename(argv[0]) == "k0s" + assert argv[1:4] == ["worker", "--token-file", "/etc/k0s/token"] + assert "/etc/k0s/token" in worker.values("Unit", "ConditionPathExists") def test_k0s_manifests_conf(): conf = ROOT / "files" / "kubestellar" / "sysext" / "k0s-manifests.conf" assert conf.is_file(), "k0s-manifests.conf missing" - text = conf.read_text() - assert "d /var/lib/k0s/manifests 0755 root root - -" in text - assert "C+ /var/lib/k0s/manifests/argocd - - - - /usr/share/k0s/manifests/argocd" in text - assert "C+ /var/lib/k0s/manifests/kubestellar - - - - /usr/share/k0s/manifests/kubestellar" in text + rules = {rule.path: rule for rule in tmpfiles(conf)} + assert rules["/var/lib/k0s/manifests"] == Tmpfile( + "d", "/var/lib/k0s/manifests", "0755", "root", "root", "-", "-" + ) + for stack in ("argocd", "kubestellar"): + rule = rules[f"/var/lib/k0s/manifests/{stack}"] + assert (rule.type, rule.argument) == ("C+", f"/usr/share/k0s/manifests/{stack}") def test_k0s_manifest_files(): argo_yaml = ROOT / "files" / "k0s" / "manifests" / "argocd" / "install.yaml" assert argo_yaml.is_file(), "argocd install.yaml missing" - assert "namespace: argocd" in argo_yaml.read_text() + docs = [d for d in yaml.safe_load_all(argo_yaml.read_text()) if d] + assert {"kind": "Namespace", "name": "argocd"} in [ + {"kind": d["kind"], "name": d["metadata"]["name"]} for d in docs + ] + namespaced = [d for d in docs if d["kind"] != "Namespace"] + assert namespaced + assert all(d["metadata"].get("namespace") == "argocd" for d in namespaced) ks_dir = ROOT / "files" / "k0s" / "manifests" / "kubestellar" assert (ks_dir / "00-kubeflex-crds.yaml").is_file() @@ -69,15 +90,17 @@ def test_postgres_password_from_secret(): assert ref == {"name": "kubeflex-postgres", "key": "password"} +def seed_runs(script: str) -> bool: + return any(posixpath.basename(argv[0]) == script for argv in SystemdFile(SEED).all_commands()) + + def test_k0s_first_boot_generates_postgres_secret_before_k0s(): # The Secret must be staged before k0s applies the manifests, and the # generated 15- file must sort before 20-postgres.yaml. - unit = ROOT / "files" / "kubestellar" / "sysext" / "kubestellar-seed.service" - text = unit.read_text() - lines = [l for l in text.splitlines() if l.startswith("ExecStart")] - gen = next((i for i, l in enumerate(lines) if "generate-postgres-secret.sh" in l), None) - assert gen is not None, "kubestellar-seed never runs the postgres secret generator" - assert "Before=k0scontroller.service" in text, "secrets must exist before k0s applies manifests" + assert seed_runs("generate-postgres-secret.sh"), "kubestellar-seed never runs the postgres secret generator" + assert "k0scontroller.service" in SystemdFile(SEED).words("Unit", "Before"), ( + "secrets must exist before k0s applies manifests" + ) def test_generate_postgres_secret_is_idempotent(tmp_path): @@ -116,12 +139,8 @@ def yaml_values(text): def test_k0s_first_boot_generates_console_secret_before_k0s(): - unit = ROOT / "files" / "kubestellar" / "sysext" / "kubestellar-seed.service" - text = unit.read_text() - lines = [l for l in text.splitlines() if l.startswith("ExecStart")] - gen = next((i for i, l in enumerate(lines) if "generate-console-secret.sh" in l), None) - assert gen is not None, "kubestellar-seed never runs the console secret generator" - assert "Before=k0scontroller.service" in text + assert seed_runs("generate-console-secret.sh"), "kubestellar-seed never runs the console secret generator" + assert "k0scontroller.service" in SystemdFile(SEED).words("Unit", "Before") def test_generate_console_secret_is_idempotent(tmp_path): From fa19b64a018e20e568d5830771ff6abbbbb34cc1 Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:39:43 -0500 Subject: [PATCH 05/12] test(kiosk): parse the kiosk manifests and run the TLS key seed The console and proxy Deployments are parsed instead of grepped: each login flag must be "true" (any 'value: "true"' used to satisfy all of them), the proxy must publish on 127.0.0.1:8080 only (hostIP was never checked), the console must not use hostNetwork, hostPort or a non ClusterIP Service, and the read-only mount must be backed by the kiosk hostPath. kubestellar-seed's key script now runs against a stub openssl: the key is created under umask 077, the certificate is chmod 0644, and an existing key is never regenerated. Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/unit/test_kubestellar_kiosk.py | 117 +++++++++++++++++++-------- 1 file changed, 82 insertions(+), 35 deletions(-) diff --git a/tests/unit/test_kubestellar_kiosk.py b/tests/unit/test_kubestellar_kiosk.py index 41c54196..3331f7f1 100644 --- a/tests/unit/test_kubestellar_kiosk.py +++ b/tests/unit/test_kubestellar_kiosk.py @@ -1,9 +1,14 @@ """Contracts for the KubeStellar kiosk proxy and authenticated agent gate.""" +import posixpath +import re +import subprocess from pathlib import Path import yaml +from _systemd import SystemdFile, tmpfiles + ROOT = Path(__file__).resolve().parents[2] KIOSK = ROOT / "files" / "k0s" / "kiosk" KIOSK_CONF = KIOSK / "nginx.conf" @@ -31,29 +36,68 @@ ) +def local_sources(element: Path) -> list[dict]: + data = yaml.safe_load(element.read_text(encoding="utf-8")) + return [s for s in data["sources"] if s["kind"] == "local"] + + +def deployment_pod(manifest: Path, name: str) -> dict: + docs = [d for d in yaml.safe_load_all(manifest.read_text(encoding="utf-8")) if d] + (deployment,) = [d for d in docs if d["kind"] == "Deployment" and d["metadata"]["name"] == name] + return deployment["spec"]["template"]["spec"] + + def test_kiosk_assets_are_packaged_and_seeded() -> None: sysext = SYSEXT.read_text(encoding="utf-8") - tmpfiles = TMPFILES.read_text(encoding="utf-8") assert KIOSK_CONF.is_file() assert KIOSK_JS.is_file() assert KIOSK_CSS.is_file() - assert "path: files/k0s/kiosk" in sysext - assert "directory: kiosk-src" in sysext + assert {"kind": "local", "path": "files/k0s/kiosk", "directory": "kiosk-src"} in local_sources(SYSEXT) assert 'cp -a kiosk-src/. "${root}/share/k0s/kiosk/"' in sysext - assert "C+ /var/lib/k0s/kiosk - - - - /usr/share/k0s/kiosk" in tmpfiles - assert "kiosk-src" not in K0S_SYSEXT.read_text(encoding="utf-8"), ( + seeded = [rule for rule in tmpfiles(TMPFILES) if rule.path == "/var/lib/k0s/kiosk"] + assert [(rule.type, rule.argument) for rule in seeded] == [("C+", "/usr/share/k0s/kiosk")] + k0s_sources = [s["path"] for s in local_sources(K0S_SYSEXT)] + assert "files/k0s/sysext" in k0s_sources + assert "files/k0s/kiosk" not in k0s_sources, ( "the kiosk ships in the opt-in KubeStellar sysext, not with k0s" ) -def test_kiosk_tls_key_is_generated_per_node_not_shipped() -> None: +def test_kiosk_tls_key_is_generated_per_node_not_shipped(tmp_path: Path) -> None: sysext = SYSEXT.read_text(encoding="utf-8") - seed = SEED.read_text(encoding="utf-8") assert "openssl req" not in sysext, "a public sysext must not carry a private key" assert "key material in a public sysext" in sysext - assert "test -s /var/lib/k0s/kiosk/key.pem ||" in seed - assert "-keyout /var/lib/k0s/kiosk/key.pem" in seed + + scripts = [ + argv[2] + for argv in SystemdFile(SEED).commands() + if posixpath.basename(argv[0]) == "sh" and argv[1:2] == ["-c"] and "openssl" in argv[2] + ] + assert len(scripts) == 1, "expected one sh -c command generating the kiosk key" + assert "/var/lib/k0s/kiosk" in scripts[0] and "/usr/bin/openssl" in scripts[0] + kiosk = tmp_path / "kiosk" + kiosk.mkdir() + openssl = tmp_path / "openssl" + openssl.write_text( + '#!/bin/sh\necho "$@" >> "$CALLS"\n' + 'while [ $# -gt 0 ]; do case "$1" in -keyout|-out) : > "$2";; esac; shift; done\n', + encoding="utf-8", + ) + openssl.chmod(0o755) + calls = tmp_path / "calls" + script = scripts[0].replace("/var/lib/k0s/kiosk", str(kiosk)).replace("/usr/bin/openssl", str(openssl)) + + def seed() -> list[str]: + subprocess.run(["sh", "-c", script], env={"CALLS": str(calls), "PATH": "/usr/bin:/bin"}, check=True) + return calls.read_text(encoding="utf-8").splitlines() if calls.exists() else [] + + first = seed() + assert len(first) == 1 and f"-keyout {kiosk}/key.pem" in first[0] + assert ((kiosk / "key.pem").stat().st_mode & 0o077) == 0, "the private key must not be group/world readable" + assert ((kiosk / "cert.pem").stat().st_mode & 0o777) == 0o644 + (kiosk / "key.pem").write_text("existing node key", encoding="utf-8") + assert seed() == first, "an existing key must never be regenerated" def test_proxy_injects_only_csp_safe_same_origin_assets() -> None: @@ -95,40 +139,43 @@ def test_gate_waits_for_session_and_blocks_until_agent_health() -> None: def test_console_provides_local_and_oauth_login_options() -> None: - console = CONSOLE_MANIFEST.read_text(encoding="utf-8") + pod = deployment_pod(CONSOLE_MANIFEST, "kubestellar-console") + (console,) = [c for c in pod["containers"] if c["name"] == "console"] + env = {e["name"]: e for e in console["env"]} - assert "name: DEV_MODE" in console - assert 'value: "true"' in console - assert "name: ALLOW_DEV_MODE_IN_CLUSTER" in console - assert "hostPort:" not in console # #193: on first boot the console must read the local k0s cluster directly # (no connected kc-agent yet) and skip the onboarding questionnaire. # SKIP_ONBOARDING skips the questionnaire, not sign-in; sign-in is bypassed # by DEV_MODE/DEV_USER_LOGIN. - assert "name: SKIP_ONBOARDING" in console - assert "name: NO_LOCAL_AGENT" in console - assert "name: POD_NAMESPACE" in console - assert "serviceAccountName: kubestellar-console" in console - assert "name: GITHUB_CLIENT_ID" in console - assert "name: GITHUB_CLIENT_SECRET" in console - assert "name: kubestellar-console-github-oauth" in console - assert "key: client-id" in console - assert "key: client-secret" in console - assert "optional: true" in console + for flag in ("DEV_MODE", "ALLOW_DEV_MODE_IN_CLUSTER", "SKIP_ONBOARDING", "NO_LOCAL_AGENT"): + assert env[flag].get("value") == "true", flag + assert env["POD_NAMESPACE"].get("value") == "kubestellar-console" + assert pod["serviceAccountName"] == "kubestellar-console" + for name, key in (("GITHUB_CLIENT_ID", "client-id"), ("GITHUB_CLIENT_SECRET", "client-secret")): + assert env[name]["valueFrom"]["secretKeyRef"] == { + "name": "kubestellar-console-github-oauth", + "key": key, + "optional": True, + }, name + + # Only the kiosk proxy may be reachable from the node. + assert not pod.get("hostNetwork") + assert not [p for c in pod["containers"] for p in c.get("ports", []) if "hostPort" in p] + docs = [d for d in yaml.safe_load_all(CONSOLE_MANIFEST.read_text(encoding="utf-8")) if d] + assert all(d["spec"].get("type", "ClusterIP") == "ClusterIP" for d in docs if d["kind"] == "Service") def test_proxy_is_the_only_public_console_endpoint() -> None: - proxy = PROXY_MANIFEST.read_text(encoding="utf-8") - - assert "name: kubestellar-kiosk-proxy" in proxy - assert "hostPort: 8080" in proxy - assert "mountPath: /etc/kubestellar-kiosk" in proxy - assert "hostPath:\n path: /var/lib/k0s/kiosk" in proxy - assert "readOnly: true" in proxy - assert ( - "nginx@sha256:62223d644fa234c3a1cc785ee14242ec47a77364226f1c811d2f669f96dc2ac8" - in proxy - ) + pod = deployment_pod(PROXY_MANIFEST, "kubestellar-kiosk-proxy") + (proxy,) = pod["containers"] + + published = [(p.get("hostIP"), p["hostPort"]) for p in proxy["ports"] if "hostPort" in p] + assert published == [("127.0.0.1", 8080)], "publish the kiosk on loopback only" + assert re.fullmatch(r"docker\.io/library/nginx@sha256:[0-9a-f]{64}", proxy["image"]), proxy["image"] + (mount,) = [m for m in proxy["volumeMounts"] if m["mountPath"] == "/etc/kubestellar-kiosk"] + assert mount.get("readOnly") is True + (volume,) = [v for v in pod["volumes"] if v["name"] == mount["name"]] + assert volume["hostPath"]["path"] == "/var/lib/k0s/kiosk" def test_console_rbac_reads_only_the_local_cluster() -> None: From ec318709c1045bd06ec6cfb5a1f184d2f904e8a7 Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:39:43 -0500 Subject: [PATCH 06/12] test(repart): read partition definitions with the systemd parser configparser with strict=False kept only the last of a repeated key, so splitting MakeDirectories= over several lines, which systemd-repart accepts, would have dropped all but one directory from the check. Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/unit/test_repart_layout.py | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/tests/unit/test_repart_layout.py b/tests/unit/test_repart_layout.py index 69292f2d..21543523 100644 --- a/tests/unit/test_repart_layout.py +++ b/tests/unit/test_repart_layout.py @@ -13,11 +13,12 @@ from __future__ import annotations -import configparser from pathlib import Path import pytest +from _systemd import SystemdFile + REPO_ROOT = Path(__file__).resolve().parents[2] REPART_DIR = REPO_ROOT / "files" / "os" / "repart.d" SYSUPDATE_DIR = REPO_ROOT / "files" / "os" / "sysupdate.d" @@ -34,17 +35,11 @@ def load(path: Path) -> dict[str, str]: - parser = configparser.ConfigParser(strict=False, interpolation=None) - parser.optionxform = str - parser.read_string(path.read_text(encoding="utf-8")) - return dict(parser["Partition"]) + return {key: values[-1] for key, values in SystemdFile(path).sections["Partition"].items()} def transfer_target(name: str) -> dict[str, str]: - parser = configparser.ConfigParser(strict=False, interpolation=None) - parser.optionxform = str - parser.read_string((SYSUPDATE_DIR / name).read_text(encoding="utf-8")) - return dict(parser["Target"]) + return {key: values[-1] for key, values in SystemdFile(SYSUPDATE_DIR / name).sections["Target"].items()} def test_layout_files_and_types(): @@ -90,8 +85,9 @@ def test_root_is_persistent_xfs_with_mount_points(): root = load(REPART_DIR / "50-root.conf") assert root["Format"] == "xfs" assert root["FactoryReset"] == "yes" + directories = SystemdFile(REPART_DIR / "50-root.conf").words("Partition", "MakeDirectories") for directory in ("/usr", "/etc", "/efi", "/var"): - assert directory in root["MakeDirectories"].split() + assert directory in directories def test_boot_element_pins_slot_a_uuids_for_sysinstall(): From 05b99ffe079dfc69df43964a54f7e413de269cf7 Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:39:43 -0500 Subject: [PATCH 07/12] test: fail the k3s alias check when export-sysext is missing The negative check sliced the Justfile from the first "export-sysext:" to the next comment line, so a renamed or reorganised recipe could leave it checking an unrelated span. Parse the recipe body instead and require it to exist and export oci/k0s-sysext.bst before asserting that no k3s alias is emitted. Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/unit/test_sysext_export_contract.py | 24 +++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_sysext_export_contract.py b/tests/unit/test_sysext_export_contract.py index 2be9168b..e81d0117 100644 --- a/tests/unit/test_sysext_export_contract.py +++ b/tests/unit/test_sysext_export_contract.py @@ -1,3 +1,4 @@ +import re from pathlib import Path @@ -5,9 +6,24 @@ JUSTFILE = ROOT / "Justfile" +def recipe_body(name: str) -> list[str]: + lines = JUSTFILE.read_text(encoding="utf-8").splitlines() + header = re.compile(rf"{re.escape(name)}(\s[^:]*)?:(?!=)") + for index, line in enumerate(lines): + if header.match(line): + body = [] + for following in lines[index + 1 :]: + if following and not following[0].isspace(): + break + if following.strip(): + body.append(following.strip()) + return body + return [] + + def test_export_sysext_does_not_emit_legacy_k3s_alias() -> None: - justfile = JUSTFILE.read_text(encoding="utf-8") - start = justfile.index("export-sysext:") - end = justfile.index("\n# ", start) + body = recipe_body("export-sysext") - assert "k3s-" not in justfile[start:end] + assert body, "the export-sysext recipe is missing, so this check would pass vacuously" + assert any("oci/k0s-sysext.bst" in line for line in body), "export-sysext no longer exports k0s" + assert not [line for line in body if "k3s" in line] From 2c993c4d4bfa4e359e194fef147d2d85f4335034 Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:42:17 -0500 Subject: [PATCH 08/12] ci(unit): install node and shellcheck; allow user namespaces for bats The kiosk-gate behaviour tests need node and the firstboot helper lint needs shellcheck; both passed on main only because the runner image happens to ship them. Install them from the runner's Ubuntu archive. Every unit-tests run on main skips the 16 os-justfile bats tests ("unprivileged user+mount namespaces are unavailable"): Ubuntu's AppArmor policy restricts unprivileged user namespaces. Lift the restriction on the throwaway runner so the k8s recipe tests execute. Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/unit-tests.yml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 0541d830..9549f947 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -51,9 +51,17 @@ jobs: - name: Install dependencies run: | - sudo apt-get update && sudo apt-get install -y bats + sudo apt-get update && sudo apt-get install -y bats nodejs shellcheck pip install pytest pyyaml + # Ubuntu's AppArmor policy blocks unprivileged user namespaces; the + # os-justfile bats tests run the k8s recipe inside one. + - name: Allow unprivileged user namespaces + run: | + if [ -e /proc/sys/kernel/apparmor_restrict_unprivileged_userns ]; then + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + fi + - name: Set up just uses: taiki-e/install-action@4cef1412cce204788f482e778a0b9187f9626a29 # v2 with: From 865df733b6ec4412d0fce86baaf329e42a1bda25 Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:42:17 -0500 Subject: [PATCH 09/12] test: fail instead of skipping when CI lacks node or shellcheck node and shellcheck now come from session fixtures in conftest.py that skip a local run without the tool but fail when CI=true, so a runner image change can no longer turn the kiosk-gate and shellcheck tests into silent skips. Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/unit/conftest.py | 21 +++++++ .../test_firstboot_credentials_behavior.py | 6 +- tests/unit/test_kiosk_gate_behavior.py | 60 ++++++++----------- 3 files changed, 49 insertions(+), 38 deletions(-) diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index ff4122d0..c1299b6c 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -1,6 +1,8 @@ """Shared fixtures for the unit tests.""" import importlib.util +import os +import shutil import sys from pathlib import Path @@ -10,6 +12,25 @@ SCRIPT_PATH = REPO_ROOT / ".github" / "scripts" / "docs-checks.py" +def _required_tool(name: str) -> str: + path = shutil.which(name) + if path is None: + if os.environ.get("CI") == "true": + pytest.fail(f"{name} is not installed; .github/workflows/unit-tests.yml must install it") + pytest.skip(f"{name} is not installed") + return path + + +@pytest.fixture(scope="session") +def node() -> str: + return _required_tool("node") + + +@pytest.fixture(scope="session") +def shellcheck() -> str: + return _required_tool("shellcheck") + + def _load_module(): spec = importlib.util.spec_from_file_location("docs_checks", SCRIPT_PATH) module = importlib.util.module_from_spec(spec) diff --git a/tests/unit/test_firstboot_credentials_behavior.py b/tests/unit/test_firstboot_credentials_behavior.py index b989cf8f..2727f21d 100644 --- a/tests/unit/test_firstboot_credentials_behavior.py +++ b/tests/unit/test_firstboot_credentials_behavior.py @@ -10,7 +10,6 @@ from __future__ import annotations import os -import shutil import subprocess from pathlib import Path @@ -48,9 +47,8 @@ def test_helper_is_bash_that_passes_syntax() -> None: subprocess.run(["bash", "-n", str(HELPER)], check=True) -@pytest.mark.skipif(shutil.which("shellcheck") is None, reason="shellcheck not installed") -def test_helper_is_shellcheck_clean_at_warning_level() -> None: - subprocess.run(["shellcheck", "-S", "warning", str(HELPER)], check=True) +def test_helper_is_shellcheck_clean_at_warning_level(shellcheck: str) -> None: + subprocess.run([shellcheck, "-S", "warning", str(HELPER)], check=True) def test_all_five_credentials_write_what_systemd_firstboot_would(tmp_path: Path) -> None: diff --git a/tests/unit/test_kiosk_gate_behavior.py b/tests/unit/test_kiosk_gate_behavior.py index 99f13a3c..244fd07e 100644 --- a/tests/unit/test_kiosk_gate_behavior.py +++ b/tests/unit/test_kiosk_gate_behavior.py @@ -15,31 +15,23 @@ modal on every tick, or if the keydown trap fires when no gate is present. These tests run the real script in node against a stub DOM -(``kiosk_gate_harness.mjs``) and assert what it actually does. +(``kiosk_gate_harness.mjs``) and assert what it actually does. Without node +they skip locally and fail in CI (the ``node`` fixture in conftest.py). """ import json -import shutil import subprocess from pathlib import Path -import pytest - ROOT = Path(__file__).resolve().parents[2] SCRIPT = ROOT / "files" / "k0s" / "kiosk" / "kiosk-gate.js" HARNESS = Path(__file__).with_name("kiosk_gate_harness.mjs") -NODE = shutil.which("node") - -pytestmark = pytest.mark.skipif( - NODE is None, reason="node is required to execute kiosk-gate.js" -) - -def run_gate(**scenario) -> dict: +def run_gate(node: str, **scenario) -> dict: """Execute kiosk-gate.js under the stub DOM and return its observed effects.""" proc = subprocess.run( - [NODE, str(HARNESS), str(SCRIPT), json.dumps(scenario)], + [node, str(HARNESS), str(SCRIPT), json.dumps(scenario)], capture_output=True, text=True, check=True, @@ -48,8 +40,8 @@ def run_gate(**scenario) -> dict: return json.loads(proc.stdout) -def test_gate_appears_when_a_session_exists_but_the_agent_is_unreachable() -> None: - result = run_gate(session="true", health="throw") +def test_gate_appears_when_a_session_exists_but_the_agent_is_unreachable(node: str) -> None: + result = run_gate(node, session="true", health="throw") assert result["afterLoad"]["gate"] is True assert result["insertPosition"] == "beforeend" @@ -60,56 +52,56 @@ def test_gate_appears_when_a_session_exists_but_the_agent_is_unreachable() -> No assert "-allowed-origins https://console.example" in result["gateHTML"] -def test_gate_appears_when_the_agent_answers_unhealthy() -> None: +def test_gate_appears_when_the_agent_answers_unhealthy(node: str) -> None: # A reachable-but-failing agent is as useless as an absent one, so a # non-2xx answer must gate just like a refused connection. - result = run_gate(session="true", health="error") + result = run_gate(node, session="true", health="error") assert result["afterLoad"]["gate"] is True -def test_no_gate_while_the_agent_is_healthy() -> None: - result = run_gate(session="true", health="ok") +def test_no_gate_while_the_agent_is_healthy(node: str) -> None: + result = run_gate(node, session="true", health="ok") assert result["afterLoad"]["gate"] is False assert result["afterTick"]["gate"] is False -def test_no_gate_before_the_user_has_a_session() -> None: +def test_no_gate_before_the_user_has_a_session(node: str) -> None: # Pre-login the console shows its own sign-in flow; gating there would # bury it behind an agent instruction the visitor cannot act on yet. - result = run_gate(session=None, health="throw") + result = run_gate(node, session=None, health="throw") assert result["afterLoad"]["gate"] is False # No session means no reason to probe the agent at all. assert result["afterLoad"]["fetchCalls"] == 0 -def test_unreadable_storage_is_treated_as_no_session() -> None: +def test_unreadable_storage_is_treated_as_no_session(node: str) -> None: # Private-mode browsers throw on localStorage access; the script must fail # open rather than gate every visitor forever. - result = run_gate(storage="throws", health="throw") + result = run_gate(node, storage="throws", health="throw") assert result["afterLoad"]["gate"] is False assert result["afterLoad"]["fetchCalls"] == 0 -def test_gate_is_removed_once_the_agent_becomes_healthy() -> None: - result = run_gate(session="true", health="throw", health2="ok") +def test_gate_is_removed_once_the_agent_becomes_healthy(node: str) -> None: + result = run_gate(node, session="true", health="throw", health2="ok") assert result["afterLoad"]["gate"] is True assert result["afterTick"]["gate"] is False -def test_repeated_failures_do_not_stack_duplicate_gates() -> None: - result = run_gate(session="true", health="throw") +def test_repeated_failures_do_not_stack_duplicate_gates(node: str) -> None: + result = run_gate(node, session="true", health="throw") assert result["afterTick"]["fetchCalls"] == 2, "poll did not probe again" assert result["afterTick"]["inserts"] == 1, "a second modal was stacked" -def test_agent_health_is_probed_without_credentials() -> None: - result = run_gate(session="true", health="ok") +def test_agent_health_is_probed_without_credentials(node: str) -> None: + result = run_gate(node, session="true", health="ok") assert result["fetchURLs"] == ["http://127.0.0.1:8585/health"] * 2 # The agent is a local daemon: sending console cookies to it is neither @@ -117,14 +109,14 @@ def test_agent_health_is_probed_without_credentials() -> None: assert result["fetchOptions"] == [{"credentials": "omit"}] * 2 -def test_agent_health_is_polled_on_an_interval() -> None: - result = run_gate(session="true", health="ok") +def test_agent_health_is_polled_on_an_interval(node: str) -> None: + result = run_gate(node, session="true", health="ok") assert result["timers"] == [2000] -def test_keystrokes_outside_the_gate_are_swallowed_while_it_is_up() -> None: - result = run_gate(session="true", health="throw") +def test_keystrokes_outside_the_gate_are_swallowed_while_it_is_up(node: str) -> None: + result = run_gate(node, session="true", health="throw") assert result["keydownOutside"] is True # Typing inside the dialog (copying the brew command, tabbing) must work. @@ -132,9 +124,9 @@ def test_keystrokes_outside_the_gate_are_swallowed_while_it_is_up() -> None: assert {"type": "keydown", "capture": True} in result["listeners"] -def test_keystrokes_pass_through_when_no_gate_is_up() -> None: +def test_keystrokes_pass_through_when_no_gate_is_up(node: str) -> None: # The trap is registered unconditionally at load, so it must no-op when # the console is usable — otherwise a healthy kiosk is unusable. - result = run_gate(session="true", health="ok") + result = run_gate(node, session="true", health="ok") assert result["keydownOutside"] is False From 91094f55ba023c2e3ff47c61a805efb834d432e4 Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:42:17 -0500 Subject: [PATCH 10/12] test(bats): fail the k8s recipe tests in CI instead of skipping them A missing user namespace or just skipped all 16 os-justfile tests, and on CI that happened on every run. Keep the skip for local runs but fail when CI=true. Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/unit/os-justfile_test.bats | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/unit/os-justfile_test.bats b/tests/unit/os-justfile_test.bats index a40d906b..d0fb225c 100644 --- a/tests/unit/os-justfile_test.bats +++ b/tests/unit/os-justfile_test.bats @@ -11,12 +11,22 @@ # Results that must outlive the namespace (the call log) are copied back # into BATS_TEST_TMPDIR, which is outside both tmpfs masks. +# skip_unless_ci -- skip locally, but fail in CI (CI=true), where a +# skip would silently drop every k8s recipe test from the gate. +skip_unless_ci() { + if [ "${CI:-}" = true ]; then + echo "CI must run this test, but: $1" >&2 + return 1 + fi + skip "$1" +} + setup() { if ! unshare --map-root-user --mount true 2>/dev/null; then - skip "unprivileged user+mount namespaces are unavailable" + skip_unless_ci "unprivileged user+mount namespaces are unavailable" fi if ! command -v just >/dev/null 2>&1; then - skip "just is not installed" + skip_unless_ci "just is not installed" fi REPO_ROOT="$(cd "${BATS_TEST_DIRNAME}/../.." && pwd)" From bef596fb9c59e09e3fc330f361763eb6a2154ae1 Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:43:40 -0500 Subject: [PATCH 11/12] build(just): run bats from a pinned container when it is not installed The README promises podman and just are enough, but `just test-unit` failed without a local bats. Fall back to bats/bats 1.14.0 pinned by index digest, mounted read-only, and forward CI so the os-justfile tests still refuse to skip in CI. CONTRIBUTING.md notes the pytest prerequisites and the fallback. Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CONTRIBUTING.md | 1 + Justfile | 13 +++++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index acdc9dcb..3b975e59 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,6 +8,7 @@ Thanks for contributing. This repository is optimized for AI coding agents first 2. AI agents must query the `projectbluefin` MCP server (`search_knowledge(query, limit)`, `get_factory_status()`, `get_work_queue()`) before investigating or implementing. 3. Make the smallest change that solves the problem. 4. Run `just validate` on every change that touches the element graph. + `just test-unit` runs pytest (needs `python3` with `pytest` and `pyyaml`) and bats; without a local `bats` it runs bats from a digest-pinned container through `podman`. 5. Validate documentation changes with `python3 .github/scripts/docs-checks.py`. 6. Use Conventional Commits (`feat:`, `fix:`, `docs:`, `ci:`, `chore:`). 7. Attribution trailers are required on all AI-assisted commits: diff --git a/Justfile b/Justfile index 0eb280ac..714b9865 100644 --- a/Justfile +++ b/Justfile @@ -6,6 +6,8 @@ default: # Same bst2 container image FSDK/dakota CI uses -- pinned by SHA. export oras_image := env("ORAS_IMAGE", "ghcr.io/oras-project/oras:v1.3.4") export bst2_image := env("BST2_IMAGE", "registry.gitlab.com/freedesktop-sdk/infrastructure/freedesktop-sdk-docker-images/bst2:64eb0b4930d57a92710822898fb73af6cc1ae35d") +# bats for `just test-unit` when none is installed -- pinned by digest. +export bats_image := env("BATS_IMAGE", "docker.io/bats/bats:1.14.0@sha256:5322b877351fda0cc435de8c6116de7d0a2ec79d7c680132a0ef329a633bc66f") # Prefix for podman calls: empty when rootless podman works, "sudo" otherwise. sudo_cmd := if `podman info >/dev/null 2>&1 && echo 1 || echo 0` == "1" { "" } else { "sudo" } @@ -68,11 +70,18 @@ validate: gen-dev-keys python3 .github/scripts/check-renovate-series.py just bst show --deps all oci/bluefin-server-image.bst oci/k0s-sysext.bst oci/kubestellar-sysext.bst oci/zfs-sysext.bst oci/kubeadm-sysext.bst -# Run the unit test suite (pytest + bats). +# Run the unit test suite (pytest + bats; bats from a container if not installed). [group('dev')] test-unit: + #!/usr/bin/env bash + set -euo pipefail python3 -m pytest tests/unit -q - bats tests/unit + if command -v bats >/dev/null 2>&1; then + exec bats tests/unit + fi + echo "==> bats is not installed; running it from ${bats_image}" >&2 + exec {{sudo_cmd}} podman run --rm --security-opt label=disable -e CI \ + -v "{{justfile_directory()}}:/code:ro" -w /code "${bats_image}" tests/unit # ── Build ───────────────────────────────────────────────────────────── # Build the k0s and KubeStellar systemd-sysext images. From bf6f35375620b63599b4777089b32bd748b0b8bb Mon Sep 17 00:00:00 2001 From: Jeffrey Sica Date: Tue, 29 Sep 2026 00:44:18 -0500 Subject: [PATCH 12/12] test: add a pytest config that reports skips testpaths keeps a bare `pytest` on tests/unit (tests/e2e needs selenium and a live console), and -ra lists every skip with its reason in the summary instead of a bare "s". Assisted-by: Claude Opus 5.5 via GitHub Copilot Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pytest.ini | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 pytest.ini diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 00000000..b2a3b038 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +testpaths = tests/unit +addopts = -ra