Files
napalm-openwrt/tests/unit/test_firmware.py
T
Christian Manivong 530f04055c feat(firmware): offer the newest release of the line and install it with owut (NetOrk/netork#2615)
get_firmware_offer() looks the device's release line up in the attended
sysupgrade server's overview.json, fetched at most once a day per server.
start_firmware_upgrade() runs owut upgrade detached from the session, and
get_update_progress() follows its log until owut hands the image to sysupgrade.
2026-11-17 11:06:32 +01:00

270 lines
10 KiB
Python

"""The firmware OpenWrt's sysupgrade server offers, and installing it with owut.
netOrk upgrades an OpenWrt device to the newest release of its own release line
instead of piling package upgrades into the overlay (NetOrk/netork#2615). The
offer comes from the attended sysupgrade server's ``overview.json`` (its shape
here is the real one, cut down to what matters); owut on the device builds the
image there and runs sysupgrade.
"""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import pytest
from napalm_device_types import CommandResult
from napalm_openwrt import firmware_mixin
from napalm_openwrt.openwrt import OpenWrtDriver
OVERVIEW = {
"latest": ["25.12.6", "24.10.8"],
"branches": {
"SNAPSHOT": {
"enabled": True,
"snapshot": True,
"versions": ["SNAPSHOT"],
"name": "SNAPSHOT",
"targets": ["ath79/generic", "ramips/mt7621"],
},
"25.12": {
"enabled": True,
"snapshot": False,
"versions": ["25.12.6", "25.12.5", "25.12.2", "25.12.0", "25.12.0-rc5"],
"name": "25.12",
"targets": ["ath79/generic", "ramips/mt7621"],
},
"24.10": {
"enabled": True,
"snapshot": False,
"versions": ["24.10.8", "24.10.2", "24.10.0"],
"name": "24.10",
"targets": ["ath79/generic", "ramips/mt7621"],
},
"23.05": {
"enabled": True,
"snapshot": False,
"versions": ["23.05.6", "23.05.3", "23.05.0-rc4"],
"name": "23.05",
"targets": ["ath79/generic"],
},
},
"upstream_url": "https://downloads.openwrt.org",
}
def _release(version: str, target: str = "ath79/generic") -> str:
return (
"DISTRIB_ID='OpenWrt'\n"
f"DISTRIB_RELEASE='{version}'\n"
"DISTRIB_REVISION='r32802-f505120278'\n"
f"DISTRIB_TARGET='{target}'\n"
"DISTRIB_ARCH='mips_24kc'\n"
f"DISTRIB_DESCRIPTION='OpenWrt {version} r32802-f505120278'\n"
)
@pytest.fixture(autouse=True)
def _no_cached_overviews():
firmware_mixin._OVERVIEWS.clear()
yield
firmware_mixin._OVERVIEWS.clear()
@pytest.fixture
def driver():
with patch("napalm_openwrt.openwrt.ConnectHandler"):
drv = OpenWrtDriver(hostname="192.0.2.1", username="root", password="")
drv.device = MagicMock()
yield drv
def _device(driver, version: str, *, owut: bool = True, server: str = "", target="ath79/generic"):
"""The device answers the offer's one reading; every command is kept."""
sent: list[str] = []
def run(command, *, privileged=False, timeout=60, stdin=None):
sent.append(command)
out = _release(version, target) + f"__ASU_URL={server}\n" + ("__OWUT=1\n" if owut else "")
return CommandResult(exit_code=0, stdout=out, stderr="")
driver.run_command = run
return sent
def _offer(driver, fetched=OVERVIEW):
with patch.object(firmware_mixin, "_fetch_json", return_value=fetched) as fetch:
return driver.get_firmware_offer(), fetch
class TestFirmwareOffer:
def test_the_newest_point_release_of_its_own_line_is_offered(self, driver):
_device(driver, "25.12.2")
offer, _ = _offer(driver)
assert offer == {
"current_version": "25.12.2",
"latest_version": "25.12.6",
"newer": True,
"installable": True,
}
def test_a_device_on_the_newest_release_is_offered_nothing_newer(self, driver):
_device(driver, "25.12.6")
offer, _ = _offer(driver)
assert offer is not None
assert offer["newer"] is False
assert offer["latest_version"] == "25.12.6"
def test_a_later_release_line_is_named_but_not_offered_as_the_upgrade(self, driver):
_device(driver, "24.10.2")
offer, _ = _offer(driver)
assert offer is not None
assert offer["latest_version"] == "24.10.8"
assert offer["latest_major_version"] == "25.12.6"
assert offer["newer"] is True
def test_a_release_candidate_is_offered_the_release(self, driver):
_device(driver, "25.12.0-rc5")
offer, _ = _offer(driver)
assert offer is not None
assert (offer["latest_version"], offer["newer"]) == ("25.12.6", True)
def test_release_candidates_are_not_offered_over_a_release(self, driver):
overview = {
**OVERVIEW,
"branches": {
"25.12": {**OVERVIEW["branches"]["25.12"], "versions": ["25.12.7-rc1", "25.12.6"]}
},
}
_device(driver, "25.12.2")
offer, _ = _offer(driver, overview)
assert offer is not None
assert offer["latest_version"] == "25.12.6"
def test_without_owut_it_cannot_be_installed_yet(self, driver):
_device(driver, "25.12.2", owut=False)
offer, _ = _offer(driver)
assert offer is not None
assert offer["installable"] is False
def test_a_release_before_owut_existed_never_says_installable(self, driver):
"""owut needs 24.10 or later; on 23.05 there is nothing to install it with."""
_device(driver, "23.05.3", owut=False)
offer, _ = _offer(driver)
assert offer is not None
assert "installable" not in offer
assert offer["latest_version"] == "23.05.6"
def test_a_snapshot_has_no_offer(self, driver):
_device(driver, "SNAPSHOT")
assert _offer(driver)[0] is None
def test_a_target_the_line_no_longer_builds_has_no_offer(self, driver):
_device(driver, "23.05.3", target="ramips/mt7621")
assert _offer(driver)[0] is None
def test_a_server_that_does_not_answer_is_no_offer(self, driver):
_device(driver, "25.12.2")
with patch.object(firmware_mixin, "_fetch_json", side_effect=OSError("timed out")):
assert driver.get_firmware_offer() is None
def test_the_server_is_asked_once_for_every_device(self, driver):
_device(driver, "25.12.2")
_, fetch = _offer(driver)
with patch.object(firmware_mixin, "_fetch_json", return_value=OVERVIEW) as again:
assert driver.get_firmware_offer() is not None
fetch.assert_called_once_with("https://sysupgrade.openwrt.org/json/v1/overview.json")
again.assert_not_called()
def test_a_failed_answer_is_not_asked_again_at_once(self, driver):
_device(driver, "25.12.2")
with patch.object(firmware_mixin, "_fetch_json", side_effect=OSError("down")) as fetch:
driver.get_firmware_offer()
driver.get_firmware_offer()
fetch.assert_called_once()
def test_the_server_the_device_is_set_to_is_asked(self, driver):
_device(driver, "25.12.2", server="https://asu.example.net/")
_, fetch = _offer(driver)
fetch.assert_called_once_with("https://asu.example.net/json/v1/overview.json")
def test_a_server_that_is_not_http_is_not_asked(self, driver):
_device(driver, "25.12.2", server="file:///etc/shadow")
_, fetch = _offer(driver)
fetch.assert_called_once_with("https://sysupgrade.openwrt.org/json/v1/overview.json")
class TestStartFirmwareUpgrade:
def _run(self, driver, result: CommandResult):
calls: list[tuple[str, bool]] = []
def run(command, *, privileged=False, timeout=60, stdin=None):
calls.append((command, privileged))
return result
driver.run_command = run
return calls
def test_owut_upgrades_to_the_version_detached_from_the_session(self, driver):
calls = self._run(driver, CommandResult(exit_code=0, stdout="", stderr=""))
driver.start_firmware_upgrade("25.12.6")
((command, privileged),) = calls
assert privileged is True
assert "owut upgrade --version-to 25.12.6" in command
assert 'trap "" HUP' in command
assert "</dev/null" in command
assert command.rstrip().endswith("&'") or command.rstrip().endswith("&")
@pytest.mark.parametrize("version", ["25.12.6; reboot", "SNAPSHOT", "", "25.12"])
def test_anything_but_a_release_version_is_refused(self, driver, version):
calls = self._run(driver, CommandResult(exit_code=0, stdout="", stderr=""))
with pytest.raises(ValueError):
driver.start_firmware_upgrade(version)
assert calls == []
def test_a_refusal_is_raised_with_the_device_reason(self, driver):
self._run(driver, CommandResult(exit_code=4, stdout="", stderr="owut is not installed\n"))
with pytest.raises(RuntimeError, match="owut is not installed"):
driver.start_firmware_upgrade("25.12.6")
def test_only_root_can_start_it(self, driver):
driver.username = "admin"
with pytest.raises(RuntimeError):
driver.start_firmware_upgrade("25.12.6")
class TestUpdateProgress:
def _log(self, driver, log: str | None):
def run(command, *, privileged=False, timeout=60, stdin=None):
if log is None:
return CommandResult(exit_code=1, stdout="", stderr="")
return CommandResult(exit_code=0, stdout=log, stderr="")
driver.run_command = run
def test_no_upgrade_since_the_device_started_is_idle(self, driver):
self._log(driver, None)
assert driver.get_update_progress() == {"state": "idle", "log": ""}
def test_an_upgrade_without_an_end_is_running(self, driver):
self._log(driver, "Requesting build\nBuild status: queued\n")
progress = driver.get_update_progress()
assert progress["state"] == "running"
assert progress["log"] == "Requesting build\nBuild status: queued"
def test_installing_the_image_is_its_end(self, driver):
"""sysupgrade stops every process, the wrapper's status line included."""
self._log(driver, "Verified\nInstalling /tmp/firmware.bin and rebooting...\n")
assert driver.get_update_progress()["state"] == "done"
def test_a_status_other_than_zero_failed(self, driver):
self._log(driver, "Package build checks reveal errors, can't proceed\n__OWUT_RC=1\n")
progress = driver.get_update_progress()
assert progress["state"] == "failed"
assert "__OWUT_RC" not in progress["log"]
def test_an_end_without_installing_failed(self, driver):
"""owut ends with 0 when there was nothing to change: nothing was installed."""
self._log(driver, "There are no changes to upgrade (see '--force')\n__OWUT_RC=0\n")
assert driver.get_update_progress()["state"] == "failed"