"""Repair runs on Windows: SFC, DISM and Microsoft Defender over PowerShell Remoting (NetOrk/netork#2899). A fake transport replays what a run's script emits, one output object per line of tests/fixtures/synthetic/.txt, through ``run_streaming``; the scripts end with a ``napalm-exit-code:`` line, or say ``napalm-not-available:`` where the tool is missing. The fixtures are written from Microsoft's documented output, not recorded from a host. """ from __future__ import annotations from collections.abc import Callable from pathlib import Path import pytest from napalm.base.exceptions import ConnectionClosedException from napalm_device_types import HostRepairMixin, offered_host_repairs from napalm_windows import WindowsDriver from napalm_windows import repairs as mod from napalm_windows.transport import PowerShellError FIXTURES = Path(__file__).parent / "fixtures" / "synthetic" def _fixture(name: str) -> list[str]: return (FIXTURES / name).read_text().split("\n")[:-1] class FakeTransport: """Replays *items* as the output objects of the next streamed script.""" def __init__(self, items: list[str], *, error: Exception | None = None) -> None: self.items = items self.error = error self.scripts: list[str] = [] self.limits: list[float] = [] self.is_open = True def run_streaming( self, script: str, on_output: Callable[[str], None], *, limit: float ) -> list[str]: self.scripts.append(script) self.limits.append(limit) for item in self.items: on_output(item) if self.error is not None: raise self.error return list(self.items) def close(self) -> None: self.is_open = False def _driver(items: list[str], **kwargs) -> tuple[WindowsDriver, FakeTransport]: transport = FakeTransport(items, **kwargs) driver = WindowsDriver("win01", "admin", "secret") driver._transport = transport # type: ignore[assignment] return driver, transport class TestCatalog: def test_the_driver_carries_the_contract(self): assert issubclass(WindowsDriver, HostRepairMixin) def test_offers_the_checks_and_the_antimalware_runs_not_the_repairs(self): # sfc /scannow and DISM /RestoreHealth wait for a real-host test (#2899). assert offered_host_repairs(WindowsDriver) == [ "verify_system_files", "check_component_store", "update_antimalware_signatures", "scan_antimalware", ] class TestToolLines: def test_an_object_is_one_line(self): assert mod.tool_lines("Verification 52% complete.") == ["Verification 52% complete."] def test_utf16_text_read_as_bytes_loses_its_nuls(self): # sfc writes UTF-16 to a redirected stdout; decoded byte by byte, each # character is followed by a NUL. raw = "Windows Resource Protection".encode("utf-16-le").decode("latin-1") assert "\x00" in raw assert mod.tool_lines(raw) == ["Windows Resource Protection"] def test_a_byte_order_mark_is_dropped(self): assert mod.tool_lines("Beginning system scan.") == ["Beginning system scan."] def test_carriage_returns_split_progress_into_lines(self): assert mod.tool_lines("Verification 1% complete.\rVerification 2% complete.\r\n") == [ "Verification 1% complete.", "Verification 2% complete.", ] def test_blank_lines_and_trailing_spaces_go(self): assert mod.tool_lines(" \r\n\nresult ") == ["result"] class TestVerifySystemFiles: def test_streams_the_lines_and_succeeds_on_exit_code_zero(self): driver, transport = _driver(_fixture("sfc_verifyonly.txt")) seen: list[str] = [] result = driver.verify_system_files(log=seen.append) assert result["success"] is True assert result["exit_code"] == 0 assert seen[0] == "Beginning system scan. This process will take some time." assert seen[-1] == "Windows Resource Protection did not find any integrity violations." assert not any(line.startswith("napalm-") for line in seen) assert result["output"] == "\n".join(seen) def test_runs_sfc_verifyonly_decoded_as_utf16(self): driver, transport = _driver(_fixture("sfc_verifyonly.txt")) driver.verify_system_files() script = transport.scripts[0] assert "'/verifyonly'" in script assert "System32\\sfc.exe" in script assert "[System.Text.Encoding]::Unicode" in script assert "/scannow" not in script assert transport.limits == [mod.SFC_LIMIT] def test_utf16_output_with_nuls_reads_as_text(self): items = [ line.encode("utf-16-le").decode("latin-1") for line in _fixture("sfc_verifyonly.txt")[:-1] ] + ["napalm-exit-code:0"] driver, _ = _driver(items) result = driver.verify_system_files() assert "did not find any integrity violations" in result["output"] assert "\x00" not in result["output"] def test_a_non_zero_exit_code_fails_with_the_last_lines(self): items = [ "Beginning system scan. This process will take some time.", "Windows Resource Protection could not start the repair service.", "napalm-exit-code:1", ] driver, _ = _driver(items) result = driver.verify_system_files() assert result["success"] is False assert result["exit_code"] == 1 assert result["error"].endswith("could not start the repair service.") def test_a_missing_tool_is_not_available_not_an_error(self): driver, _ = _driver(["napalm-not-available:sfc.exe"]) result = driver.verify_system_files() assert result == { "success": False, "output": "", "exit_code": None, "error": "sfc.exe is not available on this host", } def test_without_log_it_still_returns_the_output(self): driver, _ = _driver(_fixture("sfc_verifyonly.txt")) assert "Verification 100% complete." in driver.verify_system_files()["output"] class TestCheckComponentStore: def test_scans_health_in_english_and_succeeds(self): driver, transport = _driver(_fixture("dism_scanhealth.txt")) seen: list[str] = [] result = driver.check_component_store(log=seen.append) assert result["success"] is True assert "No component store corruption detected." in seen[-2] script = transport.scripts[0] assert "System32\\Dism.exe" in script assert "'/Online /Cleanup-Image /ScanHealth /English'" in script assert "RestoreHealth" not in script assert transport.limits == [mod.DISM_LIMIT] def test_an_hresult_exit_code_fails_in_hex(self): driver, _ = _driver(_fixture("dism_scanhealth_failed.txt")) result = driver.check_component_store() assert result["success"] is False assert result["exit_code"] == 0x800F081F assert result["error"].startswith("DISM /ScanHealth ended with exit code 0x800F081F:") assert "dism.log" in result["error"] class TestAntimalwareSignatures: def test_updates_and_reports_the_versions(self): driver, transport = _driver(_fixture("defender_signature_update.txt")) seen: list[str] = [] result = driver.update_antimalware_signatures(log=seen.append) assert result["success"] is True assert seen == [ "Signatures before: 1.401.1234.0, updated 2026-11-27 06:12 UTC", "Signatures after: 1.401.1502.0, updated 2026-12-01 08:41 UTC", ] script = transport.scripts[0] assert "Update-MpSignature" in script assert "Get-Command -Name Update-MpSignature" in script assert transport.limits == [mod.SIGNATURE_LIMIT] def test_a_host_without_defender_says_so(self): driver, _ = _driver(["napalm-not-available:Microsoft Defender Antivirus"]) result = driver.update_antimalware_signatures() assert result["success"] is False assert result["error"] == "Microsoft Defender Antivirus is not available on this host" def test_a_refused_update_fails_with_its_reason(self): items = [ "Signatures before: 1.401.1234.0, updated 2026-11-27 06:12 UTC", "Update-MpSignature failed: Virus and spyware definitions update was completed with errors.", "Signatures after: 1.401.1234.0, updated 2026-11-27 06:12 UTC", "napalm-exit-code:1", ] driver, _ = _driver(items) result = driver.update_antimalware_signatures() assert result["success"] is False assert "completed with errors" in result["error"] class TestScanAntimalware: def test_a_quick_scan_reports_what_it_found(self): driver, transport = _driver(_fixture("defender_quick_scan.txt")) seen: list[str] = [] result = driver.scan_antimalware(log=seen.append) assert result["success"] is True assert "Threats detected: 1" in seen script = transport.scripts[0] assert "Start-MpScan -ScanType QuickScan" in script assert transport.limits == [mod.QUICK_SCAN_LIMIT] def test_a_full_scan_has_its_own_limit(self): driver, transport = _driver(["napalm-exit-code:0"]) driver.scan_antimalware(quick=False) assert "Start-MpScan -ScanType FullScan" in transport.scripts[0] assert transport.limits == [mod.FULL_SCAN_LIMIT] class TestLimit: @pytest.mark.parametrize( ("run", "bound"), [ (lambda d, **kw: d.verify_system_files(**kw), mod.SFC_LIMIT), (lambda d, **kw: d.check_component_store(**kw), mod.DISM_LIMIT), (lambda d, **kw: d.update_antimalware_signatures(**kw), mod.SIGNATURE_LIMIT), (lambda d, **kw: d.scan_antimalware(**kw), mod.QUICK_SCAN_LIMIT), (lambda d, **kw: d.scan_antimalware(False, **kw), mod.FULL_SCAN_LIMIT), ], ) def test_a_callers_limit_tightens_the_bound_never_widens_it(self, run, bound): driver, transport = _driver(["napalm-exit-code:0"]) run(driver, limit=600) run(driver, limit=bound * 2) run(driver) assert transport.limits == [600, bound, bound] class TestCutOff: def test_a_run_past_its_limit_fails_with_what_it_printed(self): driver, _ = _driver( ["Beginning system scan.", "Verification 40% complete."], error=TimeoutError("The script did not end within 3600 seconds"), ) result = driver.verify_system_files() assert result["success"] is False assert result["exit_code"] is None assert result["error"].startswith("sfc /verifyonly ended without an exit code:") assert "Verification 40% complete." in result["error"] assert result["error"].endswith("did not end within 3600 seconds") def test_an_error_the_script_wrote_fails_the_run(self): driver, _ = _driver([], error=PowerShellError("Access is denied.")) result = driver.check_component_store() assert result["success"] is False assert result["error"].endswith("Access is denied.") def test_an_unreadable_exit_code_is_none(self): driver, _ = _driver(["done", "napalm-exit-code:"]) assert driver.verify_system_files()["exit_code"] is None def test_a_closed_connection_raises(self): driver = WindowsDriver("win01", "admin", "secret") with pytest.raises(ConnectionClosedException): driver.verify_system_files() @pytest.mark.parametrize( "script", [ mod._PS_SFC_VERIFY, mod._PS_DISM_SCAN, mod._PS_SIGNATURE_UPDATE, mod._PS_QUICK_SCAN, mod._PS_FULL_SCAN, ], ) def test_every_script_follows_the_conventions(script): assert "$ErrorActionPreference = 'Stop'" in script assert "napalm-exit-code:" in script assert "napalm-not-available:" in script # No restart and no restore point as a side effect of a run (#2899). for forbidden in ("Restart-Computer", "Checkpoint-Computer", "shutdown"): assert forbidden not in script