"""Tests for the WireView Pro II firmware check + DFU flasher (nvcurve/wireview_firmware.py). Standalone (no pytest required): python tests/test_wireview_firmware.py Also works under pytest. Covers the Intel-HEX parser (including checksum verification), the BuildStruct identity extraction, the compatibility verdicts (product alias, Noctua floor, version/build comparison), the bundled image, the dfu-util flasher (mocked subprocess), and the bootloader command on the serial device. """ import os import subprocess import sys import tempfile from datetime import datetime from unittest import mock sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) from nvcurve import wireview as wv # noqa: E402 from nvcurve import wireview_firmware as wf # noqa: E402 PASS = 0 FAIL = 0 def check(name: str, cond: bool) -> None: global PASS, FAIL if cond: PASS += 1 print(f" PASS {name}") else: FAIL += 1 print(f" FAIL {name}") def _hex_line(addr: int, data: bytes, record_type: int = 0) -> str: """One Intel-HEX line (count, address, type, data) with a correct checksum (the count byte is part of the sum).""" payload = bytes([len(data)]) + addr.to_bytes(2, "big") + bytes([record_type]) + data checksum = (-sum(payload)) & 0xFF return ":" + (payload + bytes([checksum])).hex().upper() def _write_hex(tmp: str, lines: list[str]) -> str: path = os.path.join(tmp, "fw.hex") with open(path, "w") as f: f.write("\n".join(lines) + "\n") return path def _build_struct_lines(vendor=0xEF, product=0x05, version=0x05, build="TG-WV-PRO2-FW_20260902_0741") -> list[str]: """HEX lines placing a BuildStruct at image offset 192 (base 0). The leading byte at offset 0 anchors min(address) so the BuildStruct lands exactly 192 bytes above the image base.""" lines = [_hex_line(0x0000, bytes([0x00]), record_type=4)] # linear addr 0 lines.append(_hex_line(0x0000, bytes([0x00]))) lines.append(_hex_line(wf.BUILD_STRUCT_OFFSET, bytes([vendor, product, version]))) build_bytes = build.encode().ljust(wf.BUILD_INFO_LENGTH, b"\x00") lines.append( _hex_line(wf.BUILD_STRUCT_OFFSET + wf.BUILD_INFO_OFFSET_IN_BUILD_STRUCT, build_bytes) ) lines.append(":00000001FF") # EOF return lines # ── Build timestamp ─────────────────────────────────────────────────────────── def test_parse_build_timestamp(): t = wf.parse_build_timestamp("TG-WV-PRO2-FW_20260902_0741") check("timestamp parsed", t == datetime(2026, 9, 2, 7, 41)) check("timestamp None input", wf.parse_build_timestamp(None) is None) check("timestamp empty input", wf.parse_build_timestamp("") is None) check("timestamp no match", wf.parse_build_timestamp("TG-WV-PRO2-FW") is None) check( "timestamp trailing digit rejected", wf.parse_build_timestamp("TG-WV-PRO2-FW_20260902_07411") is None, ) check( "timestamp invalid date", wf.parse_build_timestamp("TG-WV-PRO2-FW_20261399_0741") is None, ) # ── Intel-HEX parser ────────────────────────────────────────────────────────── def test_hex_parser(): with tempfile.TemporaryDirectory() as tmp: # Linear base 0x08000000, two data records with a gap, then EOF. path = _write_hex( tmp, [ _hex_line(0x0000, bytes([0x08, 0x00]), record_type=4), _hex_line(0x0000, bytes([0x00, 0x60])), _hex_line(0x0005, bytes([0xAA])), ":00000001FF", ], ) mem = wf._parse_hex_to_memory_map(path) check( "hex memory map", mem == {0x08000000: 0x00, 0x08000001: 0x60, 0x08000005: 0xAA}, ) base, image = wf.read_firmware_image(path) check("hex base address", base == 0x08000000) check("hex image size", len(image) == 6) check("hex gap padded 0xFF", image == bytes([0x00, 0x60, 0xFF, 0xFF, 0xFF, 0xAA])) # Extended segment address (type 2): base = value << 4. path2 = _write_hex( tmp, [ _hex_line(0x0000, bytes([0x00, 0x10]), record_type=2), _hex_line(0x0000, bytes([0x42])), ":00000001FF", ], ) mem2 = wf._parse_hex_to_memory_map(path2) check("hex segment address", mem2 == {0x100: 0x42}) # A bad checksum must be rejected — a corrupt image must never flash. bad = _hex_line(0x0000, bytes([0x00, 0x60])) bad = bad[:-2] + ("00" if bad[-2:] != "00" else "01") path3 = _write_hex(tmp, [bad]) try: wf._parse_hex_to_memory_map(path3) check("hex bad checksum rejected", False) except wf.FirmwareImageError: check("hex bad checksum rejected", True) # Non-hex garbage in a record is rejected. path4 = _write_hex(tmp, [":10000000ZZ000000000000000000000000000000000000"]) try: wf._parse_hex_to_memory_map(path4) check("hex garbage rejected", False) except wf.FirmwareImageError: check("hex garbage rejected", True) # EOF-only file: no data records. path5 = _write_hex(tmp, [":00000001FF"]) try: wf.read_firmware_info(path5) check("hex no data records", False) except wf.FirmwareImageError as exc: check("hex no data records", "data records" in str(exc)) # Missing file. try: wf.read_firmware_info(os.path.join(tmp, "nope.hex")) check("hex missing file", False) except wf.FirmwareImageError as exc: check("hex missing file", "not found" in str(exc)) def test_read_firmware_info(): with tempfile.TemporaryDirectory() as tmp: path = _write_hex(tmp, _build_struct_lines()) info = wf.read_firmware_info(path) check("info vendor", info.vendor_id == 0xEF) check("info product", info.product_id == 0x05) check("info version", info.version == 5) check("info build string", info.build_string == "TG-WV-PRO2-FW_20260902_0741") check("info build time", info.build_time == datetime(2026, 9, 2, 7, 41)) # A build string without a timestamp parses but has no build time. path2 = _write_hex(tmp, _build_struct_lines(build="TG-WV-PRO2-FW")) info2 = wf.read_firmware_info(path2) check("info build time absent", info2.build_time is None) def test_bundled_image(): """The shipped TG-WV-PRO2-FW.hex must parse to the known identity.""" path = wf.bundled_firmware_path() check("bundled exists", path.is_file()) if not path.is_file(): return info = wf.read_firmware_info(path) check("bundled vendor", info.vendor_id == 0xEF) check("bundled product", info.product_id == wf.PRODUCT_ID_PRO2) check("bundled version", info.version == 5) check("bundled build", info.build_string == "TG-WV-PRO2-FW_20260902_0741") check("bundled build time", info.build_time == datetime(2026, 9, 2, 7, 41)) base, image = wf.read_firmware_image(path) check("bundled base", base == 0x08000000) check("bundled size plausible", 64 * 1024 <= len(image) <= 256 * 1024) # The first bytes are the STM32 vector table (initial SP at 0x20006000). check("bundled first bytes", image[:2] == bytes([0x00, 0x60])) # ── Compatibility verdicts ──────────────────────────────────────────────────── def _img(version=5, build="TG-WV-PRO2-FW_20260902_0741", vendor=0xEF, product=0x05) -> wf.FirmwareImageInfo: return wf.FirmwareImageInfo(vendor, product, version, build) def test_compatibility_verdicts(): pro2 = (wf.VENDOR_ID_THERMAL_GRIZZLY, wf.PRODUCT_ID_PRO2) noctua = (wf.VENDOR_ID_THERMAL_GRIZZLY, wf.PRODUCT_ID_PRO2_NOCTUA) t_new = datetime(2026, 9, 2, 7, 41) t_old = datetime(2026, 1, 1, 0, 0) # Version dominates. check("verdict newer version", wf.evaluate(_img(version=6), *pro2, 5, t_old) == wf.VERDICT_NEWER) check("verdict downgrade version", wf.evaluate(_img(version=4), *pro2, 5, t_new) == wf.VERDICT_DOWNGRADE) # Equal version: build timestamp decides. check("verdict newer build", wf.evaluate(_img(build="TG-WV-PRO2-FW_20261001_0000"), *pro2, 5, t_old) == wf.VERDICT_NEWER) check("verdict downgrade build", wf.evaluate(_img(build="TG-WV-PRO2-FW_20250101_0000"), *pro2, 5, t_new) == wf.VERDICT_DOWNGRADE) check("verdict same", wf.evaluate(_img(), *pro2, 5, t_new) == wf.VERDICT_SAME) # Unknown sides. check("verdict unknown device version", wf.evaluate(_img(), *pro2, None, t_new) == wf.VERDICT_UNKNOWN) check("verdict unknown device build", wf.evaluate(_img(), *pro2, 5, None) == wf.VERDICT_UNKNOWN) check("verdict unknown image build", wf.evaluate(_img(build="TG-WV-PRO2-FW"), *pro2, 5, t_new) == wf.VERDICT_UNKNOWN) # Product matching (with the Noctua alias). check("verdict product mismatch", wf.evaluate(_img(product=0x99), *pro2, 5, t_new) == wf.VERDICT_PRODUCT_MISMATCH) check("verdict vendor mismatch", wf.evaluate(_img(vendor=0x12), *pro2, 5, t_new) == wf.VERDICT_PRODUCT_MISMATCH) check("verdict unknown device vendor", wf.evaluate(_img(), 0, 0, 5, t_new) == wf.VERDICT_PRODUCT_MISMATCH) check("verdict noctua alias matches pro2 image", wf.evaluate(_img(product=0x05), *noctua, 5, t_old) == wf.VERDICT_NEWER) # Noctua floor: an image predating 2026-09-02 never goes onto product 6. check("verdict too old for noctua", wf.evaluate(_img(build="TG-WV-PRO2-FW_20260801_0000"), *noctua, 5, t_old) == wf.VERDICT_TOO_OLD_FOR_NOCTUA) check("verdict noctua floor date ok", wf.evaluate(_img(build="TG-WV-PRO2-FW_20260902_0741"), *noctua, 5, t_old) == wf.VERDICT_NEWER) check("verdict noctua no build date too old", wf.evaluate(_img(build="TG-WV-PRO2-FW"), *noctua, 5, t_old) == wf.VERDICT_TOO_OLD_FOR_NOCTUA) # The floor only applies to Noctua devices: the same old image is a plain # downgrade on a Pro II. check("verdict pro2 old image is downgrade", wf.evaluate(_img(build="TG-WV-PRO2-FW_20260801_0000"), *pro2, 5, t_new) == wf.VERDICT_DOWNGRADE) # ── dfu-util flasher (mocked subprocess) ────────────────────────────────────── class _FakeStdout: def __init__(self, text: str): self._chars = list(text) def read(self, n: int) -> str: if not self._chars: return "" out = self._chars[:n] del self._chars[:n] return "".join(out) class _FakeStderr: def __init__(self, text: str): self._text = text def read(self) -> str: return self._text class _FakeProc: def __init__(self, stdout: str = "", stderr: str = "", returncode: int = 0, wait_error: Exception | None = None): self.stdout = _FakeStdout(stdout) self.stderr = _FakeStderr(stderr) self.returncode = returncode self._wait_error = wait_error self.killed = False def wait(self, timeout: float | None = None) -> int: if self._wait_error is not None: raise self._wait_error return self.returncode def kill(self) -> None: self.killed = True def test_dfu_util_version(): ok = mock.Mock(returncode=0, stdout="dfu-util 0.11\nCopyright…\n") with mock.patch.object(wf.subprocess, "run", return_value=ok): check("dfu-util version", wf.DfuUtilFlasher.dfu_util_version() == "dfu-util 0.11") with mock.patch.object(wf.subprocess, "run", side_effect=FileNotFoundError("dfu-util")): check("dfu-util missing", wf.DfuUtilFlasher.dfu_util_version() is None) broken = mock.Mock(returncode=1, stdout="") with mock.patch.object(wf.subprocess, "run", return_value=broken): check("dfu-util broken", wf.DfuUtilFlasher.dfu_util_version() is None) def test_wait_for_dfu_device(): found = mock.Mock(returncode=0, stdout="Found DFU: [0483:df11] (STM32…)\n") with mock.patch.object(wf.subprocess, "run", return_value=found): check("dfu device found", wf.DfuUtilFlasher.wait_for_dfu_device(0.5)) absent = mock.Mock(returncode=0, stdout="No DFU capable devices found.\n") with mock.patch.object(wf.subprocess, "run", return_value=absent): check("dfu device absent", not wf.DfuUtilFlasher.wait_for_dfu_device(0.6)) def test_dfu_flash(): progress: list[float] = [] out = ( "Downloading file: /tmp/fw.bin\n" "\r 0% |\r\n" "\r 25% |\r\n" "\r 50% |\r\n" "\r100% |\r\n" "File downloaded successfully\n" ) with tempfile.TemporaryDirectory() as tmp: bin_path = os.path.join(tmp, "fw.bin") with mock.patch.object(wf.subprocess, "Popen", return_value=_FakeProc(stdout=out, returncode=0)) as popen: wf.DfuUtilFlasher.flash(bin_path, 0x08000000, progress_cb=progress.append) check("flash no error", True) check("flash progress", progress == [0.0, 0.25, 0.5, 1.0]) args = popen.call_args.args[0] check("flash args", args == ["dfu-util", "-d 0483:df11", "-a", "0", "-s 0x08000000:leave", "-D", bin_path]) # Exit 74 (EX_IOERR) after a completed download is treated as success. with mock.patch.object(wf.subprocess, "Popen", return_value=_FakeProc( stdout="File downloaded successfully\n", returncode=74)): wf.DfuUtilFlasher.flash(bin_path, 0x08000000) check("flash exit 74 tolerated", True) # A real failure raises with dfu-util's output. with mock.patch.object(wf.subprocess, "Popen", return_value=_FakeProc( stderr="dfu-util: no DFU capable USB device found\n", returncode=1)): try: wf.DfuUtilFlasher.flash(bin_path, 0x08000000) check("flash failure raises", False) except wf.FirmwareFlashError as exc: check("flash failure raises", "no DFU capable USB device" in str(exc)) check("flash failure exit code", "exit 1" in str(exc)) # A hang is killed and reported as a timeout. hung = _FakeProc(wait_error=subprocess.TimeoutExpired("dfu-util", 300)) with mock.patch.object(wf.subprocess, "Popen", return_value=hung): try: wf.DfuUtilFlasher.flash(bin_path, 0x08000000, timeout_s=0.1) check("flash timeout raises", False) except wf.FirmwareFlashError as exc: check("flash timeout raises", "did not finish" in str(exc)) check("flash timeout kills", hung.killed) # A missing binary is reported, not raised as OSError. with mock.patch.object(wf.subprocess, "Popen", side_effect=FileNotFoundError("dfu-util")): try: wf.DfuUtilFlasher.flash(bin_path, 0x08000000) check("flash missing binary", False) except wf.FirmwareFlashError as exc: check("flash missing binary", "Could not run dfu-util" in str(exc)) # ── Bootloader command ──────────────────────────────────────────────────────── def _build_info_struct(product_name: str, build_info: str) -> bytes: """BuildStruct: VendorData(3) + ProductName(32) + BuildInfo(32) + NameLength(1).""" return ( bytes([0xEF, 0x05, 5]) + product_name.encode().ljust(32, b"\x00") + build_info.encode().ljust(32, b"\x00") + bytes([len(product_name)]) ) def test_enter_bootloader(): """enter_bootloader sends the top-level 0xF1 command once and closes the connection (the device re-enumerates as 0483:df11 afterwards).""" import pty import queue import threading master, slave = pty.openpty() slave_path = os.ttyname(slave) received: queue.Queue = queue.Queue() def run(): while True: try: cmd = os.read(master, 1) except OSError: return if not cmd: return if cmd[0] == wv.CMD_BOOTLOADER: received.put(cmd) continue resp = { wv.CMD_READ_VENDOR_DATA: bytes([0xEF, 0x05, 5]), wv.CMD_READ_CONFIG: bytes([0, 0, 1, 0]), wv.CMD_READ_UID: bytes(12), wv.CMD_READ_BUILD_INFO: _build_info_struct( "WireView Pro II", "TG-WV-PRO2-FW_20260902_0741" ), }.get(cmd[0]) if resp: try: os.write(master, resp) except OSError: return t = threading.Thread(target=run, daemon=True) t.start() try: dev = wv.WireViewSerialDevice(slave_path) check("boot: connect", dev.connect()) check("boot: enter", dev.enter_bootloader()) check("boot: disconnected", not dev.connected) try: got = received.get(timeout=2) check("boot: 0xF1 sent", got == b"\xF1") except queue.Empty: check("boot: 0xF1 sent", False) # A second call on a closed device fails without touching the port. check("boot: second call fails", not dev.enter_bootloader()) finally: os.close(master) t.join(timeout=2) def test_hwmon_enter_bootloader(): """The hwmon transport cannot enter the bootloader (wireviewd owns the port, and nvcurve does not speak the daemon protocol).""" dev = wv.WireViewHwmonDevice("/sys/class/hwmon/hwmon99") check("hwmon enter_bootloader unsupported", dev.enter_bootloader() is False) def main() -> int: print("wireview firmware tests:") test_parse_build_timestamp() test_hex_parser() test_read_firmware_info() test_bundled_image() test_compatibility_verdicts() test_dfu_util_version() test_wait_for_dfu_device() test_dfu_flash() test_enter_bootloader() test_hwmon_enter_bootloader() print(f"\n{PASS} passed, {FAIL} failed") return 1 if FAIL else 0 if __name__ == "__main__": sys.exit(main())