feat(access-point): SSID settings, radio channels, VLAN names, the AP configuration and DHCP leases through declared methods (NetOrk/netork#695)
push_ssid_config, set_radio_channels and set_vlan_name run as checked uci steps (#35): a refused step raises naming itself and reverts what was staged. set_radio_channels replaces the undeclared push_radio_channel. apply_ap_config takes napalm-device-types' ApConfigDict and the parts the caller found different and writes them as one detached script: the builder netOrk had in _uci_builders.py, moved here. It answers which parts it wrote and which it could not, whether the AP restarts, and the script with every passphrase masked. A passphrase part now writes the key. get_dhcp_leases reads dnsmasq's lease file. Needs napalm-device-types 4.54.0; CI pre-installs it from its branch until it is on PyPI.
This commit is contained in:
1 parent
dd3e3f1543
commit
634bc9c793
18 files changed
+2108
-40
No files matched your search
@@ -0,0 +1,552 @@
|
||||
"""``apply_ap_config``: an access point's desired configuration as one UCI script (NetOrk/netork#695).
|
||||
|
||||
netOrk built this script itself, from its AP profile, and uploaded it through the
|
||||
driver's ``run_command``. The builders moved here unchanged in what they write; what
|
||||
comes in is napalm-device-types' ``ApConfigDict`` and the parts the caller found
|
||||
different. ``uci -q show wireless`` is the shape of ``test_wireless_writes``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import ApConfigDict, ApSsidConfigDict, CommandResult
|
||||
|
||||
from napalm_openwrt.ap_config import MASK, build_script, masked
|
||||
from napalm_openwrt.ap_config._common import Radios, radios_of
|
||||
from napalm_openwrt.uci_steps import parse_uci_show
|
||||
from tests.unit.test_wireless_writes import SHOW, WIRELESS, _driver
|
||||
|
||||
RADIOS = Radios(r5g="radio1", r2g="radio0")
|
||||
PSK = "correct horse battery"
|
||||
|
||||
|
||||
def _ssid(**fields: object) -> ApSsidConfigDict:
|
||||
ssid: dict[str, object] = {
|
||||
"name": "Corp",
|
||||
"vlan_id": 30,
|
||||
"bands": ["2.4 GHz", "5 GHz"],
|
||||
"encryption": "psk2",
|
||||
"key": PSK,
|
||||
"hidden": False,
|
||||
"enabled": True,
|
||||
"client_isolation": False,
|
||||
"max_clients": None,
|
||||
"disassoc_low_ack": None,
|
||||
"max_inactivity": None,
|
||||
"acl_mode": "off",
|
||||
"acl_macs": [],
|
||||
"fast_transition": False,
|
||||
}
|
||||
ssid.update(fields)
|
||||
return ssid # type: ignore[return-value]
|
||||
|
||||
|
||||
def _config(**fields: object) -> ApConfigDict:
|
||||
config: dict[str, object] = {
|
||||
"country_code": "DE",
|
||||
"htmode_5g": "VHT80",
|
||||
"htmode_2g": "HT20",
|
||||
"syslog_host": "192.0.2.10",
|
||||
"syslog_port": 1514,
|
||||
"web_ui": True,
|
||||
"ssh_port": 22,
|
||||
"ssh_password_auth": False,
|
||||
"management_vlan_id": 10,
|
||||
"management_untagged": False,
|
||||
"bridge_stp": True,
|
||||
"mobility_domain": "a1b2",
|
||||
"ft_over_ds": True,
|
||||
"ssids": [_ssid()],
|
||||
}
|
||||
config.update(fields)
|
||||
return config # type: ignore[return-value]
|
||||
|
||||
|
||||
def _build(parts: list[str], config: ApConfigDict | None = None, radios: Radios = RADIOS):
|
||||
script, applied, skipped, restarts = build_script(config or _config(), parts, radios)
|
||||
return script, applied, skipped, restarts
|
||||
|
||||
|
||||
def _script(parts: list[str], config: ApConfigDict | None = None, radios: Radios = RADIOS) -> str:
|
||||
return _build(parts, config, radios)[0]
|
||||
|
||||
|
||||
# -- the radios --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_radios_are_found_by_their_band():
|
||||
assert radios_of(parse_uci_show(WIRELESS)) == Radios(r5g="radio1", r2g="radio0")
|
||||
|
||||
|
||||
def test_the_old_hwmode_names_the_band_too():
|
||||
text = "wireless.wl0=wifi-device\nwireless.wl0.hwmode='11a'\n"
|
||||
assert radios_of(parse_uci_show(text)) == Radios(r5g="wl0", r2g=None)
|
||||
|
||||
|
||||
# -- radio and system parts --------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_country_goes_to_both_radios():
|
||||
script = _script(["radio/country"])
|
||||
assert "uci set wireless.radio1.country='DE'" in script
|
||||
assert "uci set wireless.radio0.country='DE'" in script
|
||||
|
||||
|
||||
def test_the_country_goes_to_the_radios_there_are():
|
||||
script = _script(["radio/country"], radios=Radios(r2g="radio0"))
|
||||
assert "uci set wireless.radio0.country='DE'" in script
|
||||
assert "radio1" not in script
|
||||
|
||||
|
||||
def test_each_htmode_goes_to_its_radio():
|
||||
script = _script(["radio/5g_htmode", "radio/2g_htmode"])
|
||||
assert "uci set wireless.radio1.htmode='VHT80'" in script
|
||||
assert "uci set wireless.radio0.htmode='HT20'" in script
|
||||
|
||||
|
||||
def test_an_htmode_without_its_radio_is_skipped():
|
||||
_, applied, skipped, _ = _build(["radio/5g_htmode"], radios=Radios(r2g="radio0"))
|
||||
assert (applied, skipped) == ([], ["radio/5g_htmode"])
|
||||
|
||||
|
||||
def test_remote_syslog():
|
||||
script = _script(["system/syslog"])
|
||||
assert "uci set system.@system[0].log_ip='192.0.2.10'" in script
|
||||
assert "uci set system.@system[0].log_port='1514'" in script
|
||||
assert "uci set system.@system[0].log_remote='1'" in script
|
||||
|
||||
|
||||
def test_remote_syslog_defaults_to_port_514():
|
||||
assert "log_port='514'" in _script(["system/syslog"], _config(syslog_port=None))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("on", "line"),
|
||||
[
|
||||
(True, "/etc/init.d/uhttpd enable && /etc/init.d/uhttpd start"),
|
||||
(False, "/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable"),
|
||||
],
|
||||
)
|
||||
def test_the_web_interface_is_the_service_state(on, line):
|
||||
assert line in _script(["system/web_ui"], _config(web_ui=on))
|
||||
|
||||
|
||||
def test_the_ssh_port():
|
||||
assert "uci set dropbear.@dropbear[0].Port='2222'" in _script(
|
||||
["system/ssh_port"], _config(ssh_port=2222)
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("allowed", "value"), [(True, "on"), (False, "off")])
|
||||
def test_password_logins(allowed, value):
|
||||
script = _script(["system/password_auth"], _config(ssh_password_auth=allowed))
|
||||
assert f"uci set dropbear.@dropbear[0].PasswordAuth='{value}'" in script
|
||||
assert f"uci set dropbear.@dropbear[0].RootPasswordAuth='{value}'" in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("part", "missing"),
|
||||
[
|
||||
("system/syslog", "syslog_host"),
|
||||
("system/web_ui", "web_ui"),
|
||||
("system/ssh_port", "ssh_port"),
|
||||
("system/password_auth", "ssh_password_auth"),
|
||||
("radio/country", "country_code"),
|
||||
],
|
||||
)
|
||||
def test_a_part_without_its_value_is_skipped(part, missing):
|
||||
config = _config()
|
||||
del config[missing] # type: ignore[misc]
|
||||
script, applied, skipped, _ = _build([part], config)
|
||||
assert (script, applied, skipped) == ("", [], [part])
|
||||
|
||||
|
||||
# -- network parts -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ports(script: str, vid: int) -> str:
|
||||
line = next(c for c in script.splitlines() if f"apbr_vlan_{vid}.ports=" in c)
|
||||
return line.split("=", 1)[1]
|
||||
|
||||
|
||||
def test_the_bridge_trunks_every_vlan_tagged_by_default():
|
||||
script = _script(["network/bridge"])
|
||||
assert _ports(script, 10) == "'eth0:t'"
|
||||
assert _ports(script, 30) == "'eth0:t'"
|
||||
|
||||
|
||||
def test_the_management_vlan_untagged_when_asked():
|
||||
script = _script(["network/bridge"], _config(management_untagged=True))
|
||||
assert _ports(script, 10) == "'eth0:u*'"
|
||||
assert _ports(script, 30) == "'eth0:t'"
|
||||
|
||||
|
||||
def test_the_bridge_drops_foreign_vlan_sections_before_its_first_vlan():
|
||||
lines = _script(["network/bridge"]).split("\n")
|
||||
purge = lines.index(" uci delete network.@bridge-vlan[$n]")
|
||||
first = next(i for i, c in enumerate(lines) if "network.apbr_vlan_10=bridge-vlan" in c)
|
||||
assert purge < first
|
||||
|
||||
|
||||
def test_the_bridge_puts_the_networks_into_the_lan_zone():
|
||||
script = _script(["network/bridge"])
|
||||
assert "for net in $_mgmt_sec ap_vlan30; do" in script
|
||||
assert "uci set network.ap_vlan30.device='br-ap.30'" in script
|
||||
|
||||
|
||||
def test_the_bridge_restarts_the_ap_and_reloads_nothing():
|
||||
script, applied, _, restarts = _build(["network/bridge", "network/vlan/30"])
|
||||
lines = script.split("\n")
|
||||
assert restarts is True
|
||||
assert applied == ["network/bridge", "network/vlan/30"]
|
||||
assert lines[-1] == "reboot"
|
||||
assert "uci commit network" in lines
|
||||
assert not any(line.startswith(("wifi reload", "/etc/init.d/network")) for line in lines)
|
||||
|
||||
|
||||
def test_a_vlan_of_a_rebuilt_bridge_writes_nothing_of_its_own():
|
||||
script = _script(["network/bridge", "network/vlan/30"])
|
||||
assert "_found=$_i; break" not in script
|
||||
|
||||
|
||||
def test_one_vlan_reuses_the_section_that_carries_it():
|
||||
script = _script(["network/vlan/30"])
|
||||
assert "uci set network.@bridge-vlan[$_found].ports='eth0:t'" in script
|
||||
assert "uci set network.apbr_vlan_30=bridge-vlan" in script
|
||||
assert "uci set network.ap_vlan30.device='br-ap.30'" in script
|
||||
assert "uci delete network.@bridge-vlan[$n]" not in script
|
||||
|
||||
|
||||
def test_the_management_vlan_untagged_on_its_own():
|
||||
script = _script(["network/vlan/10"], _config(management_untagged=True))
|
||||
assert "uci set network.@bridge-vlan[$_found].ports='eth0:u*'" in script
|
||||
assert "uci set network.mgmt.device='br-ap.10'" in script
|
||||
|
||||
|
||||
def test_spanning_tree_on_the_section_named_br_ap():
|
||||
script = _script(["network/bridge_stp"], _config(bridge_stp=False))
|
||||
assert "= 'br-ap' ] || continue" in script
|
||||
assert "uci set network.$_s.stp='0'" in script
|
||||
|
||||
|
||||
# -- wireless parts ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _with(**fields: object) -> ApConfigDict:
|
||||
return _config(ssids=[_ssid(**fields)])
|
||||
|
||||
|
||||
def test_a_whitelist_sets_allow_and_rebuilds_the_list():
|
||||
script = _script(
|
||||
["wireless/Corp/acl"], _with(acl_mode="whitelist", acl_macs=["AA:BB:CC:DD:EE:02"])
|
||||
)
|
||||
assert "uci set $_s.macfilter='allow'" in script
|
||||
assert script.index("uci -q delete $_s.maclist") < script.index("uci add_list $_s.maclist")
|
||||
|
||||
|
||||
def test_a_blacklist_sets_deny_even_empty():
|
||||
script = _script(["wireless/Corp/acl"], _with(acl_mode="blacklist", acl_macs=[]))
|
||||
assert "uci set $_s.macfilter='deny'" in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("mode", "macs"), [("off", ["AA:BB:CC:DD:EE:02"]), ("whitelist", [])])
|
||||
def test_off_and_an_empty_whitelist_delete_the_filter(mode, macs):
|
||||
"""``macfilter='disable'`` puts netifd in a restart loop; off is the option left out."""
|
||||
script = _script(["wireless/Corp/acl"], _with(acl_mode=mode, acl_macs=macs))
|
||||
assert "uci -q delete $_s.macfilter" in script
|
||||
assert "macfilter='" not in script
|
||||
|
||||
|
||||
def test_a_missing_ssid_is_created_on_each_band_with_its_key():
|
||||
script = _script(["wireless/Corp/missing"])
|
||||
assert script.count("uci add wireless wifi-iface") == 2
|
||||
assert "uci set wireless.@wifi-iface[-1].device='radio0'" in script
|
||||
assert "uci set wireless.@wifi-iface[-1].network='ap_vlan30'" in script
|
||||
assert f"uci set wireless.@wifi-iface[-1].key='{PSK}'" in script
|
||||
|
||||
|
||||
def test_an_open_ssid_is_created_without_a_key():
|
||||
script = _script(["wireless/Corp/missing"], _with(encryption="none", key=""))
|
||||
assert "encryption='none'" in script
|
||||
assert ".key=" not in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize("attribute", ["missing", "bands", "encryption"])
|
||||
def test_a_keyed_mode_without_its_key_is_not_written(attribute):
|
||||
"""Off the air with the mode alone, unprotected with ``none``: skipped instead."""
|
||||
config = _config(ssids=[{**_ssid(), "key": ""}])
|
||||
script, applied, skipped, _ = _build([f"wireless/Corp/{attribute}"], config)
|
||||
assert (script, applied, skipped) == ("", [], [f"wireless/Corp/{attribute}"])
|
||||
|
||||
|
||||
def test_the_bands_take_the_ssid_off_a_radio_and_add_it_where_missing():
|
||||
script = _script(["wireless/Corp/bands"], _with(bands=["5 GHz"]))
|
||||
assert "= 'radio0' ] || continue\n uci delete $_s" in script
|
||||
assert "if [ $_found = 0 ]; then\n uci add wireless wifi-iface" in script
|
||||
assert " uci set wireless.@wifi-iface[-1].device='radio1'" in script
|
||||
|
||||
|
||||
def test_the_encryption_with_its_key():
|
||||
script = _script(["wireless/Corp/encryption"])
|
||||
assert "uci set $_s.encryption='psk2'" in script
|
||||
assert f"uci set $_s.key='{PSK}'" in script
|
||||
|
||||
|
||||
def test_switching_encryption_off_needs_no_key():
|
||||
script = _script(["wireless/Corp/encryption"], _with(encryption="none", key=""))
|
||||
assert "uci set $_s.encryption='none'" in script
|
||||
assert ".key=" not in script
|
||||
|
||||
|
||||
def test_the_passphrase_alone():
|
||||
script = _script(["wireless/Corp/passphrase"])
|
||||
assert f"uci set $_s.key='{PSK}'" in script
|
||||
assert ".encryption=" not in script
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("attribute", "fields", "line"),
|
||||
[
|
||||
("hidden", {"hidden": True}, "uci set $_s.hidden='1'"),
|
||||
("enabled", {"enabled": False}, "uci set $_s.disabled='1'"),
|
||||
("enabled", {"enabled": True}, "uci set $_s.disabled='0'"),
|
||||
("client_isolation", {"client_isolation": True}, "uci set $_s.isolate='1'"),
|
||||
("max_clients", {"max_clients": 32}, "uci set $_s.maxassoc='32'"),
|
||||
("max_clients", {"max_clients": None}, "uci -q delete $_s.maxassoc 2>/dev/null; true"),
|
||||
("disassoc_low_ack", {"disassoc_low_ack": False}, "uci set $_s.disassoc_low_ack='0'"),
|
||||
("max_inactivity", {"max_inactivity": 300}, "uci set $_s.max_inactivity='300'"),
|
||||
("vlan", {"vlan_id": 40}, "uci set $_s.network='ap_vlan40'"),
|
||||
],
|
||||
)
|
||||
def test_one_setting_of_an_ssid(attribute, fields, line):
|
||||
assert line in _script([f"wireless/Corp/{attribute}"], _with(**fields))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("attribute", "fields"),
|
||||
[
|
||||
("disassoc_low_ack", {"disassoc_low_ack": None}),
|
||||
("max_inactivity", {"max_inactivity": None}),
|
||||
("vlan", {"vlan_id": None}),
|
||||
],
|
||||
)
|
||||
def test_a_setting_left_to_the_device_is_skipped(attribute, fields):
|
||||
_, applied, skipped, _ = _build([f"wireless/Corp/{attribute}"], _with(**fields))
|
||||
assert (applied, skipped) == ([], [f"wireless/Corp/{attribute}"])
|
||||
|
||||
|
||||
def test_fast_transition_off_removes_it_without_a_domain():
|
||||
script = _script(["wireless/Corp/ft"], _config(mobility_domain="", ssids=[_ssid()]))
|
||||
assert "uci -q delete $_s.ieee80211r" in script
|
||||
assert "uci -q delete $_s.mobility_domain" in script
|
||||
|
||||
|
||||
def test_fast_transition_on_sets_the_domain():
|
||||
script = _script(["wireless/Corp/ft"], _with(fast_transition=True))
|
||||
assert "uci set $_s.ieee80211r='1'" in script
|
||||
assert "uci set $_s.mobility_domain='a1b2'" in script
|
||||
assert "uci set $_s.ft_over_ds='1'" in script
|
||||
|
||||
|
||||
def test_fast_transition_on_without_a_domain_is_skipped():
|
||||
config = _config(mobility_domain="", ssids=[_ssid(fast_transition=True)])
|
||||
assert _build(["wireless/Corp/ft"], config)[2] == ["wireless/Corp/ft"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"part", ["wireless/Nobody/hidden", "system/luci", "wireless/Corp/extra/x", "radio/power"]
|
||||
)
|
||||
def test_a_part_the_driver_cannot_write_is_skipped(part):
|
||||
assert _build([part]) == ("", [], [part], False)
|
||||
|
||||
|
||||
# -- the script --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_commits_come_before_the_reloads_network_first():
|
||||
lines = _script(["system/ssh_port", "wireless/Corp/hidden", "network/vlan/30"]).split("\n")
|
||||
assert lines[0] == "#!/bin/sh"
|
||||
last_commit = max(i for i, c in enumerate(lines) if c.startswith("uci commit "))
|
||||
assert lines[last_commit - 2 : last_commit + 1] == [
|
||||
"uci commit dropbear",
|
||||
"uci commit network",
|
||||
"uci commit wireless",
|
||||
]
|
||||
assert lines[last_commit + 1 :] == [
|
||||
"/etc/init.d/network reload 2>/dev/null; true",
|
||||
"wifi reload 2>&1; true",
|
||||
"/etc/init.d/dropbear restart 2>/dev/null; true",
|
||||
]
|
||||
|
||||
|
||||
def test_the_system_reload_restarts_logd():
|
||||
assert "/etc/init.d/log restart 2>/dev/null; true" in _script(["system/syslog"])
|
||||
|
||||
|
||||
def test_nothing_to_write_is_no_script():
|
||||
assert _build([]) == ("", [], [], False)
|
||||
|
||||
|
||||
def test_every_passphrase_is_masked():
|
||||
script = _script(["wireless/Corp/encryption"])
|
||||
shown = masked(script, _config())
|
||||
assert PSK not in shown
|
||||
assert f"uci set $_s.key={MASK}" in shown
|
||||
|
||||
|
||||
# -- values reach uci as they are (NetOrk/netork#1463) -----------------------------------------
|
||||
|
||||
NASTY = [
|
||||
"Bob's WiFi",
|
||||
"a'; touch pwned; echo 'b",
|
||||
'$(id) `id` "quoted"',
|
||||
"semi;colon && pipe | back\\slash",
|
||||
]
|
||||
|
||||
|
||||
def _fake_uci(ssid: str) -> str:
|
||||
"""A shell ``uci`` that knows one interface with *ssid* and logs every set/add_list."""
|
||||
quoted = "'" + ssid.replace("'", "'\"'\"'") + "'"
|
||||
return (
|
||||
"uci() {\n"
|
||||
' case "$1" in\n'
|
||||
' show) echo "wireless.default_radio0.ssid=x" ;;\n'
|
||||
f' -q) [ "$3" = "wireless.default_radio0.ssid" ] && printf %s {quoted} ;;\n'
|
||||
' set|add_list) printf \'%s\\n\' "$2" >> "$LOG" ;;\n'
|
||||
" esac\n"
|
||||
"}\n"
|
||||
)
|
||||
|
||||
|
||||
def _run(command: str, ssid: str, tmp_path) -> list[str]:
|
||||
log = tmp_path / "uci.log"
|
||||
log.touch()
|
||||
subprocess.run( # nosec B603 - a fixed /bin/sh on the test's own text
|
||||
["/bin/sh", "-c", _fake_uci(ssid) + command],
|
||||
env={"LOG": str(log), "PATH": "/usr/bin:/bin"},
|
||||
check=True,
|
||||
cwd=tmp_path,
|
||||
)
|
||||
return log.read_text().splitlines()
|
||||
|
||||
|
||||
def _loop(script: str) -> str:
|
||||
"""The ssid loop of a one-part script: between the shebang and the commits."""
|
||||
lines = script.split("\n")
|
||||
end = next(i for i, c in enumerate(lines) if c.startswith("uci commit"))
|
||||
return "\n".join(lines[1:end])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", NASTY)
|
||||
def test_a_passphrase_arrives_as_it_is(value, tmp_path):
|
||||
script = _script(["wireless/Home/encryption"], _config(ssids=[_ssid(name="Home", key=value)]))
|
||||
assert _run(_loop(script), "Home", tmp_path) == [
|
||||
"wireless.default_radio0.encryption=psk2",
|
||||
f"wireless.default_radio0.key={value}",
|
||||
]
|
||||
assert not (tmp_path / "pwned").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", NASTY)
|
||||
def test_an_ssid_name_is_matched_as_it_is(value, tmp_path):
|
||||
script = _script([f"wireless/{value}/hidden"], _config(ssids=[_ssid(name=value, hidden=True)]))
|
||||
assert _run(_loop(script), value, tmp_path) == ["wireless.default_radio0.hidden=1"]
|
||||
|
||||
|
||||
def test_a_mac_arrives_as_it_is(tmp_path):
|
||||
mac = "AA:BB:CC:DD:EE:01'; touch pwned; echo '"
|
||||
config = _config(ssids=[_ssid(name="Home", acl_mode="whitelist", acl_macs=[mac])])
|
||||
script = _script(["wireless/Home/acl"], config)
|
||||
assert _run(_loop(script), "Home", tmp_path)[-1] == f"wireless.default_radio0.maclist={mac}"
|
||||
assert not (tmp_path / "pwned").exists()
|
||||
|
||||
|
||||
# -- apply_ap_config ---------------------------------------------------------------------------
|
||||
|
||||
WORKDIR = "/tmp/openwrt-apply.Ab12Cd"
|
||||
|
||||
|
||||
class _ApplyAp:
|
||||
"""``run_command`` of an AP that answers the read and makes the work directory."""
|
||||
|
||||
def __init__(self, made: str = WORKDIR, write: CommandResult | None = None) -> None:
|
||||
self.made, self.write = made, write
|
||||
self.calls: list[tuple[str, bytes | None]] = []
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
self.calls.append((command, stdin))
|
||||
if command == SHOW:
|
||||
return CommandResult(WIRELESS, "", 0)
|
||||
if "mktemp -d" in command:
|
||||
return self.write or CommandResult(self.made + "\n", "", 0)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
|
||||
def test_the_script_is_written_from_stdin_into_a_fresh_directory_then_run_detached():
|
||||
ap = _ApplyAp()
|
||||
result = _driver(ap).apply_ap_config(_config(), ["radio/country", "wireless/Corp/encryption"])
|
||||
|
||||
(read, _), (write, script), (run, _) = ap.calls
|
||||
assert read == SHOW
|
||||
assert write.startswith("umask 077 && d=$(mktemp -d /tmp/openwrt-apply.XXXXXX)")
|
||||
assert script is not None and f"key='{PSK}'".encode() in script
|
||||
assert run == (
|
||||
f"( sh {WORKDIR}/apply.sh > {WORKDIR}/apply.log 2>&1 < /dev/null; "
|
||||
f"rm -f {WORKDIR}/apply.sh ) &"
|
||||
)
|
||||
assert result["applied"] == ["radio/country", "wireless/Corp/encryption"]
|
||||
assert result["skipped"] == []
|
||||
assert result["restarts"] is False
|
||||
assert result["log"] == f"{WORKDIR}/apply.log"
|
||||
assert (
|
||||
PSK not in result["commands"]
|
||||
and "uci set wireless.radio1.country='DE'" in result["commands"]
|
||||
)
|
||||
|
||||
|
||||
def test_nothing_to_write_sends_only_the_read():
|
||||
ap = _ApplyAp()
|
||||
result = _driver(ap).apply_ap_config(_config(), ["system/luci"])
|
||||
|
||||
assert [c for c, _ in ap.calls] == [SHOW]
|
||||
assert result == {
|
||||
"applied": [],
|
||||
"skipped": ["system/luci"],
|
||||
"restarts": False,
|
||||
"commands": "",
|
||||
"log": "",
|
||||
}
|
||||
|
||||
|
||||
def test_a_failed_write_runs_nothing():
|
||||
ap = _ApplyAp(write=CommandResult("", "mktemp: No space left on device\n", 1))
|
||||
with pytest.raises(RuntimeError, match="No space left"):
|
||||
_driver(ap).apply_ap_config(_config(), ["radio/country"])
|
||||
|
||||
assert len(ap.calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("made", ["", "/tmp/provision.sh", "/tmp/openwrt-apply.XXXXXX; reboot"])
|
||||
def test_no_fresh_directory_reported_runs_nothing(made):
|
||||
ap = _ApplyAp(made=made)
|
||||
with pytest.raises(RuntimeError, match="no work directory"):
|
||||
_driver(ap).apply_ap_config(_config(), ["radio/country"])
|
||||
|
||||
assert len(ap.calls) == 2
|
||||
|
||||
|
||||
def test_a_bridge_rebuild_says_the_ap_restarts():
|
||||
ap = _ApplyAp()
|
||||
result = _driver(ap).apply_ap_config(_config(), ["network/bridge"])
|
||||
|
||||
assert result["restarts"] is True
|
||||
assert result["commands"].endswith("\nreboot")
|
||||
Reference in new issue
Block a user