"""Windows optional features, the facts a role's CVE precondition is held against (NetOrk/netork#2898). ``Win32_OptionalFeature`` lists every feature of the image, on a client and a server, under the names ``Get-WindowsOptionalFeature`` uses; its ``InstallState`` is 1 enabled, 2 disabled, 3 absent, 4 unknown. The fixture is what the script emits. """ from __future__ import annotations import json from pathlib import Path from typing import Any import pytest from napalm_device_types import WindowsFeaturesMixin from napalm_windows import WindowsDriver from napalm_windows import windows_features as mod FIXTURE = Path(__file__).parent / "fixtures" / "synthetic" / "windows_features.json" class FakeHost: def __init__(self, answer: str) -> None: self.answer = answer self.sent: list[str] = [] self.is_open = True def run(self, script: str) -> str: self.sent.append(script) return self.answer def close(self) -> None: self.is_open = False def _read(answer: Any = None) -> dict[str, Any]: driver = WindowsDriver("win", "u", "p") text = FIXTURE.read_text() if answer is None else answer host = FakeHost(text if isinstance(text, str) else json.dumps(text)) driver._transport = host # type: ignore[assignment] reading = driver.get_windows_features() assert host.sent == [mod._PS_WINDOWS_FEATURES] return dict(reading) def test_the_driver_declares_the_contract(): assert issubclass(WindowsDriver, WindowsFeaturesMixin) def test_every_feature_comes_with_its_state(): assert _read()["features"] == [ {"name": "SMB1Protocol", "state": "disabled"}, {"name": "MSMQ-Server", "state": "enabled"}, {"name": "IIS-WebServerRole", "state": "enabled"}, {"name": "Microsoft-Hyper-V", "state": "absent"}, {"name": "DNS-Server-Full-Role", "state": "unknown"}, {"name": "Printing-PrintToPDFServices-Features", "state": "enabled"}, ] def test_a_state_outside_the_four_is_unknown_and_a_nameless_entry_is_dropped(): raw = [ {"name": "X", "state": 9}, {"name": "", "state": 1}, "junk", {"name": "Y", "state": None}, ] assert _read(raw)["features"] == [ {"name": "X", "state": "unknown"}, {"name": "Y", "state": "unknown"}, ] def test_one_feature_arrives_bare_and_is_still_a_list(): assert _read({"name": "SMB1Protocol", "state": 1})["features"] == [ {"name": "SMB1Protocol", "state": "enabled"} ] def test_no_feature_at_all_is_a_reading_that_went_wrong(): # Every image has features; none read is not "none switched on". with pytest.raises(ValueError, match="features"): _read("") with pytest.raises(ValueError, match="features"): _read([]) def test_the_script_asks_cim_not_dism(): script = mod._PS_WINDOWS_FEATURES assert "Win32_OptionalFeature" in script assert "$ErrorActionPreference = 'Stop'" in script assert "-InputObject @(" in script