From 58ee77425030f98c30b09a4d389d9859301aa7eb Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Mon, 2 Nov 2026 08:34:29 +0100 Subject: [PATCH] fix(packages): decide install/uninstall success by exit status install_package and uninstall_package searched the output for keywords. opkg's dependency failure ("Collected errors:") contains none of them and read as success; a successful install naming a "failed" file read as a failure. Append the exit-status marker and let the status alone decide. Closes #28 --- CHANGELOG.md | 5 ++ napalm_openwrt/packages_mixin.py | 35 ++++----- tests/unit/test_packages.py | 120 +++++++++++++++++++++++++++++++ 3 files changed, 144 insertions(+), 16 deletions(-) create mode 100644 tests/unit/test_packages.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 251a416..7d72002 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,11 @@ recorded here; their history is the git log. - `get_lldp_neighbors()` and `get_lldp_neighbors_detail()` report every neighbour on a port (a phone with a PC behind it, a switch without LLDP of its own); only the last one came back, mixed with fields of the others (#9). +- `install_package()` and `uninstall_package()` report a failed install or removal + as failed: only the package manager's exit status decides. They used to search the + output for words like "error:", so an opkg dependency failure ("Collected errors:", + "Cannot install package …") came back as a success, and a successful install of a + package whose name contains "failed" as a failure (#28). ## [0.7.0] - 2026-10-23 diff --git a/napalm_openwrt/packages_mixin.py b/napalm_openwrt/packages_mixin.py index 65cdbfb..8b31f76 100644 --- a/napalm_openwrt/packages_mixin.py +++ b/napalm_openwrt/packages_mixin.py @@ -15,6 +15,8 @@ from __future__ import annotations import re from typing import Any +from napalm_openwrt.system_mixin import _RC_MARKER, _status_result + class OpenWrtPackageMixin: """Mixin providing package-management NAPALM methods.""" @@ -200,30 +202,31 @@ class OpenWrtPackageMixin: lines.append(part) return "\n".join(lines) + def _run_pkg_command(self, command: str) -> dict[str, Any]: + """Run a package-manager command; only its exit status decides ``success``.""" + raw = self._send_command(f"{command} 2>&1; echo {_RC_MARKER}$?") + return _status_result(self._clean_pkg_output(raw), command) + 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}``. + + Only the package manager's exit status decides ``success``. + """ import shlex safe_name = shlex.quote(name) if self._pm_type() == "apk": - raw = self._send_command(f"apk add {safe_name} 2>&1") - else: - raw = self._send_command(f"opkg install {safe_name} 2>&1") - out = self._clean_pkg_output(raw) - low = out.lower() - success = not any(kw in low for kw in ("error:", "failed", "not found", "unknown package")) - return {"success": success, "output": out} + return self._run_pkg_command(f"apk add {safe_name}") + return self._run_pkg_command(f"opkg install {safe_name}") def uninstall_package(self, name: str) -> dict[str, Any]: - """Remove a package by name. Returns ``{"success": bool, "output": str}``.""" + """Remove a package by name. Returns ``{"success": bool, "output": str}``. + + Only the package manager's exit status decides ``success``. + """ import shlex safe_name = shlex.quote(name) if self._pm_type() == "apk": - raw = self._send_command(f"apk del {safe_name} 2>&1") - else: - raw = self._send_command(f"opkg remove {safe_name} 2>&1") - out = self._clean_pkg_output(raw) - low = out.lower() - success = not any(kw in low for kw in ("error:", "failed", "not found", "unknown package")) - return {"success": success, "output": out} + return self._run_pkg_command(f"apk del {safe_name}") + return self._run_pkg_command(f"opkg remove {safe_name}") diff --git a/tests/unit/test_packages.py b/tests/unit/test_packages.py new file mode 100644 index 0000000..98a913d --- /dev/null +++ b/tests/unit/test_packages.py @@ -0,0 +1,120 @@ +"""install_package / uninstall_package: only the exit status decides (#28). + +Searching the output for words like "error:" or "failed" misreads both ways: +opkg's dependency failure says "Collected errors:" (not "error:") and a +successful install may name a file containing "failed". +""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +import pytest + +from napalm_openwrt.openwrt import OpenWrtDriver + +OPKG_DEPENDS_FAILED = ( + "Installing lldpd (1.0.17-1) to root...\n" + "Collected errors:\n" + " * satisfy_dependencies_for: Cannot satisfy the following dependencies for lldpd:\n" + " * \tlibevent2-7 (>= 2.1.12)\n" + " * opkg_install_cmd: Cannot install package lldpd.\n" + "__OWRT_RC=255\n" +) +APK_ADD_OK_NAMING_FAILED = ( + "(1/1) Installing failed-login-notify (1.0-r1)\nOK: 12 MiB in 140 packages\n__OWRT_RC=0\n" +) + + +@pytest.fixture +def driver(): + with patch("napalm_openwrt.openwrt.ConnectHandler"): + drv = OpenWrtDriver(hostname="192.168.1.1", username="root", password="") + drv.device = MagicMock() + yield drv + + +def _answer(driver, pm: str, reply: str) -> list[str]: + """Answer the package-manager probe with *pm* and everything else with *reply*.""" + sent: list[str] = [] + + def send(cmd, **kwargs): + sent.append(cmd) + if cmd.startswith("command -v apk"): + return "/usr/bin/apk" if pm == "apk" else "__no_apk__" + return reply + + driver._send_command = send + return sent + + +class TestInstallPackage: + def test_opkg_dependency_failure_is_no_success(self, driver): + sent = _answer(driver, "opkg", OPKG_DEPENDS_FAILED) + + result = driver.install_package("lldpd") + + assert result["success"] is False + assert "Cannot install package lldpd" in result["output"] + assert "__OWRT_RC" not in result["output"] + assert sent[-1] == "opkg install lldpd 2>&1; echo __OWRT_RC=$?" + + def test_success_whose_output_says_failed_is_success(self, driver): + sent = _answer(driver, "apk", APK_ADD_OK_NAMING_FAILED) + + result = driver.install_package("failed-login-notify") + + assert result == { + "success": True, + "output": "(1/1) Installing failed-login-notify (1.0-r1)\nOK: 12 MiB in 140 packages", + } + assert sent[-1] == "apk add failed-login-notify 2>&1; echo __OWRT_RC=$?" + + def test_marker_behind_a_progress_bar_is_still_read(self, driver): + _answer(driver, "apk", "(1/1) Installing lldpd (1.0.17-r1)\n 100% ####\r__OWRT_RC=0\n") + + assert driver.install_package("lldpd")["success"] is True + + def test_output_without_a_status_is_no_success(self, driver): + _answer(driver, "apk", "") + + result = driver.install_package("lldpd") + + assert result["success"] is False + assert result["output"] + + def test_failure_without_output_names_the_status(self, driver): + _answer(driver, "apk", "__OWRT_RC=99\n") + + result = driver.install_package("lldpd") + + assert result["success"] is False + assert "status 99" in result["output"] + + +class TestUninstallPackage: + def test_opkg_remove_that_failed_is_no_success(self, driver): + sent = _answer( + driver, + "opkg", + "Collected errors:\n * print_dependents_warning: Package lldpd is depended upon by:\n" + "__OWRT_RC=255\n", + ) + + result = driver.uninstall_package("lldpd") + + assert result["success"] is False + assert "depended upon" in result["output"] + assert sent[-1] == "opkg remove lldpd 2>&1; echo __OWRT_RC=$?" + + def test_apk_del_that_worked(self, driver): + sent = _answer( + driver, + "apk", + "(1/1) Purging failed-login-notify (1.0-r1)\nOK: 11 MiB in 139 packages\n__OWRT_RC=0\n", + ) + + result = driver.uninstall_package("failed-login-notify") + + assert result["success"] is True + assert sent[-1] == "apk del failed-login-notify 2>&1; echo __OWRT_RC=$?" -- 2.54.1