Files
napalm-openwrt/tests/unit/test_ap_config.py
T
Christian Manivong 9bac9bd1af
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 11s
driver / lowest (pull_request) Successful in 28s
driver / types (pull_request) Successful in 1m4s
driver / test (3.13) (pull_request) Successful in 54s
driver / test (3.12) (pull_request) Successful in 1m8s
driver / build (pull_request) Successful in 28s
driver / security (pull_request) Successful in 59s
CI / driver (pull_request) Successful in 2m8s
driver / publish (pull_request) Skipped
fix(access-point): a change the AP refuses in apply_ap_config is raised, and nothing applied (#54)
The configuration ran as one detached script, so a refused uci step
only reached its log while the call reported the part as applied. The
changes are now staged by a script the call waits for: a uci wrapper
records each refused set, add, add_list or delete with its part, and at
the end every config is reverted and the script exits 3, which raises
CommandErrorException naming each part, passphrases masked. Quiet -q
calls stay tests. The commits, LuCI's service, the reloads and the
restart run detached afterwards, as before.

Closes #54
2026-11-29 22:43:34 +01:00

691 lines
25 KiB
Python

"""``apply_ap_config``: an access point's desired configuration as UCI scripts (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``.
The changes are staged by a script the call waits for, so a step the AP refuses is
raised and nothing of it applied (#54); the commits, reloads and the restart run
detached afterwards, since they may cut the session.
"""
from __future__ import annotations
import subprocess
import pytest
from napalm.base.exceptions import CommandErrorException
from napalm_device_types import ApConfigDict, ApSsidConfigDict, CommandResult
from napalm_openwrt.ap_config import MASK, build_commands, build_scripts, 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):
"""``(stage + apply, applied, skipped, restarts)``; "" when nothing is written."""
scripts = build_scripts(config or _config(), parts, radios)
script = f"{scripts.stage}\n{scripts.apply}" if scripts.stage else ""
return script, scripts.applied, scripts.skipped, scripts.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(parts: list[str], config: ApConfigDict) -> str:
"""The commands of the parts, without the stage script's own lines around them."""
plan = build_commands(config, parts, RADIOS)[0]
return "\n".join(c for c in plan.commands if not c.startswith("_part="))
@pytest.mark.parametrize("value", NASTY)
def test_a_passphrase_arrives_as_it_is(value, tmp_path):
config = _config(ssids=[_ssid(name="Home", key=value)])
assert _run(_loop(["wireless/Home/encryption"], config), "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):
config = _config(ssids=[_ssid(name=value, hidden=True)])
loop = _loop([f"wireless/{value}/hidden"], config)
assert _run(loop, 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])])
loop = _loop(["wireless/Home/acl"], config)
assert _run(loop, "Home", tmp_path)[-1] == f"wireless.default_radio0.maclist={mac}"
assert not (tmp_path / "pwned").exists()
# -- the stage script: a refused step is reported, and nothing applied (#54) -----------------
#: A ``uci`` on PATH that knows one interface serving Corp, logs every call, and
#: refuses those whose words hold $REFUSE.
_FAKE_UCI_BIN = """#!/bin/sh
echo "$*" >> "$LOG"
if [ -n "$REFUSE" ] && echo "$*" | grep -qF -- "$REFUSE"; then
echo "uci: Invalid argument" >&2
exit 1
fi
case "$1" in
show) echo "wireless.default_radio0.ssid='Corp'" ;;
-q) [ "$2" = get ] || exit 0
[ "$3" = wireless.default_radio0.ssid ] && { echo Corp; exit 0; }
exit 1 ;;
esac
exit 0
"""
def _stage(tmp_path, parts: list[str], refuse: str = "", config: ApConfigDict | None = None):
"""Run the stage script of *parts* through /bin/sh against the fake ``uci``."""
bin_dir = tmp_path / "bin"
bin_dir.mkdir(exist_ok=True)
fake = bin_dir / "uci"
fake.write_text(_FAKE_UCI_BIN)
fake.chmod(0o755)
log = tmp_path / "uci.log"
log.touch()
script = tmp_path / "stage.sh"
script.write_text(build_scripts(config or _config(), parts, RADIOS).stage)
done = subprocess.run( # nosec B603 - a fixed /bin/sh on the test's own script
["/bin/sh", str(script)],
env={"LOG": str(log), "REFUSE": refuse, "PATH": f"{bin_dir}:/usr/bin:/bin"},
capture_output=True,
text=True,
cwd=tmp_path,
)
return done, log.read_text().splitlines()
def test_a_stage_that_goes_through_commits_nothing(tmp_path):
"""The commits are the detached script's; staging leaves the device running as it is."""
done, calls = _stage(tmp_path, ["system/ssh_port", "wireless/Corp/hidden"])
assert done.returncode == 0, done.stderr
assert "set dropbear.@dropbear[0].Port=22" in calls
assert not any(c.startswith(("commit", "revert")) for c in calls)
def test_a_refused_step_reverts_every_config_and_names_its_part(tmp_path):
done, calls = _stage(
tmp_path, ["system/ssh_port", "radio/country"], refuse="dropbear.@dropbear[0].Port"
)
assert done.returncode == 3
assert "system/ssh_port: uci set dropbear.@dropbear[0].Port=22" in done.stderr
assert "uci: Invalid argument" in done.stderr
assert "radio/country" not in done.stderr
assert {"revert dropbear", "revert wireless"} <= set(calls)
assert not any(c.startswith("commit") for c in calls)
def test_every_refused_part_is_named(tmp_path):
done, _ = _stage(tmp_path, ["radio/country", "radio/5g_htmode"], refuse="radio1")
assert "radio/country: uci set wireless.radio1.country=DE" in done.stderr
assert "radio/5g_htmode: uci set wireless.radio1.htmode=VHT80" in done.stderr
def test_a_quiet_delete_of_a_missing_option_is_no_refusal(tmp_path):
"""``uci -q delete`` of an option the section lacks exits 1; the builders count on it."""
config = _config(ssids=[_ssid(acl_mode="off")])
done, calls = _stage(tmp_path, ["wireless/Corp/acl"], refuse="-q delete", config=config)
assert done.returncode == 0, done.stderr
assert "-q delete wireless.default_radio0.macfilter" in calls
assert not any(c.startswith("revert") for c in calls)
def test_the_stage_script_removes_itself(tmp_path):
"""It holds the passphrases; the AP keeps it no longer than it runs."""
_stage(tmp_path, ["wireless/Corp/encryption"])
assert not (tmp_path / "stage.sh").exists()
def test_the_detached_script_commits_reloads_and_starts_what_is_live():
scripts = build_scripts(
_config(web_ui=False), ["system/web_ui", "wireless/Corp/hidden"], RADIOS
)
assert "uhttpd" not in scripts.stage
assert scripts.apply.split("\n") == [
"#!/bin/sh",
"uci commit wireless",
"/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable",
"wifi reload 2>&1; true",
]
# -- apply_ap_config ---------------------------------------------------------------------------
WORKDIR = "/tmp/openwrt-apply.Ab12Cd"
STAGE = f"sh {WORKDIR}/stage.sh"
class _ApplyAp:
"""``run_command`` of an AP: answers the read, makes the work directory, stages."""
def __init__(
self,
made: str = WORKDIR,
write: CommandResult | None = None,
stage: CommandResult | None = None,
) -> None:
self.made, self.write, self.stage = made, write, stage
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)
if command == STAGE:
return self.stage or CommandResult("", "", 0)
return CommandResult("", "", 0)
@property
def commands(self) -> list[str]:
return [c for c, _ in self.calls]
def test_the_changes_are_staged_and_waited_for_then_applied_detached():
ap = _ApplyAp()
result = _driver(ap).apply_ap_config(_config(), ["radio/country", "wireless/Corp/encryption"])
(read, _), (write, stage), (write_apply, apply), (run, _), (start, _) = ap.calls
assert read == SHOW
assert write.startswith("umask 077 && d=$(mktemp -d /tmp/openwrt-apply.XXXXXX)")
assert stage is not None and f"key='{PSK}'".encode() in stage
assert write_apply == f"umask 077 && cat > {WORKDIR}/apply.sh"
assert apply is not None and b"uci commit wireless" in apply and PSK.encode() not in apply
assert run == STAGE
assert start == (
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"]
assert "uci set wireless.radio1.country='DE'" in result["commands"]
def test_a_refused_step_raises_names_it_and_applies_nothing():
said = (
f"wireless/Corp/encryption: uci set wireless.default_radio0.key={PSK}: "
"uci: Invalid argument\n"
)
ap = _ApplyAp(stage=CommandResult("", said, 3))
with pytest.raises(CommandErrorException) as caught:
_driver(ap).apply_ap_config(_config(), ["radio/country", "wireless/Corp/encryption"])
message = str(caught.value)
assert "wireless/Corp/encryption" in message and "Invalid argument" in message
assert "nothing of it is applied" in message
assert PSK not in message
assert not any("apply.sh >" in c for c in ap.commands)
assert ap.commands[-1] == f"rm -rf {WORKDIR}"
def test_nothing_to_write_sends_only_the_read():
ap = _ApplyAp()
result = _driver(ap).apply_ap_config(_config(), ["system/luci"])
assert ap.commands == [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")