diff --git a/Makefile b/Makefile index 4fb7d81..ba84ef9 100644 --- a/Makefile +++ b/Makefile @@ -22,7 +22,7 @@ TTY := $(shell [ -t 0 ] && echo -it) OWNER := $(shell docker info --format '{{.SecurityOptions}}' 2>/dev/null | grep -q rootless && echo 0:0 || echo $$(id -u):$$(id -g)) FIX_OWNER = chown -R $(OWNER) /project -.PHONY: help web build flash ota ota-drivers monitor flash-monitor log size menuconfig clean fullclean erase test test-driver test-envelope +.PHONY: help web build flash ota ota-drivers monitor flash-monitor log size menuconfig clean fullclean erase test test-driver test-envelope test-api test-browser help: @echo "LED controller (ESP32-S3):" @@ -41,6 +41,8 @@ help: @echo " make clean remove the build directory (keeps sdkconfig)" @echo " make fullclean also remove sdkconfig and the web UI output" @echo " make test driver unit tests + C/Python envelope cross-check" + @echo " make test-api HOST=ip HTTP API tests against a running controller (data restored afterwards)" + @echo " make test-browser HOST=ip Selenium UI tests against a running controller (needs selenium + chromedriver)" @echo "variables: PORT=$(PORT) IDF_IMAGE=$(IDF_IMAGE)" # --- web UI --------------------------------------------------------------- @@ -93,6 +95,16 @@ test: test-driver test-envelope test-driver: python3 tools/run_driver_tests.py +# HTTP API tests (ported from v1) against a running controller; v1 features v2 lacks are xfail +test-api: + @test -n "$(HOST)" || { echo "usage: make test-api HOST="; exit 1; } + python3 -m pytest test/api -q --host $(HOST) + +# Selenium UI tests (ported from v1); they change the controller's data and do not restore it +test-browser: + @test -n "$(HOST)" || { echo "usage: make test-browser HOST="; exit 1; } + LED_CONTROLLER_RUN_BROWSER_TESTS=1 LED_HOST=$(HOST) python3 -m pytest test/browser -q + # The C envelope packer must produce the same bytes as test/binary_envelope.py test-envelope: @tmp=$$(mktemp -d); \ diff --git a/test/api/README.md b/test/api/README.md new file mode 100644 index 0000000..adc879b --- /dev/null +++ b/test/api/README.md @@ -0,0 +1,27 @@ +# API tests + +HTTP tests against a running controller, ported from the v1 Python app's `tests/test_endpoints_pytest.py` and `tests/test_endpoints.py`. They need `pytest` and `requests`. + +```bash +make test-api HOST=10.1.1.180 +``` + +or `python3 -m pytest test/api --host ` (or set `LED_HOST`). Without a host every test is skipped. + +The tests create and delete profiles, presets, zones and so on. Before the run they save every collection (`GET /db/`), and afterwards they write each one back (`PUT /db/`). Zone play and preset send do go out over ESP-NOW. They use made-up driver names (`pytest-a`, `pytest-nobody`) so real drivers ignore them. + +## v1 features v2 does not have yet + +A test for v1 behaviour that v2 is missing is marked `@missing("")`. That is a strict `xfail`, so the test shows as `x`, and it fails as `XPASS(strict)` once the feature works. When that happens, remove the marker. To list what is still missing: + +```bash +python3 -m pytest test/api --host -rx +``` + +v1 tests that were not ported: +- the model and engine unit tests (`tests/models/`, `tests/engine_tests/`), which test Python modules that have no C counterpart; +- the Wi-Fi/TCP/UDP driver test servers. + +The checks on exact driver messages became checks on status codes and replies, because ESP-NOW frames can't be captured from outside the board. + +The Selenium UI tests are in `test/browser/` (`make test-browser HOST=`). diff --git a/test/api/conftest.py b/test/api/conftest.py new file mode 100644 index 0000000..4dbb75f --- /dev/null +++ b/test/api/conftest.py @@ -0,0 +1,76 @@ +"""Black-box HTTP tests against a running controller. + +Ported from the v1 Python app's tests (tests/test_endpoints_pytest.py, tests/test_endpoints.py). +Point them at a board with --host or LED_HOST; without one every test is skipped. +The board's stored collections are snapshotted first and written back afterwards. +""" + +import os + +import pytest +import requests + +# Store collections (main/store.c NAMES), all reachable through GET/PUT /db/ +COLLECTIONS = ["device", "zone", "preset", "profile", "palette", "pattern", + "sequence", "scene", "group", "output", "settings"] + +TIMEOUT = 10 + + +def pytest_addoption(parser): + parser.addoption("--host", default=os.environ.get("LED_HOST"), + help="controller address (or set LED_HOST)") + + +def pytest_collection_modifyitems(config, items): + if config.getoption("--host"): + return + skip = pytest.mark.skip(reason="no controller: pass --host or set LED_HOST") + for item in items: + item.add_marker(skip) + + +class Client(requests.Session): + """requests.Session that takes paths relative to the controller.""" + + def __init__(self, base_url): + super().__init__() + self.base_url = base_url + self.headers.update({"User-Agent": "pytest/requests", "Accept": "application/json"}) + + def request(self, method, url, *args, **kwargs): + kwargs.setdefault("timeout", TIMEOUT) + return super().request(method, self.base_url + url, *args, **kwargs) + + +@pytest.fixture(scope="session") +def base_url(request): + host = request.config.getoption("--host") + return host if host.startswith("http") else f"http://{host}" + + +@pytest.fixture(scope="session") +def c(base_url): + with Client(base_url) as client: + yield client + + +@pytest.fixture(scope="session", autouse=True) +def restore_db(request): + """Snapshot every collection before the run and write it back afterwards.""" + if not request.config.getoption("--host"): + yield + return + client = request.getfixturevalue("c") + snapshot = {} + for name in COLLECTIONS: + resp = client.get(f"/db/{name}") + resp.raise_for_status() + snapshot[name] = resp.json() + yield snapshot + failed = [] + for name, data in snapshot.items(): + resp = client.put(f"/db/{name}", json=data) + if resp.status_code != 200: + failed.append(f"{name}: {resp.status_code}") + assert not failed, f"could not restore the controller's data: {failed}" diff --git a/test/api/helpers.py b/test/api/helpers.py new file mode 100644 index 0000000..d235e63 --- /dev/null +++ b/test/api/helpers.py @@ -0,0 +1,27 @@ +import uuid + +import pytest + + +def unique(prefix): + return f"{prefix}-{uuid.uuid4().hex[:8]}" + + +def new_id(resp): + """Id of a created record: replies are {"": record} or a record with "id".""" + data = resp.json() + if "id" in data and not isinstance(data["id"], dict): + return str(data["id"]) + return str(next(iter(data))) + + +def find_id_by_field(listing, field, value): + for obj_id, data in listing.items(): + if isinstance(data, dict) and data.get(field) == value: + return str(obj_id) + raise AssertionError(f"Could not find id for {field}={value!r}") + + +def missing(feature): + """Mark a test for v1 behaviour v2 does not have yet; strict, so it fails once the feature lands.""" + return pytest.mark.xfail(strict=True, reason=f"v2: {feature} not implemented") diff --git a/test/api/test_collections.py b/test/api/test_collections.py new file mode 100644 index 0000000..33bfb1f --- /dev/null +++ b/test/api/test_collections.py @@ -0,0 +1,102 @@ +"""Groups, sequences, scenes and palettes.""" + +from helpers import find_id_by_field, missing, new_id, unique + + +def test_groups(c): + name = unique("pytest-group") + assert c.post("/groups", json={"name": name}).status_code == 201 + gid = find_id_by_field(c.get("/groups").json(), "name", name) + resp = c.get(f"/groups/{gid}") + assert resp.status_code == 200 + assert resp.json()["name"] == name + resp = c.put(f"/groups/{gid}", json={"brightness": 10}) + assert resp.status_code == 200 + assert resp.json()["brightness"] == 10 + assert c.delete(f"/groups/{gid}").status_code == 200 + + +def test_sequences_crud(c): + name = unique("pytest-seq") + resp = c.post("/sequences", json={"name": name, "steps": [{"preset_id": "1", "duration_s": 2}]}) + assert resp.status_code == 201 + sid = find_id_by_field(c.get("/sequences").json(), "name", name) + resp = c.get(f"/sequences/{sid}") + assert resp.status_code == 200 + assert resp.json()["steps"] == [{"preset_id": "1", "duration_s": 2.0}] + resp = c.put(f"/sequences/{sid}", json={"loop": False, "repeat_count": 2}) + assert resp.status_code == 200 + assert resp.json()["loop"] is False and resp.json()["repeat_count"] == 2 + assert c.get("/sequences/status").status_code == 200 + assert c.delete(f"/sequences/{sid}").status_code == 200 + + +@missing("sequence step validation") +def test_sequence_step_needs_preset(c): + sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq"), "steps": []})) + assert c.put(f"/sequences/{sid}", json={"steps": [{"duration_s": 1}]}).status_code == 400 + c.delete(f"/sequences/{sid}") + + +@missing("400 for a sequence without zone_id") +def test_sequence_without_zone_cannot_play(c): + sid = new_id(c.post("/sequences", json={"name": unique("pytest-seq"), + "steps": [{"preset_id": "1", "duration_s": 1}]})) + assert c.post(f"/sequences/{sid}/play").status_code == 400 + c.delete(f"/sequences/{sid}") + + +@missing("sequence play/stop status replies and active flag") +def test_sequence_play_and_stop(c): + profile = new_id(c.post("/profiles", json={"name": unique("pytest-engine")})) + c.post(f"/profiles/{profile}/apply") + preset = new_id(c.post("/presets", json={"name": "pytest-on", "pattern": "on", "colors": ["#ff0000"]})) + zone = new_id(c.post("/zones", json={"name": "pytest-engine-zone", "names": ["pytest-nobody"]})) + c.post("/sequences", json={"name": "pytest-engine-seq", "zone_id": zone, "loop": False, + "steps": [{"preset_id": preset, "duration_s": 0.5}]}) + sid = find_id_by_field(c.get("/sequences").json(), "name", "pytest-engine-seq") + + resp = c.post(f"/sequences/{sid}/play") + assert resp.status_code == 200 + assert resp.json()["zone_id"] == zone + assert c.get(f"/sequences/{sid}").json()["active"] is True + resp = c.post(f"/sequences/{sid}/stop") + assert resp.json()["stopped"] is True + assert c.get(f"/sequences/{sid}").json()["active"] is False + + c.delete(f"/sequences/{sid}") + c.delete(f"/zones/{zone}") + c.delete(f"/profiles/{profile}") + + +def test_scenes(c): + name = unique("pytest-scene") + assert c.post("/scenes", json={"name": name}).status_code == 201 + sid = find_id_by_field(c.get("/scenes").json(), "name", name) + assert c.get(f"/scenes/{sid}").status_code == 200 + resp = c.put(f"/scenes/{sid}", json={"name": name + "-updated"}) + assert resp.status_code == 200 + assert resp.json()["name"].endswith("-updated") + assert c.delete(f"/scenes/{sid}").status_code == 200 + + +@missing("v1 palette shape ({id, colors})") +def test_palettes(c): + resp = c.post("/palettes", json={"colors": ["#112233", "#445566"]}) + assert resp.status_code == 201 + pid = str(resp.json()["id"]) + assert resp.json()["colors"] == ["#112233", "#445566"] + resp = c.get(f"/palettes/{pid}") + assert resp.status_code == 200 + assert resp.json()["id"] == pid + resp = c.put(f"/palettes/{pid}", json={"colors": ["#000000"]}) + assert resp.status_code == 200 + assert resp.json()["colors"] == ["#000000"] + assert c.delete(f"/palettes/{pid}").status_code == 200 + + +@missing("v1 palette shape ({id, colors})") +def test_palettes_list_is_colour_lists(c): + pid = str(c.post("/palettes", json={"colors": ["#abcdef"]}).json()["id"]) + assert c.get("/palettes").json()[pid] == ["#abcdef"] + c.delete(f"/palettes/{pid}") diff --git a/test/api/test_devices.py b/test/api/test_devices.py new file mode 100644 index 0000000..52b275c --- /dev/null +++ b/test/api/test_devices.py @@ -0,0 +1,136 @@ +import pytest + +from helpers import missing + +# Test MACs from v1; no real driver has them +ESPNOW_MAC = "aabbccddeeff" +WIFI_MAC = "102030405060" +WIFI_MAC2 = "102030405061" + + +@pytest.fixture +def espnow_dev(c): + c.delete(f"/devices/{ESPNOW_MAC}") + resp = c.post("/devices", json={"name": "pytest-dev", "address": "aa:bb:cc:dd:ee:ff"}) + assert resp.status_code == 201, resp.text + yield resp + c.delete(f"/devices/{ESPNOW_MAC}") + + +@pytest.fixture +def wifi_dev(c): + c.delete(f"/devices/{WIFI_MAC}") + resp = c.post("/devices", json={"name": "pytest-wifi", "type": "led", "transport": "wifi", + "address": "192.168.50.10", "mac": WIFI_MAC}) + assert resp.status_code == 201, resp.text + yield resp + c.delete(f"/devices/{WIFI_MAC}") + + +def test_list(c): + resp = c.get("/devices") + assert resp.status_code == 200 + assert isinstance(resp.json(), dict) + + +@missing("v1 device registry (MAC keys, validation)") +def test_create_requires_name(c): + assert c.post("/devices", json={}).status_code == 400 + + +@missing("v1 device registry (MAC keys, validation)") +def test_create_espnow_keyed_by_mac(espnow_dev): + dev = espnow_dev.json() + assert list(dev) == [ESPNOW_MAC] + rec = dev[ESPNOW_MAC] + assert rec["name"] == "pytest-dev" + assert rec["id"] == ESPNOW_MAC + assert rec["type"] == "led" + assert rec["transport"] == "espnow" + assert rec["address"] == ESPNOW_MAC + + +@missing("v1 device registry (MAC keys, validation)") +def test_get_espnow_has_no_connection_state(c, espnow_dev): + resp = c.get(f"/devices/{ESPNOW_MAC}") + assert resp.status_code == 200 + assert resp.json()["name"] == "pytest-dev" + assert resp.json().get("connected") is None + assert c.get("/devices").json()[ESPNOW_MAC].get("connected") is None + + +@missing("v1 device registry (MAC keys, validation)") +def test_create_wifi(c, wifi_dev): + rec = wifi_dev.json()[WIFI_MAC] + assert rec["transport"] == "wifi" + assert rec["address"] == "192.168.50.10" + assert c.get(f"/devices/{WIFI_MAC}").json().get("connected") is False + + +@missing("v1 device registry (MAC keys, validation)") +def test_create_second_wifi_same_name(c, wifi_dev): + resp = c.post("/devices", json={"name": "pytest-wifi", "transport": "wifi", + "address": "192.168.50.11", "mac": WIFI_MAC2}) + assert resp.status_code == 201 + assert resp.json()[WIFI_MAC2]["name"] == "pytest-wifi" + assert c.delete(f"/devices/{WIFI_MAC2}").status_code == 200 + + +@missing("v1 device registry (MAC keys, validation)") +def test_create_duplicate_mac(c, wifi_dev): + resp = c.post("/devices", json={"name": "pytest-wifi-dupmac", "transport": "wifi", + "address": "192.168.50.99", "mac": WIFI_MAC}) + assert resp.status_code == 409 + + +@missing("v1 device registry (MAC keys, validation)") +def test_create_wifi_requires_mac(c): + resp = c.post("/devices", json={"name": "no-mac-wifi", "transport": "wifi", "address": "192.168.50.12"}) + assert resp.status_code == 400 + + +@missing("v1 device registry (MAC keys, validation)") +def test_create_rejects_unknown_transport(c): + assert c.post("/devices", json={"name": "bad-tr", "transport": "serial"}).status_code == 400 + + +@missing("v1 device registry (MAC keys, validation)") +def test_rename_blank(c, espnow_dev): + assert c.put(f"/devices/{ESPNOW_MAC}", json={"name": " "}).status_code == 400 + + +@missing("v1 device registry (MAC keys, validation)") +def test_rename(c, espnow_dev, wifi_dev): + for mac in (ESPNOW_MAC, WIFI_MAC): + resp = c.put(f"/devices/{mac}", json={"name": "renamed"}) + assert resp.status_code == 200 + assert resp.json()["name"] == "renamed" + + +@missing("v1 device registry (MAC keys, validation)") +def test_cannot_change_mac(c, espnow_dev): + assert c.put(f"/devices/{ESPNOW_MAC}", json={"mac": "001122334455"}).status_code == 400 + + +@missing("device identify") +def test_identify(c, espnow_dev): + resp = c.post(f"/devices/{ESPNOW_MAC}/identify") + assert resp.status_code == 200 + assert resp.json().get("message") + + +@missing("device identify") +def test_identify_unknown(c): + assert c.post("/devices/000000000000/identify").status_code == 404 + + +def test_status(c): + resp = c.get("/devices/status") + assert resp.status_code == 200 + assert isinstance(resp.json(), dict) + + +@missing("v1 device registry (MAC keys, validation)") +def test_delete(c, espnow_dev): + assert c.delete(f"/devices/{ESPNOW_MAC}").status_code == 200 + assert c.get(f"/devices/{ESPNOW_MAC}").status_code == 404 diff --git a/test/api/test_led_tool.py b/test/api/test_led_tool.py new file mode 100644 index 0000000..422c4f3 --- /dev/null +++ b/test/api/test_led_tool.py @@ -0,0 +1,20 @@ +"""led-tool: configure drivers over USB serial (v1 controllers/led_tool.py).""" + +from helpers import missing + +# Every test here fails on v2 +pytestmark = missing("led-tool (USB serial)") + + +def test_ports(c): + resp = c.get("/led-tool/ports") + assert resp.status_code == 200 + assert isinstance(resp.json()["ports"], list) + + +def test_settings_requires_port(c): + assert c.get("/led-tool/settings").status_code == 400 + + +def test_reset_requires_port(c): + assert c.post("/led-tool/reset", json={}).status_code == 400 diff --git a/test/api/test_outputs.py b/test/api/test_outputs.py new file mode 100644 index 0000000..df0a2e2 --- /dev/null +++ b/test/api/test_outputs.py @@ -0,0 +1,55 @@ +import pytest + +from helpers import missing + +# Every test here fails on v2 +pytestmark = missing("pixel outputs (DDP, Art-Net, sACN, DMX)") + + +@pytest.fixture +def output(c): + # 127.0.0.1 is the board itself, so the test frames go nowhere + resp = c.post("/outputs", json={"name": "pytest-wall", "protocol": "ddp", "host": "127.0.0.1", + "port": 9, "pixel_count": 10}) + assert resp.status_code == 201, resp.text + oid = str(resp.json()["id"]) + yield oid + c.delete(f"/outputs/{oid}") + + +def test_ddp_requires_host(c): + resp = c.post("/outputs", json={"name": "wall", "protocol": "ddp"}) + assert resp.status_code == 400 + assert "host" in resp.json()["error"] + + +def test_rejects_unknown_protocol(c): + assert c.post("/outputs", json={"name": "wall", "protocol": "hdmi", "host": "x"}).status_code == 400 + + +def test_defaults(c, output): + rec = c.get(f"/outputs/{output}").json() + assert rec["color_order"] == "rgb" + assert rec["fps"] == 40 + assert rec["enabled"] is True + + +def test_update(c, output): + resp = c.put(f"/outputs/{output}", json={"color_order": "grb"}) + assert resp.status_code == 200 + assert resp.json()["color_order"] == "grb" + + +def test_update_validates(c, output): + assert c.put(f"/outputs/{output}", json={"color_order": "xyz"}).status_code == 400 + + +def test_test_pattern(c, output): + resp = c.post(f"/outputs/{output}/test", json={"step_s": 0.1}) + assert resp.status_code == 200 + assert resp.json()["status"]["frames"] > 0 + + +def test_delete(c, output): + assert c.delete(f"/outputs/{output}").status_code == 200 + assert c.get(f"/outputs/{output}").status_code == 404 diff --git a/test/api/test_patterns.py b/test/api/test_patterns.py new file mode 100644 index 0000000..2c222c2 --- /dev/null +++ b/test/api/test_patterns.py @@ -0,0 +1,73 @@ +from helpers import missing, unique + + +@missing("/patterns/definitions") +def test_definitions(c): + resp = c.get("/patterns/definitions") + assert resp.status_code == 200 + assert isinstance(resp.json(), dict) + + +@missing("driver pattern files in /patterns") +def test_list_includes_driver_patterns(c): + resp = c.get("/patterns") + assert resp.status_code == 200 + assert "blink" in resp.json() + + +@missing("v1 pattern create ({name, data})") +def test_crud(c): + pid = unique("pytest_pattern").replace("-", "_") + resp = c.post("/patterns", json={"name": pid, "data": {"foo": "bar"}}) + assert resp.status_code == 201 + assert resp.json()["foo"] == "bar" + resp = c.get(f"/patterns/{pid}") + assert resp.status_code == 200 + assert resp.json()["foo"] == "bar" + resp = c.put(f"/patterns/{pid}", json={"baz": 1}) + assert resp.status_code == 200 + assert resp.json()["baz"] == 1 + assert c.delete(f"/patterns/{pid}").status_code == 200 + + +@missing("/patterns/ota/file") +def test_ota_file(c): + resp = c.get("/patterns/ota/file/blink.py") + assert resp.status_code == 200 + assert resp.headers["Content-Type"].startswith("text/plain") + assert "class" in resp.text + + +@missing("/patterns/ota/file") +def test_ota_file_rejects_builtin(c): + # on/off are built into the driver firmware, not OTA files + resp = c.get("/patterns/ota/file/on.py") + assert resp.status_code == 400 + assert "error" in resp.json() + + +@missing("/patterns/ota/manifest") +def test_ota_manifest(c): + resp = c.get("/patterns/ota/manifest") + assert resp.status_code == 200 + names = [f["name"] for f in resp.json()["files"]] + assert "blink.py" in names + + +@missing("/patterns//send") +def test_send_rejects_builtin(c): + resp = c.post("/patterns/off/send", json={}) + assert resp.status_code == 400 + assert "error" in resp.json() + + +@missing("/patterns/upload") +def test_upload_rejects_builtin(c): + resp = c.post("/patterns/upload", json={"name": "on.py", "code": "class On:\n def run(self, p):\n yield\n"}) + assert resp.status_code == 400 + + +@missing("/patterns/driver") +def test_driver_rejects_builtin(c): + resp = c.post("/patterns/driver", json={"name": "off", "code": "class Off:\n def run(self, p):\n yield\n"}) + assert resp.status_code == 400 diff --git a/test/api/test_presets.py b/test/api/test_presets.py new file mode 100644 index 0000000..758a45c --- /dev/null +++ b/test/api/test_presets.py @@ -0,0 +1,87 @@ +import pytest + +from helpers import missing, new_id, unique + + +@pytest.fixture +def profile(c): + pid = new_id(c.post("/profiles", json={"name": unique("pytest-profile")})) + assert c.post(f"/profiles/{pid}/apply").status_code == 200 + yield pid + c.delete(f"/profiles/{pid}") + + +@pytest.fixture +def preset(c, profile): + resp = c.post("/presets", json={"name": unique("pytest-preset"), "pattern": "on", + "colors": ["#ff0000"], "brightness": 123, "delay": 100}) + assert resp.status_code == 201 + pid = new_id(resp) + yield pid + c.delete(f"/presets/{pid}") + + +@missing("seeded presets for a new profile") +def test_list_and_get(c, profile): + resp = c.get("/presets") + assert resp.status_code == 200 + presets = resp.json() + assert presets + first = next(iter(presets)) + resp = c.get(f"/presets/{first}") + assert resp.status_code == 200 + assert resp.json() + + +def test_create_belongs_to_current_profile(c, profile): + resp = c.post("/presets", json={"name": unique("pytest-preset"), "pattern": "on", "colors": ["#ff0000"]}) + assert resp.status_code == 201 + pid = new_id(resp) + assert str(resp.json()[pid]["profile_id"]) == profile + + +@missing("preset defaults on create") +def test_create_fills_defaults(c, profile): + resp = c.post("/presets", json={"name": unique("pytest-preset"), "pattern": "on"}) + rec = resp.json()[new_id(resp)] + for key in ("colors", "brightness", "delay", "n1", "n8"): + assert key in rec, key + + +def test_presets_scoped_to_profile(c, preset): + other = new_id(c.post("/profiles", json={"name": unique("pytest-profile")})) + c.post(f"/profiles/{other}/apply") + assert preset not in c.get("/presets").json() + assert c.get(f"/presets/{preset}").status_code == 404 + c.delete(f"/profiles/{other}") + + +def test_update(c, preset): + resp = c.put(f"/presets/{preset}", json={"brightness": 77}) + assert resp.status_code == 200 + assert resp.json()["brightness"] == 77 + + +def test_send(c, preset): + resp = c.post("/presets/send", json={"preset_ids": [preset], "save": False}) + assert resp.status_code == 200 + assert resp.json()["presets_sent"] >= 1 + + +def test_send_requires_ids(c, profile): + assert c.post("/presets/send", json={"preset_ids": []}).status_code == 400 + + +def test_push(c): + resp = c.post("/presets/push", json={"payload": {"v": "1", "select": {"pytest-nobody": ["off"]}}}) + assert resp.status_code == 200 + assert resp.json()["message"] == "Delivered" + + +def test_push_requires_payload(c): + assert c.post("/presets/push", json={"targets": []}).status_code == 400 + + +def test_delete(c, preset): + assert c.delete(f"/presets/{preset}").status_code == 200 + assert c.get(f"/presets/{preset}").status_code == 404 diff --git a/test/api/test_profiles.py b/test/api/test_profiles.py new file mode 100644 index 0000000..eaa6cca --- /dev/null +++ b/test/api/test_profiles.py @@ -0,0 +1,89 @@ +import pytest + +from helpers import missing, new_id, unique + +# Presets every new profile is seeded with (v1 controllers/profile.py) +SEEDED = {"on", "off", "rainbow", "Colour Cycle", "transition", "flicker", "flame", "twinkle"} + + +@pytest.fixture +def profile(c): + resp = c.post("/profiles", json={"name": unique("pytest-profile")}) + assert resp.status_code == 201 + pid = new_id(resp) + assert c.post(f"/profiles/{pid}/apply").status_code == 200 + yield pid + c.delete(f"/profiles/{pid}") + + +def test_list(c, profile): + resp = c.get("/profiles") + assert resp.status_code == 200 + data = resp.json() + assert profile in data["profiles"] + assert data["current_profile_id"] == profile + + +def test_apply_sets_current(c, profile): + resp = c.get("/profiles/current") + assert resp.status_code == 200 + assert str(resp.json()["id"]) == profile + assert resp.json()["profile"]["name"].startswith("pytest-profile") + + +def test_apply_unknown_profile(c): + assert c.post("/profiles/999999/apply").status_code == 404 + + +@missing("profile seeding (presets, default zone, palette)") +def test_new_profile_is_seeded(c, profile): + presets = c.get("/presets").json() + assert SEEDED <= {p["name"] for p in presets.values()} + rec = c.get(f"/profiles/{profile}").json() + assert rec["palette_id"] in c.get("/palettes").json() + zones = rec["zones"] + assert len(zones) == 1 + zone = c.get(f"/zones/{zones[0]}").json() + assert zone["name"] == "default" + assert set(zone["presets_flat"]) == set(presets) + + +def test_put_current(c, profile): + name = unique("pytest-renamed") + assert c.put("/profiles/current", json={"name": name}).status_code == 200 + assert c.get(f"/profiles/{profile}").json()["name"] == name + + +def test_put(c, profile): + name = unique("pytest-renamed") + resp = c.put(f"/profiles/{profile}", json={"name": name}) + assert resp.status_code == 200 + assert resp.json()["name"] == name + + +@missing("profile clone") +def test_clone(c, profile): + name = unique("pytest-profile-clone") + resp = c.post(f"/profiles/{profile}/clone", json={"name": name}) + assert resp.status_code == 201 + clone = new_id(resp) + assert clone != profile + assert resp.json()[clone]["name"] == name + src_presets = c.get("/presets").json() + + assert c.post(f"/profiles/{clone}/apply").status_code == 200 + cloned_presets = c.get("/presets").json() + # The clone gets its own copies of the presets, zones and palette + assert not set(cloned_presets) & set(src_presets) + assert sorted(p["name"] for p in cloned_presets.values()) == sorted(p["name"] for p in src_presets.values()) + src, dst = c.get(f"/profiles/{profile}").json(), c.get(f"/profiles/{clone}").json() + assert dst["palette_id"] != src["palette_id"] + assert len(dst["zones"]) == len(src["zones"]) and not set(dst["zones"]) & set(src["zones"]) + + assert c.delete(f"/profiles/{clone}").status_code == 200 + + +def test_delete(c): + pid = new_id(c.post("/profiles", json={"name": unique("pytest-profile")})) + assert c.delete(f"/profiles/{pid}").status_code == 200 + assert c.get(f"/profiles/{pid}").status_code == 404 diff --git a/test/api/test_routes.py b/test/api/test_routes.py new file mode 100644 index 0000000..b490d25 --- /dev/null +++ b/test/api/test_routes.py @@ -0,0 +1,31 @@ +import pytest + +from helpers import missing + + +def test_index(c): + resp = c.get("/") + assert resp.status_code == 200 + assert "LED Controller" in resp.text + + +def test_favicon(c): + assert c.get("/favicon.ico").status_code == 204 + + +@pytest.mark.parametrize("path", ["style.css", "zones.js", "presets.js", "profiles.js", "devices.js"]) +def test_static(c, path): + assert c.get(f"/static/{path}").status_code == 200 + + +def test_settings_page(c): + resp = c.get("/settings/page") + assert resp.status_code == 200 + assert "LED Controller" in resp.text + + +@missing("/ws") +def test_ws_rejects_plain_get(c): + # A websocket endpoint refuses a request that is not an upgrade + resp = c.get("/ws") + assert resp.status_code in {400, 401, 403, 405, 426} diff --git a/test/api/test_settings.py b/test/api/test_settings.py new file mode 100644 index 0000000..3119b18 --- /dev/null +++ b/test/api/test_settings.py @@ -0,0 +1,58 @@ +from helpers import missing, unique + + +@missing("settings defaults") +def test_get_settings(c): + resp = c.get("/settings") + assert resp.status_code == 200 + assert "wifi_channel" in resp.json() + + +@missing("/settings/wifi/ap") +def test_wifi_ap_get(c): + resp = c.get("/settings/wifi/ap") + assert resp.status_code == 200 + ap = resp.json() + assert "saved_ssid" in ap + assert "active" in ap + + +@missing("/settings/wifi/ap") +def test_wifi_ap_post(c): + ssid = unique("pytest-ssid") + resp = c.post("/settings/wifi/ap", json={"ssid": ssid, "password": "secret", "channel": 1}) + assert resp.status_code == 200 + assert resp.json()["ssid"] == ssid + assert resp.json()["channel"] == 1 + assert c.get("/settings/wifi/ap").json()["saved_ssid"] == ssid + + +@missing("/settings/wifi/ap") +def test_wifi_ap_rejects_bad_channel(c): + resp = c.post("/settings/wifi/ap", json={"ssid": "bad-ssid", "password": "secret", "channel": 12}) + assert resp.status_code == 400 + + +@missing("/settings/wifi/ap") +def test_wifi_ap_requires_ssid(c): + assert c.post("/settings/wifi/ap", json={"password": "secret"}).status_code == 400 + + +def test_wifi_channel(c): + assert c.put("/settings/settings", json={"wifi_channel": 11}).status_code == 200 + assert c.get("/settings").json()["wifi_channel"] == 11 + + +@missing("settings validation") +def test_wifi_channel_out_of_range(c): + assert c.put("/settings/settings", json={"wifi_channel": 12}).status_code == 400 + + +def test_global_brightness(c): + assert c.put("/settings/settings", json={"global_brightness": 42}).status_code == 200 + assert c.get("/settings").json().get("global_brightness") == 42 + + +@missing("settings validation") +def test_global_brightness_out_of_range(c): + assert c.put("/settings/settings", json={"global_brightness": 300}).status_code == 400 diff --git a/test/api/test_zones.py b/test/api/test_zones.py new file mode 100644 index 0000000..c593365 --- /dev/null +++ b/test/api/test_zones.py @@ -0,0 +1,130 @@ +import pytest + +from helpers import missing, new_id, unique + + +@pytest.fixture +def profile(c): + pid = new_id(c.post("/profiles", json={"name": unique("pytest-profile")})) + assert c.post(f"/profiles/{pid}/apply").status_code == 200 + yield pid + c.delete(f"/profiles/{pid}") + + +@pytest.fixture +def zone(c, profile): + name = unique("pytest-zone") + resp = c.post("/zones", json={"name": name, "names": ["pytest-a", "pytest-b"]}) + assert resp.status_code == 201 + zid = new_id(resp) + yield zid + c.delete(f"/zones/{zid}") + + +@missing("v1 zone list shape and profile zone order") +def test_list(c, profile, zone): + resp = c.get("/zones") + assert resp.status_code == 200 + data = resp.json() + assert zone in data["zones"] + assert zone in data["zone_order"] + assert str(data["profile_id"]) == profile + assert "current_zone_id" in data + + +@missing("adding new zones to the current profile") +def test_create_adds_to_profile(c, profile, zone): + assert zone in c.get(f"/profiles/{profile}").json()["zones"] + + +@missing("zone validation") +def test_create_requires_name(c, profile): + assert c.post("/zones", json={"names": ["1"]}).status_code == 400 + + +def test_get(c, zone): + resp = c.get(f"/zones/{zone}") + assert resp.status_code == 200 + assert resp.json()["name"].startswith("pytest-zone") + + +@missing("zone set-current") +def test_set_current(c, zone): + resp = c.post(f"/zones/{zone}/set-current") + assert resp.status_code == 200 + assert resp.json()["zone_id"] == zone + assert c.cookies.get("current_zone") == zone + resp = c.get("/zones/current") + assert resp.status_code == 200 + assert resp.json()["zone_id"] == zone + + +@missing("zone set-current") +def test_set_current_unknown(c): + assert c.post("/zones/999999/set-current").status_code == 404 + + +def test_edit_workflow(c, zone): + # From v1 tests/test_endpoints.py test_zone_edit_workflow + resp = c.put(f"/zones/{zone}", json={"name": "Edited Zone Name", "names": ["2", "3", "4"]}) + assert resp.status_code == 200 + assert resp.json()["name"] == "Edited Zone Name" + assert resp.json()["names"] == ["2", "3", "4"] + stored = c.get(f"/zones/{zone}").json() + assert stored["name"] == "Edited Zone Name" + assert stored["names"] == ["2", "3", "4"] + + +@missing("zone clone") +def test_clone(c, profile, zone): + resp = c.post(f"/zones/{zone}/clone", json={"name": "pytest-zone-clone"}) + assert resp.status_code == 201 + clone = new_id(resp) + assert clone != zone + rec = c.get(f"/zones/{clone}").json() + assert rec["name"] == "pytest-zone-clone" + assert rec["names"] == ["pytest-a", "pytest-b"] + assert clone in c.get(f"/profiles/{profile}").json()["zones"] + assert c.delete(f"/zones/{clone}").status_code == 200 + + +@missing("zone clone") +def test_clone_default_name(c, zone): + resp = c.post(f"/zones/{zone}/clone", json={}) + clone = new_id(resp) + assert resp.json()[clone]["name"].endswith(" Copy") + c.delete(f"/zones/{clone}") + + +@missing("zone content-fragment") +def test_content_fragment(c, zone): + resp = c.get(f"/zones/{zone}/content-fragment", headers={"HX-Request": "true", "Accept": "text/html"}) + assert resp.status_code == 200 + assert f'data-zone-id="{zone}"' in resp.text + + +@missing("removing deleted zones from the profile") +def test_delete_removes_from_profile(c, profile): + zid = new_id(c.post("/zones", json={"name": unique("pytest-zone"), "names": ["1"]})) + assert c.delete(f"/zones/{zid}").status_code == 200 + assert c.get(f"/zones/{zid}").status_code == 404 + assert zid not in c.get(f"/profiles/{profile}").json()["zones"] + + +def test_play_requires_preset(c, zone): + assert c.post(f"/zones/{zone}/play", json={}).status_code == 400 + + +def test_play_unknown_preset(c, zone): + assert c.post(f"/zones/{zone}/play", json={"preset_id": "nope"}).status_code == 404 + + +@missing("zone stop reply ({stopped})") +def test_play_and_stop(c, zone): + preset = new_id(c.post("/presets", json={"name": "pytest-on", "pattern": "on", "colors": ["#ff0000"]})) + resp = c.post(f"/zones/{zone}/play", json={"preset_id": preset}) + assert resp.status_code == 200, resp.text + assert c.get("/zones/engine/status").status_code == 200 + resp = c.post(f"/zones/{zone}/stop") + assert resp.status_code == 200 + assert resp.json()["stopped"] is True diff --git a/test/browser/test_browser.py b/test/browser/test_browser.py new file mode 100644 index 0000000..f8fa544 --- /dev/null +++ b/test/browser/test_browser.py @@ -0,0 +1,1131 @@ +#!/usr/bin/env python3 +""" +Browser automation tests using Selenium. +Tests run against the controller in an actual browser. Set the target with +``LED_HOST`` or ``LED_CONTROLLER_DEVICE_IP`` (IP or hostname, or a full +``http://`` / ``https://`` base URL); the default is ``led-controller.local``. +Ported from the v1 app's tests/test_browser.py. + +Fixed delays between UI steps use ``LED_CONTROLLER_BROWSER_SLEEP_SCALE`` +(default ``0.5``, i.e. half the nominal pause). Set to ``1`` for the old pacing, +or ``0`` to skip fixed sleeps (may flake). Driver implicit wait defaults to +``2`` seconds; override with ``LED_CONTROLLER_BROWSER_IMPLICIT_WAIT``. + +Needs selenium plus headless Chromium and chromedriver (or Firefox and geckodriver). +""" + +import os +import sys + +import pytest + +if os.environ.get("LED_CONTROLLER_RUN_BROWSER_TESTS") != "1": + # pytest catches Skipped; plain `python tests/test_browser.py` does not. + if __name__ == "__main__": + print( + "Browser tests are disabled by default. " + "Set LED_CONTROLLER_RUN_BROWSER_TESTS=1 to run.", + file=sys.stderr, + ) + raise SystemExit(0) + pytest.skip( + "Browser tests are opt-in: set LED_CONTROLLER_RUN_BROWSER_TESTS=1.", + allow_module_level=True, + ) +import time +import requests +from typing import Optional, List + +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.chrome.options import Options as ChromeOptions +from selenium.webdriver.firefox.options import Options as FirefoxOptions +from selenium.webdriver.common.action_chains import ActionChains +from selenium.common.exceptions import ( + TimeoutException, + NoSuchElementException, + ElementNotInteractableException, +) + +_DEFAULT_DEVICE_HOST = "led-controller.local" + + +def _device_base_url() -> str: + raw = (os.environ.get("LED_CONTROLLER_DEVICE_IP") or os.environ.get("LED_HOST") or _DEFAULT_DEVICE_HOST).strip() + if not raw: + raw = _DEFAULT_DEVICE_HOST + if raw.startswith(("http://", "https://")): + return raw.rstrip("/") + return f"http://{raw}" + + +# Base URL for the device +BASE_URL = _device_base_url() + + +def _browser_sleep(seconds: float) -> None: + """Scale fixed UI pauses via LED_CONTROLLER_BROWSER_SLEEP_SCALE (default 0.5).""" + try: + scale = float(os.environ.get("LED_CONTROLLER_BROWSER_SLEEP_SCALE", "0.5")) + except ValueError: + scale = 0.5 + if scale <= 0: + return + time.sleep(max(0.0, float(seconds)) * scale) + + +def _implicit_wait_s() -> int: + try: + v = float(os.environ.get("LED_CONTROLLER_BROWSER_IMPLICIT_WAIT", "2")) + except ValueError: + v = 2.0 + return int(max(0, min(60, round(v)))) + + +class BrowserTest: + """Browser automation test class.""" + + def __init__(self, base_url: str = BASE_URL, headless: bool = False): + self.base_url = base_url + self.driver = None + self.headless = headless + self.created_zones: List[str] = [] + self.created_profiles: List[str] = [] + self.created_presets: List[str] = [] + + def setup(self): + """Set up the browser driver. Tries Chrome first, then Firefox.""" + err_chrome, err_firefox = None, None + # Try Chrome first + try: + opts = ChromeOptions() + if self.headless: + opts.add_argument('--headless') + opts.add_argument('--no-sandbox') + opts.add_argument('--disable-dev-shm-usage') + opts.add_argument('--disable-gpu') + opts.add_argument('--window-size=1920,1080') + self.driver = webdriver.Chrome(options=opts) + self.driver.implicitly_wait(_implicit_wait_s()) + print("✓ Browser started (Chrome)") + return True + except Exception as e: + err_chrome = e + # Fallback to Firefox + try: + opts = FirefoxOptions() + if self.headless: + opts.add_argument('--headless') + self.driver = webdriver.Firefox(options=opts) + self.driver.implicitly_wait(_implicit_wait_s()) + print("✓ Browser started (Firefox)") + return True + except Exception as e: + err_firefox = e + print("✗ Failed to start browser.") + if err_chrome: + print(f" Chrome: {err_chrome}") + if err_firefox: + print(f" Firefox: {err_firefox}") + print(" On Raspberry Pi (aarch64), install: chromium-browser and chromium-chromedriver") + return False + + def teardown(self): + """Close the browser.""" + if self.driver: + self.driver.quit() + print("✓ Browser closed") + + def navigate(self, path: str = '/'): + """Navigate to a URL.""" + url = f"{self.base_url}{path}" + try: + self.driver.get(url) + _browser_sleep(1) # Wait for page load + return True + except Exception as e: + print(f"✗ Failed to navigate to {url}: {e}") + return False + + def wait_for_element(self, by, value, timeout=10): + """Wait for an element to appear.""" + try: + element = WebDriverWait(self.driver, timeout).until( + EC.presence_of_element_located((by, value)) + ) + return element + except TimeoutException: + return None + + def _scroll_into_view(self, element) -> None: + self.driver.execute_script( + "arguments[0].scrollIntoView({block: 'center', inline: 'nearest'});", + element, + ) + + def click_element(self, by, value, timeout=10, use_js=False): + """Click an element.""" + try: + element = self.wait_for_element(by, value, timeout) + if element: + self._scroll_into_view(element) + if use_js: + # Use JavaScript click for elements that might be intercepted + self.driver.execute_script("arguments[0].click();", element) + else: + # Try normal click first, fall back to JS if it fails + try: + element.click() + except Exception: + self.driver.execute_script("arguments[0].click();", element) + _browser_sleep(0.5) # Wait for action + return True + return False + except Exception as e: + print(f"✗ Failed to click {value}: {e}") + return False + + def handle_alert(self, accept=True, timeout=2): + """Handle an alert dialog.""" + try: + alert = WebDriverWait(self.driver, timeout).until(EC.alert_is_present()) + if accept: + alert.accept() + else: + alert.dismiss() + _browser_sleep(0.3) + return True + except TimeoutException: + return False + except Exception as e: + print(f"✗ Failed to handle alert: {e}") + return False + + def cleanup_test_data(self): + """Clean up test data created during tests.""" + print("\n Cleaning up test data...") + try: + # Use requests to make API calls for cleanup + session = requests.Session() + + # Delete created presets by ID + for preset_id in self.created_presets: + try: + response = session.delete(f"{self.base_url}/presets/{preset_id}") + if response.status_code == 200: + print(f" ✓ Cleaned up preset: {preset_id}") + except Exception as e: + print(f" ⚠ Failed to cleanup preset {preset_id}: {e}") + + # Delete created zones by ID + for zone_id in self.created_zones: + try: + response = session.delete(f"{self.base_url}/zones/{zone_id}") + if response.status_code == 200: + print(f" ✓ Cleaned up zone: {zone_id}") + except Exception as e: + print(f" ⚠ Failed to cleanup zone {zone_id}: {e}") + + # Delete created profiles by ID + for profile_id in self.created_profiles: + try: + response = session.delete(f"{self.base_url}/profiles/{profile_id}") + if response.status_code == 200: + print(f" ✓ Cleaned up profile: {profile_id}") + except Exception as e: + print(f" ⚠ Failed to cleanup profile {profile_id}: {e}") + + # Also try to cleanup by name pattern (in case IDs weren't tracked) + test_names = ['Browser Test Zone', 'Browser Test Profile', 'Browser Test Preset', + 'Preset 1', 'Preset 2', 'Preset 3', 'Edited Browser Zone'] + + # Cleanup zones by name + try: + zones_response = session.get(f"{self.base_url}/zones") + if zones_response.status_code == 200: + zones_data = zones_response.json() + zones_map = zones_data.get('zones', {}) + for zone_id, zone_row in zones_map.items(): + if isinstance(zone_row, dict) and zone_row.get('name') in test_names: + try: + session.delete(f"{self.base_url}/zones/{zone_id}") + print(f" ✓ Cleaned up zone by name: {zone_row.get('name')}") + except: + pass + except: + pass + + # Cleanup profiles by name + try: + profiles_response = session.get(f"{self.base_url}/profiles") + if profiles_response.status_code == 200: + profiles_data = profiles_response.json() + profiles = profiles_data.get('profiles', {}) + for profile_id, profile_data in profiles.items(): + if isinstance(profile_data, dict) and profile_data.get('name') in test_names: + try: + session.delete(f"{self.base_url}/profiles/{profile_id}") + print(f" ✓ Cleaned up profile by name: {profile_data.get('name')}") + except: + pass + except: + pass + + # Cleanup presets by name + try: + presets_response = session.get(f"{self.base_url}/presets") + if presets_response.status_code == 200: + presets_data = presets_response.json() + presets = presets_data.get('presets', {}) if isinstance(presets_data, dict) else presets_data + for preset_id, preset_data in presets.items(): + if isinstance(preset_data, dict) and preset_data.get('name') in test_names: + try: + session.delete(f"{self.base_url}/presets/{preset_id}") + print(f" ✓ Cleaned up preset by name: {preset_data.get('name')}") + except: + pass + except: + pass + + # Clear the lists + self.created_zones.clear() + self.created_profiles.clear() + self.created_presets.clear() + except Exception as e: + print(f" ⚠ Cleanup error: {e}") + + def fill_input(self, by, value, text, timeout=10): + """Fill an input field.""" + try: + element = self.wait_for_element(by, value, timeout) + if element: + self._scroll_into_view(element) + # Chrome often reports as not interactable for clear/send_keys. + if (element.get_attribute("type") or "").lower() == "color": + hex_v = text.strip() + if hex_v and not hex_v.startswith("#"): + hex_v = "#" + hex_v + self.driver.execute_script( + """ + var el = arguments[0], v = arguments[1]; + el.value = v; + el.dispatchEvent(new Event('input', {bubbles: true})); + el.dispatchEvent(new Event('change', {bubbles: true})); + """, + element, + hex_v, + ) + return True + element.clear() + try: + element.send_keys(text) + except ElementNotInteractableException: + self.driver.execute_script( + "arguments[0].value = arguments[1];" + "arguments[0].dispatchEvent(new Event('input', {bubbles: true}));" + "arguments[0].dispatchEvent(new Event('change', {bubbles: true}));", + element, + text, + ) + return True + return False + except Exception as e: + print(f"✗ Failed to fill {value}: {e}") + return False + + def get_text(self, by, value, timeout=10): + """Get text from an element.""" + try: + element = self.wait_for_element(by, value, timeout) + if element: + return element.text + return None + except Exception as e: + return None + + def get_cookie(self, name: str): + """Get a cookie value.""" + try: + return self.driver.get_cookie(name) + except: + return None + + def drag_and_drop(self, source_element, target_element): + """Perform drag and drop operation.""" + try: + actions = ActionChains(self.driver) + actions.drag_and_drop(source_element, target_element).perform() + _browser_sleep(0.5) # Wait for drop to complete + return True + except Exception as e: + print(f"✗ Drag and drop failed: {e}") + return False + + def drag_and_drop_by_offset(self, element, x_offset, y_offset): + """Perform drag and drop by offset.""" + try: + actions = ActionChains(self.driver) + actions.drag_and_drop_by_offset(element, x_offset, y_offset).perform() + _browser_sleep(0.5) + return True + except Exception as e: + print(f"✗ Drag and drop by offset failed: {e}") + return False + + +@pytest.fixture +def browser() -> BrowserTest: + return BrowserTest() + + +def test_browser_connection(browser: BrowserTest) -> bool: + """Test basic browser connection.""" + print("Testing browser connection...") + if not browser.setup(): + return False + + try: + if browser.navigate('/'): + print("✓ Successfully loaded page") + title = browser.driver.title + print(f" Page title: {title}") + return True + else: + print("✗ Failed to load page") + return False + finally: + browser.teardown() + +def test_zones_ui(browser: BrowserTest) -> bool: + """Test zones UI in browser.""" + print("\n=== Testing Zones UI in Browser ===") + passed = 0 + total = 0 + + if not browser.setup(): + return False + + try: + # Test 1: Load page + total += 1 + if browser.navigate('/'): + print("✓ Loaded main page") + passed += 1 + else: + print("✗ Failed to load main page") + browser.teardown() + return False + + # Test 2: Open zones modal + total += 1 + if browser.click_element(By.ID, 'zones-btn'): + print("✓ Clicked Zones button") + # Wait for modal to appear + _browser_sleep(0.5) + modal = browser.wait_for_element(By.ID, 'zones-modal') + if modal and 'active' in modal.get_attribute('class'): + print("✓ Zones modal opened") + passed += 1 + else: + print("✗ Zones modal didn't open") + else: + print("✗ Failed to click Zones button") + + # Test 3: Create a zone via UI + total += 1 + try: + # Fill in zone name + if browser.fill_input(By.ID, 'new-zone-name', 'Browser Test Zone'): + print(" ✓ Filled zone name") + # Devices default from registry or placeholder name "1" + # Click create button + if browser.click_element(By.ID, 'create-zone-btn'): + print(" ✓ Clicked create button") + _browser_sleep(1) # Wait for creation + # Check if zone appears in list and extract ID + tabs_list = browser.wait_for_element(By.ID, 'zones-list-modal') + if tabs_list: + list_text = tabs_list.text + if 'Browser Test Zone' in list_text: + print("✓ Created zone via UI") + # Try to extract zone ID from the list (look for data-zone-id attribute) + try: + tab_rows = browser.driver.find_elements(By.CSS_SELECTOR, '#zones-list-modal .profiles-row') + for row in tab_rows: + if 'Browser Test Zone' in row.text: + zone_id = row.get_attribute('data-zone-id') + if zone_id: + browser.created_zones.append(zone_id) + break + except: + pass # If we can't extract ID, cleanup will try by name + passed += 1 + else: + print("✗ Zone not found in list after creation") + else: + print("✗ Zones list not found") + else: + print("✗ Failed to click create button") + except Exception as e: + print(f"✗ Failed to create zone via UI: {e}") + + # Test 4: Edit a zone via UI (right-click in zones list) + total += 1 + try: + # First, close and reopen modal to refresh + browser.click_element(By.ID, 'zones-close-btn') + _browser_sleep(0.5) + browser.click_element(By.ID, 'zones-btn') + _browser_sleep(0.5) + + # Right-click the row corresponding to 'Browser Test Zone' + try: + tab_row = browser.driver.find_element( + By.XPATH, + "//div[@id='zones-list-modal']//div[contains(@class,'profiles-row')][.//span[contains(text(), 'Browser Test Zone')]]" + ) + except Exception: + tab_row = None + + if tab_row: + actions = ActionChains(browser.driver) + actions.context_click(tab_row).perform() + _browser_sleep(0.5) + + # Check if edit modal opened + edit_modal = browser.wait_for_element(By.ID, 'edit-zone-modal') + if edit_modal: + print("✓ Edit modal opened via right-click") + # Fill in new name + if browser.fill_input(By.ID, 'edit-zone-name', 'Edited Browser Zone'): + print(" ✓ Filled new zone name") + # Submit form + edit_form = browser.wait_for_element(By.ID, 'edit-zone-form') + if edit_form: + browser.driver.execute_script("arguments[0].submit();", edit_form) + _browser_sleep(1) # Wait for update + print("✓ Submitted edit form") + passed += 1 + else: + print("✗ Edit form not found") + else: + print("✗ Edit modal didn't open after right-click") + else: + print("✗ Could not find zone row for 'Browser Test Zone'") + except Exception as e: + print(f"✗ Failed to edit zone via UI: {e}") + import traceback + traceback.print_exc() + + # Test 5: Check current zone cookie + total += 1 + cookie = browser.get_cookie('current_zone') + if cookie: + print(f"✓ Found current_zone cookie: {cookie.get('value')}") + passed += 1 + else: + print("⚠ No current_zone cookie found (might be normal if no zone selected)") + passed += 1 # Not a failure, just informational + + # Close modal + browser.click_element(By.ID, 'zones-close-btn') + + except Exception as e: + print(f"✗ Browser test error: {e}") + import traceback + traceback.print_exc() + finally: + browser.cleanup_test_data() + browser.teardown() + + print(f"\nBrowser zones UI tests: {passed}/{total} passed") + return passed == total + +def test_profiles_ui(browser: BrowserTest) -> bool: + """Test profiles UI in browser.""" + print("\n=== Testing Profiles UI in Browser ===") + passed = 0 + total = 0 + + if not browser.setup(): + return False + + try: + # Test 1: Load page + total += 1 + if browser.navigate('/'): + print("✓ Loaded main page") + passed += 1 + else: + browser.teardown() + return False + + # Test 2: Open profiles modal + total += 1 + if browser.click_element(By.ID, 'profiles-btn'): + print("✓ Clicked Profiles button") + _browser_sleep(0.5) + modal = browser.wait_for_element(By.ID, 'profiles-modal') + if modal: + print("✓ Profiles modal opened") + passed += 1 + else: + print("✗ Profiles modal didn't open") + + # Test 3: Create profile via UI + total += 1 + try: + if browser.fill_input(By.ID, 'new-profile-name', 'Browser Test Profile'): + print(" ✓ Filled profile name") + if browser.click_element(By.ID, 'create-profile-btn'): + print(" ✓ Clicked create button") + _browser_sleep(1) + # Check if profile appears + profiles_list = browser.wait_for_element(By.ID, 'profiles-list') + if profiles_list and 'Browser Test Profile' in profiles_list.text: + print("✓ Created profile via UI") + passed += 1 + else: + print("✗ Profile not found in list") + except Exception as e: + print(f"✗ Failed to create profile: {e}") + + # Close modal + browser.click_element(By.ID, 'profiles-close-btn') + + except Exception as e: + print(f"✗ Browser test error: {e}") + import traceback + traceback.print_exc() + finally: + browser.cleanup_test_data() + browser.teardown() + + print(f"\nBrowser profiles UI tests: {passed}/{total} passed") + return passed == total + + +def test_mobile_tab_presets_two_columns(): + """ + Verify that the zone preset selecting area shows roughly two preset tiles per row + on a phone-sized viewport. + """ + bt = BrowserTest(base_url=BASE_URL, headless=True) + if not bt.setup(): + assert False, "Failed to start browser" + + try: + # Simulate a mobile viewport + bt.driver.set_window_size(400, 800) + assert bt.navigate('/'), "Failed to load main page" + + # Click the first zone button to load presets for that zone + first_tab = bt.wait_for_element(By.CSS_SELECTOR, '.zone-button', timeout=10) + assert first_tab is not None, "No zone buttons found" + first_tab.click() + _browser_sleep(1) + + container = bt.wait_for_element(By.ID, 'presets-list-zone', timeout=10) + assert container is not None, "presets-list-zone not found" + + tiles = bt.driver.find_elements(By.CSS_SELECTOR, '#presets-list-zone .preset-tile-row') + # Need at least 2 presets to make this meaningful + assert len(tiles) >= 2, "Fewer than 2 presets found for zone" + + container_width = container.size['width'] + first_width = tiles[0].size['width'] + + # Each tile should be about half the container width (tolerate some margin) + assert 0.4 * container_width <= first_width <= 0.6 * container_width, ( + f"Preset tile width {first_width} not ~half of container {container_width}" + ) + finally: + bt.teardown() + +def test_presets_ui(browser: BrowserTest) -> bool: + """Test presets UI in browser.""" + print("\n=== Testing Presets UI in Browser ===") + passed = 0 + total = 0 + + if not browser.setup(): + return False + + try: + # Test 1: Load page + total += 1 + if browser.navigate('/'): + print("✓ Loaded main page") + passed += 1 + else: + browser.teardown() + return False + + # Test 2: Open presets modal + total += 1 + if browser.click_element(By.ID, 'presets-btn'): + print("✓ Clicked Presets button") + _browser_sleep(0.5) + modal = browser.wait_for_element(By.ID, 'presets-modal') + if modal: + print("✓ Presets modal opened") + passed += 1 + else: + print("✗ Presets modal didn't open") + + # Test 3: Click Add button to open preset editor + total += 1 + try: + if browser.click_element(By.ID, 'preset-add-btn'): + print(" ✓ Clicked Add Preset button") + _browser_sleep(0.5) + editor_modal = browser.wait_for_element(By.ID, 'preset-editor-modal') + if editor_modal: + print("✓ Preset editor modal opened") + passed += 1 + else: + print("✗ Preset editor modal didn't open") + else: + print("✗ Failed to click Add Preset button") + except Exception as e: + print(f"✗ Failed to open preset editor: {e}") + + # Test 4: Create a preset via UI + total += 1 + try: + # Fill preset name + if browser.fill_input(By.ID, 'preset-name-input', 'Browser Test Preset'): + print(" ✓ Filled preset name") + # Select a pattern + pattern_select = browser.wait_for_element(By.ID, 'preset-pattern-input') + if pattern_select: + # Try to select first available pattern + from selenium.webdriver.support.ui import Select + select = Select(pattern_select) + if len(select.options) > 1: # More than just the placeholder + select.select_by_index(1) # Select first real pattern + print(" ✓ Selected pattern") + # Add a color + if browser.fill_input(By.ID, 'preset-new-color', '#ff0000'): + print(" ✓ Set color") + if browser.click_element(By.ID, 'preset-add-color-btn'): + print(" ✓ Added color") + # Set brightness + if browser.fill_input(By.ID, 'preset-brightness-input', '200'): + print(" ✓ Set brightness") + # Save preset + if browser.click_element(By.ID, 'preset-save-btn'): + print(" ✓ Clicked save button") + _browser_sleep(1) + # Check if preset appears in list + presets_list = browser.wait_for_element(By.ID, 'presets-list') + if presets_list and 'Browser Test Preset' in presets_list.text: + print("✓ Created preset via UI") + passed += 1 + else: + print("✗ Preset not found in list after creation") + else: + print("✗ Failed to click save button") + except Exception as e: + print(f"✗ Failed to create preset: {e}") + import traceback + traceback.print_exc() + + # Close editor modal + browser.click_element(By.ID, 'preset-editor-close-btn', use_js=True) + _browser_sleep(0.5) + # Close presets modal + browser.click_element(By.ID, 'presets-close-btn', use_js=True) + + except Exception as e: + print(f"✗ Browser test error: {e}") + import traceback + traceback.print_exc() + finally: + browser.cleanup_test_data() + browser.teardown() + + print(f"\nBrowser presets UI tests: {passed}/{total} passed") + return passed == total + +def test_color_palette_ui(browser: BrowserTest) -> bool: + """Test color palette UI in browser.""" + print("\n=== Testing Color Palette UI in Browser ===") + passed = 0 + total = 0 + + if not browser.setup(): + return False + + try: + # Test 1: Load page + total += 1 + if browser.navigate('/'): + print("✓ Loaded main page") + passed += 1 + else: + browser.teardown() + return False + + # Test 2: Open color palette modal + total += 1 + if browser.click_element(By.ID, 'color-palette-btn'): + print("✓ Clicked Color Palette button") + _browser_sleep(0.5) + modal = browser.wait_for_element(By.ID, 'color-palette-modal') + if modal: + print("✓ Color palette modal opened") + passed += 1 + else: + print("✗ Color palette modal didn't open") + + # Test 3: Add a color to palette + total += 1 + try: + # Set color picker - use a unique color that's likely not in palette + color_input = browser.wait_for_element(By.ID, 'palette-new-color') + if color_input: + # Use a unique color (purple) that's less likely to be in palette + browser.driver.execute_script("arguments[0].value = '#9b59b6'; arguments[0].dispatchEvent(new Event('input'));", color_input) + print(" ✓ Set color to #9b59b6") + # Click add color button + if browser.click_element(By.ID, 'palette-add-color-btn'): + print(" ✓ Clicked Add Color button") + _browser_sleep(0.5) + # Handle alert if color already exists + browser.handle_alert(accept=True, timeout=1) + # Check if color appears in palette + palette_container = browser.wait_for_element(By.ID, 'palette-container') + if palette_container: + # Look for color swatches + color_swatches = browser.driver.find_elements(By.CSS_SELECTOR, '#palette-container .draggable-color-swatch, #palette-container [style*="background-color"]') + if color_swatches: + print("✓ Added color to palette") + passed += 1 + else: + print("✗ Color not found in palette after adding") + else: + print("✗ Palette container not found") + else: + print("✗ Failed to click Add Color button") + except Exception as e: + print(f"✗ Failed to add color: {e}") + import traceback + traceback.print_exc() + + # Test 4: Test drag and drop colors (if multiple colors exist) + total += 1 + try: + color_swatches = browser.driver.find_elements(By.CSS_SELECTOR, '#palette-container .draggable-color-swatch, #palette-container [draggable="true"]') + if len(color_swatches) >= 2: + # Drag first color to second position + source = color_swatches[0] + target = color_swatches[1] + if browser.drag_and_drop(source, target): + print("✓ Dragged color to reorder") + _browser_sleep(0.5) + passed += 1 + else: + print("✗ Drag and drop failed") + else: + print("⚠ Not enough colors to test drag and drop (need at least 2)") + passed += 1 # Not a failure + except Exception as e: + print(f"✗ Drag and drop test error: {e}") + + # Close modal + browser.click_element(By.ID, 'color-palette-close-btn', use_js=True) + + except Exception as e: + print(f"✗ Browser test error: {e}") + import traceback + traceback.print_exc() + finally: + browser.cleanup_test_data() + browser.teardown() + + print(f"\nBrowser color palette UI tests: {passed}/{total} passed") + return passed >= total - 1 # Allow one failure (alert handling might be flaky) + +def test_preset_drag_and_drop(browser: BrowserTest) -> bool: + """Test dragging presets around in a zone.""" + print("\n=== Testing Preset Drag and Drop in Zone ===") + passed = 0 + total = 0 + + if not browser.setup(): + return False + + try: + # Test 1: Load page and ensure we have a zone + total += 1 + if browser.navigate('/'): + print("✓ Loaded main page") + passed += 1 + else: + browser.teardown() + return False + + # Test 2: Open zones modal and create/select a zone + total += 1 + browser.click_element(By.ID, 'zones-btn') + _browser_sleep(0.5) + + # Check if we have zones, if not create one + tabs_list = browser.wait_for_element(By.ID, 'zones-list-modal') + if tabs_list and 'No zones found' in tabs_list.text: + # Create a zone + browser.fill_input(By.ID, 'new-zone-name', 'Drag Test Zone') + browser.click_element(By.ID, 'create-zone-btn') + _browser_sleep(1) + + # Select first zone (or the one we just created) + select_buttons = browser.driver.find_elements(By.XPATH, "//button[contains(text(), 'Select')]") + if select_buttons: + select_buttons[0].click() + _browser_sleep(1) + print("✓ Selected a zone") + passed += 1 + else: + print("✗ No zones available to select") + browser.click_element(By.ID, 'zones-close-btn') + browser.teardown() + return False + + browser.click_element(By.ID, 'zones-close-btn', use_js=True) + _browser_sleep(0.5) + + # Test 3: Open presets modal and create presets + total += 1 + browser.click_element(By.ID, 'presets-btn') + _browser_sleep(0.5) + + # Create first preset + browser.click_element(By.ID, 'preset-add-btn') + _browser_sleep(0.5) + browser.fill_input(By.ID, 'preset-name-input', 'Preset 1') + browser.fill_input(By.ID, 'preset-new-color', '#ff0000') + browser.click_element(By.ID, 'preset-add-color-btn') + browser.click_element(By.ID, 'preset-save-btn') + _browser_sleep(1) + + # Create second preset + browser.click_element(By.ID, 'preset-add-btn') + _browser_sleep(0.5) + browser.fill_input(By.ID, 'preset-name-input', 'Preset 2') + browser.fill_input(By.ID, 'preset-new-color', '#00ff00') + browser.click_element(By.ID, 'preset-add-color-btn') + browser.click_element(By.ID, 'preset-save-btn') + _browser_sleep(1) + + # Create third preset + browser.click_element(By.ID, 'preset-add-btn') + _browser_sleep(0.5) + browser.fill_input(By.ID, 'preset-name-input', 'Preset 3') + browser.fill_input(By.ID, 'preset-new-color', '#0000ff') + browser.click_element(By.ID, 'preset-add-color-btn') + browser.click_element(By.ID, 'preset-save-btn') + _browser_sleep(1) + + browser.click_element(By.ID, 'presets-close-btn', use_js=True) + _browser_sleep(0.5) + + print("✓ Created 3 presets for drag test") + passed += 1 + + # Test 4: Add presets to the zone (via Edit Zone modal – Add buttons in list) + total += 1 + try: + zone_id = browser.driver.execute_script( + "return (window.tabsManager && window.tabsManager.getCurrentTabId && window.tabsManager.getCurrentTabId()) || null;" + ) + if not zone_id: + print("✗ Could not get current zone id") + else: + browser.driver.execute_script( + "if (window.tabsManager && window.tabsManager.openEditTabModal) { window.tabsManager.openEditTabModal(arguments[0], null); }", + zone_id + ) + _browser_sleep(1) + list_el = browser.wait_for_element(By.ID, 'edit-zone-presets-list', timeout=5) + if list_el: + select_buttons = browser.driver.find_elements(By.XPATH, "//div[@id='edit-zone-presets-list']//button[text()='Add']") + if len(select_buttons) >= 2: + browser.driver.execute_script("arguments[0].click();", select_buttons[0]) + _browser_sleep(1.5) + browser.handle_alert(accept=True, timeout=1) + select_buttons = browser.driver.find_elements(By.XPATH, "//div[@id='edit-zone-presets-list']//button[text()='Add']") + if len(select_buttons) >= 1: + browser.driver.execute_script("arguments[0].click();", select_buttons[0]) + _browser_sleep(1.5) + browser.handle_alert(accept=True, timeout=1) + print(" ✓ Added 2 presets to zone") + passed += 1 + elif len(select_buttons) == 1: + browser.driver.execute_script("arguments[0].click();", select_buttons[0]) + _browser_sleep(1.5) + browser.handle_alert(accept=True, timeout=1) + print(" ✓ Added 1 preset to zone") + passed += 1 + else: + print(" ⚠ No presets available to add (all already in zone)") + else: + print("✗ Edit zone presets list not found") + except Exception as e: + print(f"✗ Failed to add presets to zone: {e}") + import traceback + traceback.print_exc() + + # Test 5: Find presets in zone and test drag and drop (Edit mode only) + total += 1 + try: + # Wait for presets to load in the zone + presets_list_tab = browser.wait_for_element(By.ID, 'presets-list-zone', timeout=5) + if presets_list_tab: + _browser_sleep(1) # Wait for presets to render + + # Reordering is only available in Edit mode (tiles get .draggable-preset) + mode_toggle = browser.wait_for_element(By.CSS_SELECTOR, '.ui-mode-toggle', timeout=5) + if mode_toggle and mode_toggle.get_attribute('aria-pressed') == 'false': + mode_toggle.click() + _browser_sleep(0.5) + + # Find draggable preset elements - wait a bit more for rendering + _browser_sleep(1) + draggable_presets = browser.driver.find_elements(By.CSS_SELECTOR, '#presets-list-zone .draggable-preset') + if len(draggable_presets) >= 2: + print(f" ✓ Found {len(draggable_presets)} draggable presets") + + # Get initial order + initial_order = [p.text for p in draggable_presets] + print(f" Initial order: {initial_order[:3]}") # Show first 3 + + # Drag first preset down + source = draggable_presets[0] + target = draggable_presets[1] + + # Use ActionChains for drag and drop + actions = ActionChains(browser.driver) + actions.click_and_hold(source).move_to_element(target).release().perform() + _browser_sleep(1) # Wait for reorder to complete + + # Check if order changed + draggable_presets_after = browser.driver.find_elements(By.CSS_SELECTOR, '#presets-list-zone .draggable-preset') + if len(draggable_presets_after) >= 2: + new_order = [p.text for p in draggable_presets_after] + print(f" New order: {new_order[:3]}") + + if initial_order != new_order: + print("✓ Preset drag and drop worked - order changed") + passed += 1 + else: + print("⚠ Order didn't change (might need to verify with API)") + passed += 1 # Not necessarily a failure + else: + print("✗ Presets disappeared after drag") + elif len(draggable_presets) == 1: + print(f"⚠ Only 1 preset found in zone (need 2 for drag test). Preset: {draggable_presets[0].text}") + zone_id = browser.driver.execute_script( + "return (window.tabsManager && window.tabsManager.getCurrentTabId && window.tabsManager.getCurrentTabId()) || null;" + ) + if zone_id: + browser.driver.execute_script( + "if (window.tabsManager && window.tabsManager.openEditTabModal) { window.tabsManager.openEditTabModal(arguments[0], null); }", + zone_id + ) + _browser_sleep(1) + select_buttons = browser.driver.find_elements(By.XPATH, "//div[@id='edit-zone-presets-list']//button[text()='Add']") + if select_buttons: + print(" Attempting to add another preset...") + browser.driver.execute_script("arguments[0].click();", select_buttons[0]) + _browser_sleep(1.5) + browser.handle_alert(accept=True, timeout=1) + try: + browser.driver.execute_script("document.getElementById('edit-zone-modal').classList.remove('active');") + except Exception: + pass + _browser_sleep(1) + draggable_presets = browser.driver.find_elements(By.CSS_SELECTOR, '#presets-list-zone .draggable-preset') + if len(draggable_presets) >= 2: + print(" ✓ Added another preset, now testing drag...") + source = draggable_presets[0] + target = draggable_presets[1] + actions = ActionChains(browser.driver) + actions.click_and_hold(source).move_to_element(target).release().perform() + _browser_sleep(1) + print("✓ Performed drag and drop") + passed += 1 + else: + print(f" ✗ Still only {len(draggable_presets)} preset(s) after adding") + else: + print(" ✗ No Add buttons found in Edit Zone modal") + else: + print(f"✗ No presets found in zone (found {len(draggable_presets)})") + else: + print("✗ Presets list in zone not found") + except Exception as e: + print(f"✗ Drag and drop test error: {e}") + import traceback + traceback.print_exc() + + except Exception as e: + print(f"✗ Browser test error: {e}") + import traceback + traceback.print_exc() + finally: + browser.cleanup_test_data() + browser.teardown() + + print(f"\nBrowser preset drag and drop tests: {passed}/{total} passed") + return passed >= total - 2 # Allow up to 2 failures (drag test and adding presets can be flaky) + +def main(): + """Run all browser tests.""" + print("=" * 60) + print("LED Controller Browser Tests") + print(f"Testing against: {BASE_URL}") + print("=" * 60) + + # On Pi OS Lite there is no browser by default; skip with exit 0 instead of failing + browser = BrowserTest(headless=True) + if not browser.setup(): + print("\nSkipped (Pi OS Lite / no browser). Install chromium-browser and") + print("chromium-chromedriver to run browser tests, or run on Pi OS with desktop.") + sys.exit(0) + browser.teardown() + + browser = BrowserTest(headless=False) # Set to True for headless mode + + results = [] + + # Run browser tests + results.append(("Browser Connection", test_browser_connection(browser))) + results.append(("Zones UI", test_zones_ui(browser))) + results.append(("Profiles UI", test_profiles_ui(browser))) + results.append(("Presets UI", test_presets_ui(browser))) + results.append(("Color Palette UI", test_color_palette_ui(browser))) + results.append(("Preset Drag and Drop", test_preset_drag_and_drop(browser))) + + # Summary + print("\n" + "=" * 60) + print("Browser Test Summary") + print("=" * 60) + all_passed = True + for name, passed in results: + status = "✓ PASS" if passed else "✗ FAIL" + print(f"{status} - {name}") + if not passed: + all_passed = False + + print("=" * 60) + if all_passed: + print("✓ All browser tests passed!") + sys.exit(0) + else: + print("✗ Some browser tests failed") + sys.exit(1) + +if __name__ == "__main__": + main()