From eaa08ae7e3080f535b797563f44dd15a052d78e7 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sun, 1 Nov 2026 21:44:51 +0100 Subject: [PATCH] fix(packages): read install_package's success from the exit status install_package searched the output of `... || true` for words such as "failed", the pattern uninstall_package left behind for netork#267: a postinst that only mentions a failure read as a failed install, and a failure phrased without those words read as success. It now runs through _sudo_status like the removal and falls back to the keywords only when the channel gave no exit status. The ruff findings named in the issue are gone since the driver adopted the standard; strict mypy for linux.py is held by the quality ratchet, and the None-vs-dict package contract is NAPALM/napalm-device-types#36. Closes #4 --- CHANGELOG.md | 4 ++++ napalm_linux/linux.py | 45 +++++++++++++++++-------------------- tests/quality_baseline.json | 2 +- tests/test_linux.py | 45 +++++++++++++++++++++++++++++++++++++ 4 files changed, 70 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8008b90..386e2ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `get_arp_table()` reports an unknown age as `-1.0` (napalm-device-types' `ARP_AGE_UNKNOWN`) instead of `0.0`, which means "confirmed just now": `ip neigh` has no age, and a STALE entry may be hours old (NetOrk/netork#1327). +- `install_package()` reports success by the package manager's exit status, as + `uninstall_package()` already does (#4). It used to search the output for words like + "failed": an install whose postinst merely mentioned a failure read as failed, and a + failure that used none of the words read as success. ## [0.15.1] - 2026-10-23 diff --git a/napalm_linux/linux.py b/napalm_linux/linux.py index c8438ec..3cf3de4 100644 --- a/napalm_linux/linux.py +++ b/napalm_linux/linux.py @@ -1455,39 +1455,33 @@ class LinuxDriver( return packages def install_package(self, name: str) -> dict[str, Any]: - """Install a package by name. Returns ``{"success": bool, "output": str}``.""" + """Install a package by name. Returns ``{"success": bool, "output": str}``. + + Success is the package manager's exit status, as for ``uninstall_package``.""" from shlex import quote as _q safe = _q(name) pm = self._pkg_manager if pm == "apt": - raw = self._sudo( - f"DEBIAN_FRONTEND=noninteractive apt-get install -y {safe} 2>&1 || true" - ) + cmd = f"DEBIAN_FRONTEND=noninteractive apt-get install -y {safe} 2>&1" elif pm in ("dnf", "yum"): - raw = self._sudo(f"{pm} install -y {safe} 2>&1 || true") + cmd = f"{pm} install -y {safe} 2>&1" elif pm == "apk": - raw = self._sudo(f"apk add {safe} 2>&1 || true") + cmd = f"apk add {safe} 2>&1" elif pm == "pacman": - raw = self._sudo(f"pacman -S --noconfirm {safe} 2>&1 || true") + cmd = f"pacman -S --noconfirm {safe} 2>&1" else: return {"success": False, "output": f"Unsupported package manager: {pm}"} - low = raw.lower() - success = not any( - kw in low - for kw in ( - "error:", - "failed", - "no packages", - "not found", - "unable to locate", - "no match", - ) - ) - return {"success": success, "output": raw.strip()} + raw, rc = self._sudo_status(cmd) + failed = self._package_command_failed(raw, rc, self._INSTALL_FAILED) + return {"success": not failed, "output": raw.strip()} + + #: Words in a package manager's output that mean an install did not happen. + #: Only consulted when the exit status is unknown; see ``_package_command_failed``. + _INSTALL_FAILED = ("error:", "failed", "no packages", "not found", "unable to locate") #: Words in a package manager's output that mean it did not do the job. - #: Only consulted when the exit status is unknown; see ``_uninstall_failed``. + #: Only consulted when the exit status is unknown; see ``_package_command_failed``. _UNINSTALL_FAILED = ("error:", "failed", "not found", "is not installed", "no packages") def uninstall_package(self, name: str, purge: bool = False) -> dict[str, Any]: @@ -1533,16 +1527,17 @@ class LinuxDriver( return {"success": False, "output": f"Unsupported package manager: {pm}"} raw, rc = self._sudo_status(cmd) - failed = self._uninstall_failed(raw, rc) + failed = self._package_command_failed(raw, rc, self._UNINSTALL_FAILED) if failed and pm == "apt": forced, forced_rc = self._sudo_status(f"dpkg --purge --force-all {safe} 2>&1") raw = f"{raw.strip()}\n--- dpkg --purge --force-all ---\n{forced.strip()}" - failed = self._uninstall_failed(forced, forced_rc) + failed = self._package_command_failed(forced, forced_rc, self._UNINSTALL_FAILED) return {"success": not failed, "output": raw.strip()} - def _uninstall_failed(self, output: str, rc: int | None = None) -> bool: + @staticmethod + def _package_command_failed(output: str, rc: int | None, keywords: tuple[str, ...]) -> bool: """Whether the package manager did not do the job. The exit status decides whenever there is one (netork#267): it is the @@ -1566,7 +1561,7 @@ class LinuxDriver( low = output.lower() if any(line.lstrip().startswith("e: ") for line in low.splitlines()): return True - return any(kw in low for kw in self._UNINSTALL_FAILED) + return any(kw in low for kw in keywords) def get_available_updates(self) -> list[UpdateDict]: if self._pkg_manager == "apt": diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index c558b17..fc08f32 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -22,7 +22,7 @@ "napalm_linux.linux" ], "python_file_lines": { - "napalm_linux/linux.py": 2265 + "napalm_linux/linux.py": 2260 }, "untyped_public": [] } diff --git a/tests/test_linux.py b/tests/test_linux.py index 97bd1d8..dda30af 100644 --- a/tests/test_linux.py +++ b/tests/test_linux.py @@ -1276,6 +1276,51 @@ class TestUninstallExitStatus: assert result["success"] is False +class TestInstallExitStatus: + """``install_package`` decides by the exit status too (#4), as removal does + since netork#267: keywords in the output were guesswork in both directions.""" + + def test_a_non_zero_exit_is_a_failure_whatever_the_output_says(self, driver): + driver._pkg_manager = "dnf" + _mock_send(driver, _with_rc("Last metadata expiration check: 0:01:02 ago.", 1)) + + result = driver.install_package("curl") + + assert result["success"] is False + + def test_a_zero_exit_is_a_success_even_if_the_output_mentions_failure(self, driver): + """A postinst that cannot start a unit in a container says "Failed" and + apt still installs the package.""" + _mock_send( + driver, + _with_rc( + "Setting up nginx (1.26.3-3) ...\n" + "Failed to start nginx.service: System has not been booted with systemd.", + 0, + ), + ) + + result = driver.install_package("nginx") + + assert result["success"] is True + + def test_the_install_command_keeps_its_exit_status(self, driver): + _mock_send(driver, _with_rc("Setting up curl ...", 0)) + + result = driver.install_package("curl") + + sent = driver._device.send_command.call_args[0][0] + assert "|| true" not in sent + assert result["output"] == "Setting up curl ..." + + def test_without_an_exit_status_the_output_is_read(self, driver): + _mock_send(driver, _with_rc("E: Unable to locate package nosuchpkg", -1)) + + result = driver.install_package("nosuchpkg") + + assert result["success"] is False + + # --------------------------------------------------------------------------- # get_kernel_facts -- the command and its parse live in napalm-device-types # ---------------------------------------------------------------------------