first push

This commit is contained in:
jhartworks committed 2026-11-09 10:37:41 +01:00
commit 2a81b4a502
845 files changed
+356635

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Tests for NextFloor."""
+28
View File
@@ -0,0 +1,28 @@
"""Fixtures for NextFloor tests."""
from __future__ import annotations
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
from homeassistant.core import HomeAssistant
import pytest
@pytest.fixture(autouse=True)
def auto_enable_custom_integrations(enable_custom_integrations):
"""Enable loading custom integrations in all tests."""
return
@pytest.fixture(autouse=True)
def mock_frontend(hass: HomeAssistant) -> Generator[dict[str, object]]:
"""Stand in for the frontend and panel_custom components (hass_frontend is not installed in tests)."""
hass.config.components.update({"frontend", "panel_custom"})
with (
patch("homeassistant.components.frontend.add_extra_js_url") as add_js,
patch("homeassistant.components.frontend.remove_extra_js_url") as remove_js,
patch("homeassistant.components.frontend.async_remove_panel") as remove_panel,
patch("homeassistant.components.panel_custom.async_register_panel", new_callable=AsyncMock) as register,
):
yield {"add_js": add_js, "remove_js": remove_js, "remove_panel": remove_panel, "register": register}
+249
View File
@@ -0,0 +1,249 @@
"""Announcements: which rooms and speakers, how each speaker is spoken to, quiet times and the screens."""
from __future__ import annotations
import copy
from datetime import time
from typing import Any
from unittest.mock import patch
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import area_registry as ar
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
import pytest
from pytest_homeassistant_custom_component.common import MockConfigEntry, async_mock_service
from custom_components.nextfloor.announce import in_quiet_time, target_rooms
from custom_components.nextfloor.const import DOMAIN
_POINTS = {
"kitchen": [[0, 0], [4, 0], [4, 3], [0, 3]],
"living": [[4, 0], [8, 0], [8, 3], [4, 3]],
"nursery": [[0, 3], [4, 3], [4, 6], [0, 6]],
}
def _building(areas: dict[str, str | None]) -> dict[str, Any]:
def room(room_id: str, name: str) -> dict[str, Any]:
return {
"id": room_id,
"name": name,
"area_id": areas.get(room_id),
"points": _POINTS[room_id],
"floor_material": "wood",
}
return {
"version": 1,
"settings": {},
"floors": [
{
"id": "g",
"name": "Ground floor",
"elevation": 0,
"height": 2.5,
"rooms": [room("kitchen", "Kitchen"), room("living", "Living room"), room("nursery", "Nursery")],
"openings": [],
"furniture": [],
"placements": [],
},
{
"id": "u",
"name": "Upstairs",
"elevation": 2.8,
"height": 2.5,
"rooms": [{"id": "office", "name": "Office", "area_id": None, "points": _POINTS["kitchen"]}],
"openings": [],
"furniture": [],
"placements": [],
},
],
}
def test_quiet_time_also_over_midnight() -> None:
room = {"announce_quiet": {"from": "20:00", "to": "07:00"}}
assert in_quiet_time(room, time(21, 0))
assert in_quiet_time(room, time(6, 59))
assert not in_quiet_time(room, time(7, 0))
assert not in_quiet_time(room, time(12, 0))
assert in_quiet_time({"announce_quiet": {"from": "13:00", "to": "15:00"}}, time(14, 0))
assert not in_quiet_time({"announce_quiet": {"from": "13:00", "to": "13:00"}}, time(13, 0))
assert not in_quiet_time({"announce_quiet": {"from": "late", "to": "07:00"}}, time(23, 0))
assert not in_quiet_time({}, time(23, 0))
def test_rooms_by_name_id_area_and_floor() -> None:
building = _building({"nursery": "nursery_area"})
def ids(pairs: list[tuple[dict, dict]]) -> list[str]:
return [r["id"] for _, r in pairs]
assert ids(target_rooms(building, ["kitchen", "LIVING ROOM"], None)[0]) == ["kitchen", "living"]
assert ids(target_rooms(building, ["nursery_area"], None)[0]) == ["nursery"]
assert target_rooms(building, ["kitchen"], None)[1] is True
pairs, named = target_rooms(building, None, "upstairs")
assert ids(pairs) == ["office"] and named is False
assert len(target_rooms(building, None, None)[0]) == 4
assert target_rooms(building, ["cellar"], None)[0] == []
@pytest.fixture
def areas(hass: HomeAssistant) -> dict[str, str]:
reg = ar.async_get(hass)
return {
room: reg.async_create(name).id
for room, name in (("kitchen", "Kitchen"), ("living", "Living"), ("nursery", "Nursery"))
}
def _speaker(
hass: HomeAssistant,
entity_id: str,
area: str | None,
state: str = "idle",
platform: str = "test",
unique: str | None = None,
**attrs: Any,
) -> None:
domain, object_id = entity_id.split(".")
reg = er.async_get(hass)
entry = reg.async_get_or_create(domain, platform, unique or object_id, suggested_object_id=object_id)
assert entry.entity_id == entity_id
if area:
reg.async_update_entity(entity_id, area_id=area)
hass.states.async_set(entity_id, state, attrs)
async def _setup(hass: HomeAssistant, building: dict[str, Any]) -> None:
await async_setup_component(hass, "http", {})
entry = MockConfigEntry(domain=DOMAIN, data={})
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
hass.data[DOMAIN].building = copy.deepcopy(building)
async def _announce(hass: HomeAssistant, **data: Any) -> dict[str, Any]:
return await hass.services.async_call(DOMAIN, "announce", data, blocking=True, return_response=True)
async def test_each_room_speaks_through_its_own_speaker(hass: HomeAssistant, areas: dict[str, str]) -> None:
satellite = async_mock_service(hass, "assist_satellite", "announce")
speak = async_mock_service(hass, "tts", "speak")
play = async_mock_service(hass, "media_player", "play_media")
hass.states.async_set("tts.voice", "unknown")
_speaker(hass, "assist_satellite.kitchen_voice", areas["kitchen"])
_speaker(hass, "media_player.kitchen_radio", areas["kitchen"])
# a TV and a speaker that is off are never picked by themselves; a speaker that can announce gets play_media
_speaker(hass, "media_player.living_tv", areas["living"], device_class="tv")
_speaker(hass, "media_player.living_off", areas["living"], state="off")
_speaker(hass, "media_player.living_sonos", areas["living"], state="playing", supported_features=1048576)
_speaker(hass, "media_player.nursery_box", areas["nursery"])
await _setup(hass, _building(areas))
with patch("custom_components.nextfloor.announce.tts_media_id", return_value="media-source://tts/x"):
result = await _announce(hass, message="Dinner is ready!", on_screens=False)
assert result["speakers"] == {
"assist_satellite.kitchen_voice": "satellite",
"media_player.living_sonos": "announce",
"media_player.nursery_box": "tts",
}
assert satellite[0].data == {"entity_id": "assist_satellite.kitchen_voice", "message": "Dinner is ready!"}
assert play[0].data["entity_id"] == "media_player.living_sonos" and play[0].data["announce"] is True
assert speak[0].data["media_player_entity_id"] == "media_player.nursery_box"
assert speak[0].data["entity_id"] == "tts.voice"
async def test_a_speaker_chosen_or_placed_in_the_plan_wins(hass: HomeAssistant, areas: dict[str, str]) -> None:
speak = async_mock_service(hass, "tts", "speak")
hass.states.async_set("tts.voice", "unknown")
_speaker(hass, "media_player.kitchen_radio", areas["kitchen"])
_speaker(hass, "media_player.kitchen_placed", None)
_speaker(hass, "media_player.living_radio", areas["living"])
_speaker(hass, "media_player.living_chosen", None, state="off")
building = _building(areas)
ground = building["floors"][0]
ground["placements"].append({"entity_id": "media_player.kitchen_placed", "x": 1, "z": 1})
ground["rooms"][1]["announce_speaker"] = "media_player.living_chosen"
ground["rooms"][2]["announce_speaker"] = "none"
await _setup(hass, building)
result = await _announce(hass, message="Hi", on_screens=False)
assert set(result["speakers"]) == {"media_player.kitchen_placed", "media_player.living_chosen"}
assert len(speak) == 2
async def test_echos_announce_with_their_own_entity(hass: HomeAssistant, areas: dict[str, str]) -> None:
notify = async_mock_service(hass, "notify", "send_message")
alexa_media = async_mock_service(hass, "notify", "alexa_media")
# Alexa Devices: the Echo is only a notify entity whose unique id ends in -announce (and a -speak one beside it)
_speaker(
hass,
"notify.echo_kitchen_speak",
areas["kitchen"],
state="unknown",
platform="alexa_devices",
unique="SERIAL1-speak",
)
_speaker(
hass,
"notify.echo_kitchen_announce",
areas["kitchen"],
state="unknown",
platform="alexa_devices",
unique="SERIAL1-announce",
)
# Alexa Media Player (HACS): a media player, announced through notify.alexa_media
_speaker(hass, "media_player.echo_living", areas["living"], platform="alexa_media")
await _setup(hass, _building(areas))
result = await _announce(hass, message="Door!", rooms=["Kitchen", "Living room"], on_screens=False)
assert result["speakers"] == {"notify.echo_kitchen_announce": "echo", "media_player.echo_living": "echo"}
assert notify[0].data == {"entity_id": "notify.echo_kitchen_announce", "message": "Door!"}
assert alexa_media[0].data["target"] == ["media_player.echo_living"]
assert alexa_media[0].data["data"] == {"type": "announce"}
async def test_quiet_rooms_are_left_out_unless_named_alone(hass: HomeAssistant, areas: dict[str, str]) -> None:
speak = async_mock_service(hass, "tts", "speak")
hass.states.async_set("tts.voice", "unknown")
_speaker(hass, "media_player.kitchen_radio", areas["kitchen"])
_speaker(hass, "media_player.nursery_box", areas["nursery"])
building = _building(areas)
building["floors"][0]["rooms"][2]["announce_quiet"] = {"from": "00:00", "to": "23:59"}
await _setup(hass, building)
result = await _announce(hass, message="Hi", on_screens=False)
assert set(result["speakers"]) == {"media_player.kitchen_radio"}
assert result["skipped"] == {"Nursery": "quiet"}
result = await _announce(hass, message="Wake up", rooms=["Nursery"], on_screens=False)
assert set(result["speakers"]) == {"media_player.nursery_box"}
assert len(speak) == 2
async def test_without_text_to_speech_it_says_why(hass: HomeAssistant, areas: dict[str, str]) -> None:
_speaker(hass, "media_player.kitchen_radio", areas["kitchen"])
await _setup(hass, _building(areas))
with pytest.raises(ServiceValidationError):
await _announce(hass, message="Hi", on_screens=False)
with pytest.raises(ServiceValidationError):
await _announce(hass, message="Hi", rooms=["Cellar"])
async def test_screens_get_the_announcement(hass: HomeAssistant, hass_ws_client, areas: dict[str, str]) -> None:
await _setup(hass, _building(areas))
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "nextfloor/announcements/subscribe"})
assert (await client.receive_json())["success"]
result = await _announce(hass, message="Someone is at the door!", screens=["Hallway"], on_speakers=False)
assert result == {"speakers": {}, "skipped": {}, "screens": True}
event = (await client.receive_json())["event"]
assert event["message"] == "Someone is at the door!"
assert event["screens"] == ["Hallway"]
# no text-to-speech entity: the screens speak with the browser's own voice
assert event["audio"] is None
+74
View File
@@ -0,0 +1,74 @@
"""Full backup: export of plan and imported packs, restore with a fresh content check."""
from __future__ import annotations
import json
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.nextfloor.const import DOMAIN
from tests.test_init import BUILDING
PAYLOAD = {
"format": "nfpack",
"version": 1,
"id": "test.backup",
"name": "Backup",
"publisher": "Test",
"items": [
{
"id": "cube",
"name": {"de": "Würfel", "en": "Cube"},
"size": [0.5, 0.5, 0.5],
"parts": [{"shape": "box", "x": 0, "z": 0, "w": 1, "d": 1, "y": 0, "h": 1, "color": "body"}],
}
],
}
async def test_backup_round_trip(hass: HomeAssistant, hass_ws_client) -> None:
await async_setup_component(hass, "http", {})
entry = MockConfigEntry(domain=DOMAIN, data={})
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "nextfloor/packs/import", "pack": json.dumps(PAYLOAD)})
assert (await client.receive_json())["success"]
building = json.loads(json.dumps(BUILDING))
building["floors"][0]["name"] = "Backup floor"
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": building})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/backup/export"})
backup = (await client.receive_json())["result"]
assert backup["format"] == "nextfloor-backup"
assert backup["building"]["floors"][0]["name"] == "Backup floor"
# only imported packs go into the backup (the built-in ones come with the integration)
assert [p["id"] for p in backup["packs"]] == ["test.backup"]
# a broken pack is skipped on restore, a built-in one is left alone, the good one comes back
broken = json.loads(json.dumps(backup["packs"][0]))
broken["id"] = "test.broken"
broken["items"][0]["parts"] = []
backup["building"]["floors"][0]["name"] = "Restored floor"
restore = {"type": "nextfloor/backup/import", "building": backup["building"]}
builtin_copy = {**PAYLOAD, "id": "nextfloor.energie"}
await client.send_json_auto_id({**restore, "packs": [*backup["packs"], broken, builtin_copy]})
result = await client.receive_json()
assert result["success"], result
assert result["result"]["packs"] == 1
assert [s["id"] for s in result["result"]["skipped"]] == ["test.broken"]
assert result["result"]["building"]["floors"][0]["name"] == "Restored floor"
await client.send_json_auto_id({"type": "nextfloor/packs/list"})
listed = (await client.receive_json())["result"]["packs"]
assert [p["id"] for p in listed if not p.get("builtin")] == ["test.backup"]
# a broken building is refused before anything changes
await client.send_json_auto_id({"type": "nextfloor/backup/import", "building": {"version": 99}, "packs": []})
result = await client.receive_json()
assert not result["success"] and result["error"]["code"] == "invalid_format"
+97
View File
@@ -0,0 +1,97 @@
"""Locating a Bluetooth tag by room: the signal patterns, the smoothing and the plan's schema."""
from __future__ import annotations
import math
import pytest
import voluptuous as vol
from custom_components.nextfloor import ble
from custom_components.nextfloor.schema import BLE_TAG_SCHEMA, SETTINGS_SCHEMA
_BASE = {"wall_exterior": 0.24, "wall_interior": 0.12, "grid": 0.05}
def _prints() -> list[dict]:
return [
{"room": "kitchen", "rssi": {"a": -50.0, "b": -80.0, "c": -90.0}},
{"room": "kitchen", "rssi": {"a": -55.0, "b": -78.0, "c": -92.0}},
{"room": "bath", "rssi": {"a": -85.0, "b": -45.0, "c": -70.0}},
{"room": "hall", "rssi": {"a": -75.0, "b": -75.0, "c": -50.0}},
]
def test_distance_is_zero_for_the_same_pattern_and_missing_scanners_count_as_far() -> None:
assert ble.distance({"a": -60}, {"a": -60}) == 0
# one scanner hears the tag, the other not at all: its missing value is -100 dBm, differences are capped at 40
assert ble.distance({"a": -60, "b": -50}, {"a": -60}) == pytest.approx(math.sqrt(40**2 / 2))
assert ble.distance({}, {}) == math.inf
def test_the_nearest_room_wins_and_a_room_may_have_several_spots() -> None:
room, dist, margin = ble.locate(_prints(), {"a": -53.0, "b": -79.0, "c": -91.0})
assert room == "kitchen" and dist < 5 and margin > 20
assert ble.locate(_prints(), {"a": -84.0, "b": -47.0, "c": -71.0})[0] == "bath"
assert ble.locate(_prints(), {"a": -76.0, "b": -74.0, "c": -52.0})[0] == "hall"
def test_nothing_heard_or_nothing_close_gives_no_room() -> None:
assert ble.locate(_prints(), {})[0] is None
assert ble.locate([], {"a": -60})[0] is None
# a pattern far from every fingerprint is "unknown", not the least bad room
assert ble.locate(_prints(), {"a": -30.0, "b": -30.0, "c": -30.0})[0] is None
def test_median_reading_drops_a_scanner_that_missed_most_samples() -> None:
samples = [{"a": -60, "b": -70}, {"a": -64, "b": -72}, {"a": -62}, {"a": -61}]
out = ble.median_reading(samples)
assert out == {"a": -61.5}
assert ble.median_reading([]) == {}
def test_smoother_switches_only_after_three_readings_in_a_row() -> None:
s = ble.Smoother()
assert s.update("kitchen") is None
assert s.update("kitchen") is None
assert s.update("kitchen") == "kitchen"
# one stray reading does not move it, and neither do two different ones
assert s.update("bath") == "kitchen"
assert s.update("hall") == "kitchen"
assert s.update("bath") == "kitchen"
assert s.update("bath") == "kitchen"
assert s.update("bath") == "bath"
def test_smooth_reading_keeps_the_last_five() -> None:
history: list[dict[str, float]] = []
for value in (-90, -50, -52, -51, -53, -50):
out = ble.smooth_reading(history, {"a": value})
assert len(history) == 5 and out == {"a": -51.0}
def test_tag_schema_needs_an_address_or_a_tracker() -> None:
tag = BLE_TAG_SCHEMA({"id": "t1", "name": "Keys", "address": "aa:bb:cc:dd:ee:ff"})
assert tag["address"] == "AA:BB:CC:DD:EE:FF" and tag["prints"] == [] and tag["entity"] is None
assert BLE_TAG_SCHEMA({"id": "t2", "name": "Phone", "entity": "device_tracker.my_phone"})["address"] is None
with pytest.raises(vol.Invalid):
BLE_TAG_SCHEMA({"id": "t3", "name": "Nothing"})
with pytest.raises(vol.Invalid):
BLE_TAG_SCHEMA({"id": "t4", "name": "Bad", "address": "not-a-mac"})
with pytest.raises(vol.Invalid):
BLE_TAG_SCHEMA({"id": "t5", "name": "Bad", "entity": "light.kitchen"})
def test_prints_and_settings_validate() -> None:
tag = {
"id": "t1",
"name": "Keys",
"address": "AA:BB:CC:DD:EE:FF",
"prints": [{"room": "kitchen", "rssi": {"s1": -60.5}}],
}
settings = SETTINGS_SCHEMA({**_BASE, "ble": {"tags": [tag]}})
assert settings["ble"]["tags"][0]["prints"][0]["rssi"] == {"s1": -60.5}
with pytest.raises(vol.Invalid):
BLE_TAG_SCHEMA({**tag, "prints": [{"room": "kitchen", "rssi": {"s1": 10}}]})
with pytest.raises(vol.Invalid):
SETTINGS_SCHEMA({**_BASE, "ble": {"tags": [tag] * 11}})
+62
View File
@@ -0,0 +1,62 @@
"""The card bundle is kept in the dashboard resources (#252)."""
from __future__ import annotations
from types import SimpleNamespace
from typing import Any
from custom_components.nextfloor.card_resource import async_ensure_card_resource, async_remove_card_resource
class FakeResources:
"""The parts of Lovelace's ResourceStorageCollection we use."""
def __init__(self, items: list[dict[str, Any]]) -> None:
self.items = items
async def async_get_info(self) -> dict[str, int]:
return {"resources": len(self.items)}
def async_items(self) -> list[dict[str, Any]]:
return self.items
async def async_create_item(self, data: dict[str, Any]) -> dict[str, Any]:
item = {"id": f"r{len(self.items)}", "type": data["res_type"], "url": data["url"]}
self.items.append(item)
return item
async def async_update_item(self, item_id: str, updates: dict[str, Any]) -> dict[str, Any]:
item = next(i for i in self.items if i["id"] == item_id)
item.update({"type": updates["res_type"], "url": updates["url"]})
return item
async def async_delete_item(self, item_id: str) -> None:
self.items = [i for i in self.items if i["id"] != item_id]
URL = "/nextfloor_static/nextfloor.js?v=1.12.4-abc"
async def test_added_updated_and_removed() -> None:
"""Added once, older copies point to the current bundle, other resources stay, removal takes only ours."""
other = {"id": "x", "type": "module", "url": "/hacsfiles/button-card/button-card.js"}
res = FakeResources([dict(other)])
hass = SimpleNamespace(data={"lovelace": SimpleNamespace(resources=res)})
await async_ensure_card_resource(hass, URL)
assert [i["url"] for i in res.items] == [other["url"], URL]
# an update and an old hand-installed copy: both lead to the current bundle, nothing is added twice
res.items[1]["url"] = "/nextfloor_static/nextfloor.js?v=1.12.3-old"
res.items.append({"id": "old", "type": "module", "url": "/local/nextfloor.js"})
await async_ensure_card_resource(hass, URL)
assert [i["url"] for i in res.items] == [other["url"], URL, URL]
await async_remove_card_resource(hass)
assert res.items == [other]
async def test_yaml_mode_and_old_layout() -> None:
"""YAML resources are left alone; the dict layout before HA 2025.2 works too."""
yaml = SimpleNamespace(loaded=True, async_items=lambda: [])
await async_ensure_card_resource(SimpleNamespace(data={"lovelace": SimpleNamespace(resources=yaml)}), URL)
res = FakeResources([])
await async_ensure_card_resource(SimpleNamespace(data={"lovelace": {"resources": res}}), URL)
assert [i["url"] for i in res.items] == [URL]
+453
View File
@@ -0,0 +1,453 @@
"""Setup, websocket and removal tests."""
from __future__ import annotations
import copy
from homeassistant import config_entries
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.setup import async_setup_component
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.nextfloor.const import DOMAIN, STORAGE_KEY_BUILDING, STORAGE_KEY_HISTORY, STORAGE_KEY_IMAGES
BUILDING = {
"version": 1,
"settings": {"wall_exterior": 0.24, "wall_interior": 0.12, "grid": 0.05},
"floors": [
{
"id": "f1",
"name": "Ground floor",
"elevation": 0,
"height": 2.5,
"cut_height": 1.15,
"rooms": [
{
"id": "r1",
"name": "Living",
"area_id": None,
"points": [[0, 0], [4, 0], [4, 3], [0, 3]],
"floor_material": "wood",
}
],
"openings": [],
"furniture": [],
"placements": [],
"background": {"image_id": "img1", "x": 0, "z": 0, "width": 10, "opacity": 0.5},
}
],
}
IMAGE = "data:image/png;base64,iVBORw0KGgo="
async def _setup(hass: HomeAssistant) -> MockConfigEntry:
await async_setup_component(hass, "http", {})
entry = MockConfigEntry(domain=DOMAIN, data={})
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
return entry
async def test_config_flow_creates_single_entry(hass: HomeAssistant) -> None:
result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": config_entries.SOURCE_USER})
assert result["type"] is FlowResultType.FORM
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
await hass.async_block_till_done()
again = await hass.config_entries.flow.async_init(DOMAIN, context={"source": config_entries.SOURCE_USER})
assert again["type"] is FlowResultType.ABORT
async def test_save_and_get_building(hass: HomeAssistant, hass_ws_client) -> None:
await _setup(hass)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "nextfloor/building/subscribe"})
sub = await client.receive_json()
assert sub["success"]
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": BUILDING})
event = await client.receive_json()
result = await client.receive_json()
if "event" in result:
event, result = result, event
assert result["success"]
assert result["result"]["revision"] == 1
assert event["event"] == {"revision": 1}
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = await client.receive_json()
assert got["result"]["revision"] == 1
assert got["result"]["building"]["floors"][0]["rooms"][0]["name"] == "Living"
assert got["result"]["version"]
async def test_opening_fields_get_defaults(hass: HomeAssistant, hass_ws_client) -> None:
await _setup(hass)
client = await hass_ws_client(hass)
building = copy.deepcopy(BUILDING)
opening = {
"id": "o1",
"room_id": "r1",
"edge": 0,
"offset": 2,
"width": 1.2,
"type": "window",
"sill": 0.9,
"height": 1.3,
}
building["floors"][0]["openings"] = [
opening,
{**opening, "id": "o2", "hinge": "right", "cover": "cover.x", "contact": "none"},
]
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": building})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = (await client.receive_json())["result"]["building"]["floors"][0]["openings"]
assert got[0] == {
**opening,
"hinge": "left",
"leaves": 1,
"swing": "in",
"cover": None,
"contact": None,
"contact2": None,
"tilt": None,
"sensor": None,
"sensor2": None,
"tilt2": None,
"style": None,
"sidelight_hinge": False,
"sidelight_width": None,
"sidelight_width2": None,
"position": None,
"position_inverted": False,
"tilt_angle": None,
"tilt_max": None,
"tilt_offset": None,
"tilt_invert": False,
"shut": False,
"open_angle": None,
"wall": None,
"mark": None,
"confirm": False,
"panes": None,
"front": None,
}
assert got[1]["hinge"] == "right" and got[1]["cover"] == "cover.x" and got[1]["contact"] == "none"
double = {**opening, "id": "o3", "sill": 0, "leaves": 2, "contact2": "binary_sensor.b"}
building["floors"][0]["openings"] = [double, {**opening, "id": "o4", "type": "door", "swing": "out"}]
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": building})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = (await client.receive_json())["result"]["building"]["floors"][0]["openings"]
assert got[0]["leaves"] == 2 and got[0]["contact2"] == "binary_sensor.b"
assert got[1]["swing"] == "out"
# an opening in a free wall keeps the wall's id
building["floors"][0]["walls"] = [{"id": "fw1", "a": [1, 0], "b": [1, 2]}]
building["floors"][0]["openings"] = [{**opening, "id": "o5", "type": "door", "wall": "fw1", "offset": 1}]
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": building})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = (await client.receive_json())["result"]["building"]["floors"][0]["openings"]
assert got[0]["wall"] == "fw1"
building["floors"][0]["openings"] = [{**opening, "leaves": 3}]
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": building})
assert not (await client.receive_json())["success"]
async def test_furniture_links_default_to_automatic(hass: HomeAssistant, hass_ws_client) -> None:
await _setup(hass)
client = await hass_ws_client(hass)
building = copy.deepcopy(BUILDING)
item = {
"id": "m1",
"type": "tv_board",
"x": 1,
"z": 1,
"rotation": 0,
"w": 1.8,
"d": 0.4,
"h": 0.5,
"variant": None,
}
building["floors"][0]["furniture"] = [item, {**item, "id": "m2", "entity": "media_player.tv", "power": "none"}]
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": building})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = (await client.receive_json())["result"]["building"]["floors"][0]["furniture"]
assert (got[0]["entity"], got[0]["power"]) == (None, None)
assert (got[1]["entity"], got[1]["power"]) == ("media_player.tv", "none")
async def test_screen_pictures_keep_their_images(hass: HomeAssistant, hass_ws_client) -> None:
"""Images used by screen picture rules are not dropped as unused when the building is saved."""
await _setup(hass)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "nextfloor/image/set", "image_id": "pic1", "data": IMAGE})
assert (await client.receive_json())["success"]
building = copy.deepcopy(BUILDING)
item = {
"id": "m1",
"type": "tv_wall",
"x": 1,
"z": 1,
"rotation": 0,
"w": 1.4,
"d": 0.1,
"h": 0.8,
"variant": None,
"pictures": [
{"entity": "binary_sensor.cat", "state": "on", "image": "pic1"},
{"entity": "sun.sun", "state": "*", "image": "https://x/y.png"},
],
}
building["floors"][0]["furniture"] = [item]
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": building})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/image/get", "image_id": "pic1"})
assert (await client.receive_json())["result"]["data"] == IMAGE
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = (await client.receive_json())["result"]["building"]["floors"][0]["furniture"][0]
assert [r["image"] for r in got["pictures"]] == ["pic1", "https://x/y.png"]
async def test_placement_mount_defaults_to_none(hass: HomeAssistant, hass_ws_client) -> None:
await _setup(hass)
client = await hass_ws_client(hass)
building = copy.deepcopy(BUILDING)
building["floors"][0]["placements"] = [
{"entity_id": "light.a", "x": 1, "z": 1, "y": None},
{"entity_id": "light.b", "x": 2, "z": 1, "y": None, "mount": "floor"},
]
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": building})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = (await client.receive_json())["result"]["building"]["floors"][0]["placements"]
assert [p["mount"] for p in got] == [None, "floor"]
async def test_energy_and_presence_get_defaults(hass: HomeAssistant, hass_ws_client) -> None:
await _setup(hass)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": BUILDING})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = (await client.receive_json())["result"]["building"]
assert got["energy"]["meter"] is None and got["energy"]["grid_invert"] is False
assert got["presence"] == []
building = copy.deepcopy(BUILDING)
building["energy"] = {"meter": {"floor_id": "f1", "x": 1, "z": 2}, "grid": "sensor.grid"}
building["presence"] = [{"person": "person.mia", "sensor": "sensor.mia_area"}]
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": building})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = (await client.receive_json())["result"]["building"]
assert got["energy"]["meter"] == {"floor_id": "f1", "x": 1, "z": 2}
assert got["energy"]["grid"] == "sensor.grid" and got["energy"]["solar"] is None
assert got["presence"] == [{"person": "person.mia", "sensor": "sensor.mia_area"}]
async def test_unknown_fields_from_newer_frontends_are_kept(hass: HomeAssistant, hass_ws_client) -> None:
await _setup(hass)
client = await hass_ws_client(hass)
building = copy.deepcopy(BUILDING)
building["future_setting"] = {"a": 1}
building["floors"][0]["rooms"][0]["ceiling_color"] = "#ffffff"
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": building})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = (await client.receive_json())["result"]["building"]
assert got["future_setting"] == {"a": 1}
assert got["floors"][0]["rooms"][0]["ceiling_color"] == "#ffffff"
async def test_restore_points(hass: HomeAssistant, hass_ws_client, hass_storage) -> None:
await _setup(hass)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": BUILDING})
assert (await client.receive_json())["success"]
# an empty building is no restore point
await client.send_json_auto_id({"type": "nextfloor/history/list"})
assert (await client.receive_json())["result"]["snapshots"] == []
changed = copy.deepcopy(BUILDING)
changed["floors"][0]["rooms"][0]["name"] = "Changed"
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": changed})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/history/list"})
snapshots = (await client.receive_json())["result"]["snapshots"]
assert len(snapshots) == 1 and snapshots[0]["rooms"] == 1
await client.send_json_auto_id({"type": "nextfloor/history/restore", "snapshot_id": snapshots[0]["id"]})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = (await client.receive_json())["result"]["building"]
assert got["floors"][0]["rooms"][0]["name"] == "Living"
# the state before restoring is a restore point as well
await client.send_json_auto_id({"type": "nextfloor/history/list"})
assert len((await client.receive_json())["result"]["snapshots"]) == 2
await hass.async_block_till_done()
assert STORAGE_KEY_HISTORY in hass_storage
async def test_named_versions_stay_and_can_be_fetched_and_removed(hass: HomeAssistant, hass_ws_client) -> None:
await _setup(hass)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": BUILDING})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/history/snapshot", "name": " Before the renovation "})
version = (await client.receive_json())["result"]["id"]
# many unnamed points later the named one is still there
for _ in range(25):
await client.send_json_auto_id({"type": "nextfloor/history/snapshot"})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/history/list"})
snapshots = (await client.receive_json())["result"]["snapshots"]
assert [s["name"] for s in snapshots if s.get("name")] == ["Before the renovation"]
assert len([s for s in snapshots if not s.get("name")]) == 20
await client.send_json_auto_id({"type": "nextfloor/history/get", "snapshot_id": version})
got = (await client.receive_json())["result"]["building"]
assert got["floors"][0]["rooms"][0]["name"] == "Living"
await client.send_json_auto_id({"type": "nextfloor/history/delete", "snapshot_id": version})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/history/get", "snapshot_id": version})
assert (await client.receive_json())["error"]["code"] == "not_found"
async def test_outdoor_roof_and_north_get_defaults(hass: HomeAssistant, hass_ws_client) -> None:
await _setup(hass)
client = await hass_ws_client(hass)
building = copy.deepcopy(BUILDING)
building["floors"][0]["outdoor"] = [{"id": "o1", "type": "lawn", "points": [[0, 0], [1, 0], [1, 1]]}]
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": building})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/building/get"})
got = (await client.receive_json())["result"]["building"]
assert got["settings"]["north"] == 0
assert got["settings"]["roof"] == {
"type": "none",
"pitch": 35,
"overhang": 0.4,
"ridge": None,
"sections": [],
"solar": [],
"strings": [],
"windows": [],
"chimneys": [],
}
assert got["floors"][0]["outdoor"][0]["type"] == "lawn"
assert got["floors"][0]["outdoor"][0]["slope"] == 0
assert got["floors"][0]["outdoor"][0]["slope_dir"] == "x"
assert got["floors"][0]["outdoor"][0]["cut"] is False
assert got["floors"][0]["ha_floor"] is None
assert got["floors"][0]["rooms"][0]["panel"] == []
# a height offset or slope set back to 0 arrives as None from the editor and still saves (#242)
cleared = copy.deepcopy(building)
cleared["floors"][0]["outdoor"][0].update({"type": "pergola", "offset": None, "slope": None})
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": cleared})
assert (await client.receive_json())["success"]
bad = copy.deepcopy(building)
bad["floors"][0]["outdoor"][0]["type"] = "volcano"
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": bad})
assert not (await client.receive_json())["success"]
async def test_invalid_building_is_rejected(hass: HomeAssistant, hass_ws_client) -> None:
await _setup(hass)
client = await hass_ws_client(hass)
bad = copy.deepcopy(BUILDING)
bad["floors"][0]["rooms"][0]["points"] = [[0, 0], [1, 1]]
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": bad})
result = await client.receive_json()
assert not result["success"]
assert result["error"]["code"] == "invalid_format"
async def test_changes_require_admin(hass: HomeAssistant, hass_ws_client, hass_read_only_access_token) -> None:
await _setup(hass)
client = await hass_ws_client(hass, hass_read_only_access_token)
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": BUILDING})
result = await client.receive_json()
assert not result["success"]
assert result["error"]["code"] == "unauthorized"
await client.send_json_auto_id({"type": "nextfloor/image/set", "image_id": "img1", "data": IMAGE})
result = await client.receive_json()
assert result["error"]["code"] == "unauthorized"
# reading is allowed
await client.send_json_auto_id({"type": "nextfloor/building/get"})
result = await client.receive_json()
assert result["success"]
async def test_images(hass: HomeAssistant, hass_ws_client) -> None:
await _setup(hass)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "nextfloor/image/set", "image_id": "img1", "data": IMAGE})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/image/get", "image_id": "img1"})
assert (await client.receive_json())["result"]["data"] == IMAGE
await client.send_json_auto_id({"type": "nextfloor/image/set", "image_id": "img2", "data": "not an image"})
assert not (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/image/delete", "image_id": "img1"})
assert (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/image/get", "image_id": "img1"})
assert (await client.receive_json())["error"]["code"] == "not_found"
async def test_unused_images_are_dropped_on_load(hass: HomeAssistant, hass_storage) -> None:
hass_storage[STORAGE_KEY_BUILDING] = {
"version": 1,
"key": STORAGE_KEY_BUILDING,
"data": {"revision": 3, "building": BUILDING},
}
hass_storage[STORAGE_KEY_IMAGES] = {
"version": 1,
"key": STORAGE_KEY_IMAGES,
"data": {"images": {"img1": IMAGE, "old": IMAGE}},
}
await _setup(hass)
data = hass.data[DOMAIN]
assert data.revision == 3
assert data.get_image("img1") == IMAGE
assert data.get_image("old") is None
async def test_remove_entry_keeps_the_stores(hass: HomeAssistant, hass_ws_client, hass_storage) -> None:
"""Removing the integration must never delete the plan (re-adding it finds everything again)."""
entry = await _setup(hass)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "nextfloor/building/save", "building": BUILDING})
await client.receive_json()
await client.send_json_auto_id({"type": "nextfloor/image/set", "image_id": "img1", "data": IMAGE})
await client.receive_json()
await hass.async_block_till_done()
assert STORAGE_KEY_BUILDING in hass_storage
assert STORAGE_KEY_IMAGES in hass_storage
assert await hass.config_entries.async_remove(entry.entry_id)
await hass.async_block_till_done()
assert STORAGE_KEY_BUILDING in hass_storage
assert STORAGE_KEY_IMAGES in hass_storage
assert DOMAIN not in hass.data
async def test_panel_and_card_are_registered_and_removed(hass: HomeAssistant, mock_frontend) -> None:
entry = await _setup(hass)
mock_frontend["register"].assert_awaited_once()
assert mock_frontend["register"].await_args.kwargs["frontend_url_path"] == "nextfloor"
url = mock_frontend["add_js"].call_args.args[1]
assert url.startswith("/nextfloor_static/nextfloor.js?v=")
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
mock_frontend["remove_panel"].assert_called_once_with(hass, "nextfloor")
mock_frontend["remove_js"].assert_called_once_with(hass, url)
+109
View File
@@ -0,0 +1,109 @@
"""Standalone validation checks, without importing the Home Assistant integration."""
import importlib.util
import json
from pathlib import Path
import pytest
import voluptuous as vol
spec = importlib.util.spec_from_file_location(
"nextfloor_schema", Path(__file__).parents[1] / "custom_components/nextfloor/schema.py"
)
schema = importlib.util.module_from_spec(spec)
spec.loader.exec_module(schema)
@pytest.mark.parametrize(
"validator,base",
[
(schema.PLACEMENT_SCHEMA, {"entity_id": "light.demo", "x": 1, "z": 1, "y": None}),
(
schema.FURNITURE_SCHEMA,
{
"id": "demo",
"type": "lamp_floor",
"x": 1,
"z": 1,
"rotation": 0,
"w": 0.3,
"d": 0.3,
"h": 1.5,
"variant": None,
},
),
],
)
@pytest.mark.parametrize(
"name,accepted",
[
("", False),
("💡", True),
("💡" * 128, True),
("💡" * 255, True),
("💡" * 256, False),
("a" * 127 + "💡" * 128, True),
("a" * 128 + "💡" * 128, False),
(" e\u0301" + "💡" * 251 + " ", True),
(" e\u0301" + "💡" * 252 + " ", False),
],
ids=[
"empty",
"one",
"128-supplementary",
"255-supplementary",
"256-supplementary",
"255-mixed",
"256-mixed",
"255-unmodified",
"256-unmodified",
],
)
def test_effect_names_use_unicode_code_points(validator, base, name, accepted):
payload = json.loads(json.dumps({**base, "effect_animations": {name: "future"}}))
if accepted:
assert validator(payload)["effect_animations"] == {name: "future"}
else:
with pytest.raises(vol.Invalid):
validator(payload)
PLACEMENT = {"entity_id": "light.demo", "x": 1, "z": 1, "y": None}
FURNITURE = {
"id": "demo",
"type": "lamp_floor",
"x": 1,
"z": 1,
"rotation": 0,
"w": 0.3,
"d": 0.3,
"h": 1.5,
"variant": None,
}
@pytest.mark.parametrize("validator,base", [(schema.PLACEMENT_SCHEMA, PLACEMENT), (schema.FURNITURE_SCHEMA, FURNITURE)])
def test_effect_configuration_rejects_invalid_shapes(validator, base):
for invalid in [[], "rainbow", {"Demo": 42}, {"": "rainbow"}, {"x" * 256: "rainbow"}]:
with pytest.raises(vol.Invalid):
validator({**base, "effect_animations": invalid})
with pytest.raises(vol.Invalid):
validator({**base, "animations_enabled": "yes"})
@pytest.mark.parametrize("validator,base", [(schema.PLACEMENT_SCHEMA, PLACEMENT), (schema.FURNITURE_SCHEMA, FURNITURE)])
def test_effect_configuration_round_trips_exact_names_and_future_identifiers(validator, base):
mapping = {"Regenbogen": "rainbow", "Kerzenlicht": "flicker", "Weiß": "none", " White ": "future"}
result = validator(json.loads(json.dumps({**base, "effect_animations": mapping, "animations_enabled": False})))
assert result["effect_animations"] == mapping
assert result["animations_enabled"] is False
assert "effect_animations" not in validator(base)
@pytest.mark.parametrize("validator,base", [(schema.PLACEMENT_SCHEMA, PLACEMENT), (schema.FURNITURE_SCHEMA, FURNITURE)])
def test_effect_configuration_accepts_limits_and_explicit_prototype_names(validator, base):
mapping = {str(i): "future" for i in range(96)}
mapping.update({"x" * 255: "pulse", "__proto__": "rainbow", "constructor": "pulse", "toString": "flicker"})
assert validator({**base, "effect_animations": mapping})["effect_animations"] == mapping
with pytest.raises(vol.Invalid):
validator({**base, "effect_animations": {**mapping, "entry-101": "none"}})
+250
View File
@@ -0,0 +1,250 @@
"""Furniture packs: content check, the built-in packs, and import through the websocket."""
from __future__ import annotations
import copy
import json
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
import pytest
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.nextfloor import packs
from custom_components.nextfloor.const import DOMAIN
PAYLOAD = {
"format": "nfpack",
"version": 1,
"id": "test.starter",
"name": "Starter",
"publisher": "Test",
"items": [
{
"id": "cube_chair",
"name": {"de": "Würfelsessel", "en": "Cube chair"},
"size": [0.8, 0.8, 0.75],
"parts": [
{"shape": "box", "x": 0, "z": 0, "w": 1, "d": 1, "y": 0, "h": 0.55, "color": "fabric"},
{"shape": "box", "x": 0, "z": -0.4, "w": 1, "d": 0.2, "y": 0.55, "h": 0.45, "color": "#223355"},
],
}
],
}
def test_a_plain_pack_is_accepted() -> None:
clean = packs.parse_pack(json.dumps(PAYLOAD))
assert clean["items"][0]["parts"][0]["edges"] is False
with pytest.raises(packs.PackError) as err:
packs.parse_pack("{}")
assert err.value.code == "not_a_pack"
with pytest.raises(packs.PackError) as err:
packs.parse_pack("no json")
assert err.value.code == "not_a_pack"
def test_a_climate_pack_item_is_accepted() -> None:
payload = copy.deepcopy(PAYLOAD)
payload["items"][0]["climate"] = True
clean = packs.validate_payload(payload)
assert clean["items"][0]["climate"] is True
def test_a_studio_recipe_is_kept_and_checked() -> None:
payload = copy.deepcopy(PAYLOAD)
recipe = {
"kind": "cabinet",
"name": "Sideboard",
"w": 160,
"d": 45,
"h": 80,
"doors": 2,
"drawers": 1,
"base": "plinth",
"handle": "bar",
"body": "white",
"front": "#8a6a4a",
}
payload["items"][0]["recipe"] = recipe
clean = packs.validate_payload(payload)
assert clean["items"][0]["recipe"]["doors"] == 2
assert clean["items"][0]["recipe"]["shelves"] == 0
payload["items"][0]["recipe"] = {**recipe, "kind": "sofa"}
with pytest.raises(packs.PackError):
packs.validate_payload(payload)
def test_a_pack_needs_items() -> None:
with pytest.raises(packs.PackError):
packs.validate_payload({**PAYLOAD, "items": []})
def test_sloped_and_lying_parts_are_accepted() -> None:
shaped = copy.deepcopy(PAYLOAD)
box = {"x": 0, "z": 0.2, "w": 1, "d": 0.6, "y": 0, "h": 0.5, "color": "body"}
shaped["items"][0]["parts"] = [
{"shape": "loft", **box, "tx": 0, "tz": 0.1, "tw": 0.9, "td": 0.2, "edges": "glow"},
{"shape": "cyl", "axis": "x", **box, "edges": "faint"},
]
clean = packs.validate_payload(shaped)
assert clean["items"][0]["parts"][0]["edges"] == "glow"
assert clean["items"][0]["parts"][1]["axis"] == "x"
shaped["items"][0]["parts"][1]["axis"] = "w"
with pytest.raises(packs.PackError):
packs.validate_payload(shaped)
def test_pack_content_is_checked() -> None:
heavy = copy.deepcopy(PAYLOAD)
heavy["items"][0]["parts"] *= 31 # more than 60 parts
with pytest.raises(packs.PackError) as err:
packs.validate_payload(heavy)
assert err.value.code == "invalid_content"
twice = copy.deepcopy(PAYLOAD)
twice["items"].append(copy.deepcopy(twice["items"][0]))
with pytest.raises(packs.PackError):
packs.validate_payload(twice)
def test_turned_parts_and_stairs_holes_are_accepted() -> None:
"""A part may turn around its centre (rot) and a stairs item may cut the floor above (hole)."""
item = copy.deepcopy(PAYLOAD["items"][0])
item["hole"] = True
item["parts"][0]["rot"] = 27.5
clean = packs.validate_payload({**PAYLOAD, "items": [item]})
assert clean["items"][0]["hole"] is True
assert clean["items"][0]["parts"][0]["rot"] == 27.5
with pytest.raises(packs.PackError):
item["parts"][0]["rot"] = 400
packs.validate_payload({**PAYLOAD, "items": [item]})
def test_builtin_packs_are_valid() -> None:
"""The packs that come with NextFloor all pass the content check, with unique pack ids."""
builtin = packs.load_builtin_packs()
assert len(builtin) >= 10
assert len({p["id"] for p in builtin}) == len(builtin)
assert all(p["builtin"] and p["id"].startswith("nextfloor.") for p in builtin)
assert sum(len(p["items"]) for p in builtin) >= 90
async def test_import_list_and_remove(hass: HomeAssistant, hass_ws_client) -> None:
await async_setup_component(hass, "http", {})
entry = MockConfigEntry(domain=DOMAIN, data={})
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "nextfloor/packs/list"})
builtin = [p["id"] for p in (await client.receive_json())["result"]["packs"]]
assert "nextfloor.energie" in builtin
await client.send_json_auto_id({"type": "nextfloor/packs/import", "pack": json.dumps(PAYLOAD)})
result = await client.receive_json()
assert result["success"]
assert result["result"] == {"id": "test.starter", "name": "Starter", "publisher": "Test", "items": 1}
await client.send_json_auto_id({"type": "nextfloor/packs/import", "pack": "{}"})
result = await client.receive_json()
assert not result["success"] and result["error"]["code"] == "not_a_pack"
# a pack may not take the id of a built-in one
await client.send_json_auto_id(
{"type": "nextfloor/packs/import", "pack": json.dumps({**PAYLOAD, "id": "nextfloor.energie"})}
)
result = await client.receive_json()
assert not result["success"] and result["error"]["code"] == "builtin"
await client.send_json_auto_id({"type": "nextfloor/packs/list"})
listed = (await client.receive_json())["result"]["packs"]
assert [p["id"] for p in listed] == [*builtin, "test.starter"]
assert listed[-1]["items"][0]["name"]["de"] == "Würfelsessel"
await client.send_json_auto_id({"type": "nextfloor/packs/remove", "pack_id": "test.starter"})
assert (await client.receive_json())["success"]
# built-in packs cannot be removed
await client.send_json_auto_id({"type": "nextfloor/packs/remove", "pack_id": "nextfloor.energie"})
assert not (await client.receive_json())["success"]
await client.send_json_auto_id({"type": "nextfloor/packs/list"})
assert [p["id"] for p in (await client.receive_json())["result"]["packs"]] == builtin
def _sweep_pack(stations):
item = {
"id": "boat",
"name": {"de": "Boot", "en": "Boat"},
"size": [2, 6, 1.5],
"parts": [
{
"shape": "sweep",
"x": 0,
"z": 0,
"w": 1,
"d": 1,
"y": 0,
"h": 1,
"color": "body",
"stations": stations,
"exp": 3,
"n": 12,
}
],
}
return {**PAYLOAD, "items": [item]}
def test_a_swept_body_needs_valid_stations() -> None:
ok = packs.validate_payload(_sweep_pack([[-0.5, 0, 0.3, 0.2], [0, 0, 0.6, 1], [0.5, 0.1, 0.3, 0.1]]))
assert ok["items"][0]["parts"][0]["stations"][1] == [0.0, 0.0, 0.6, 1.0]
for bad in ([[-0.5, 0, 0.3, 0.2]], [[-0.5, 0, 0.3, 0.2], [0.9, 0, 0.3, 0.2]], [[-0.5, 0, 0.3], [0, 0, 0.3, 0.2]]):
with pytest.raises(packs.PackError):
packs.validate_payload(_sweep_pack(bad))
# without stations it is no body at all
broken = _sweep_pack([[-0.5, 0, 0.3, 0.2], [0.5, 0, 0.3, 0.2]])
del broken["items"][0]["parts"][0]["stations"]
with pytest.raises(packs.PackError):
packs.validate_payload(broken)
def test_colours_of_an_item_are_checked() -> None:
def pack(colors):
item = {
"id": "car",
"name": {"en": "Car"},
"size": [2, 4, 1.5],
"colors": colors,
"parts": [{"shape": "box", "x": 0, "z": 0, "w": 1, "d": 1, "y": 0, "h": 1, "color": "body", "paint": True}],
}
return {**PAYLOAD, "items": [item]}
white = {"id": "white", "name": {"en": "White"}, "hex": "#ffffff"}
red = {"id": "red", "name": {"en": "Red", "de": "Rot"}, "hex": "#c01020"}
assert packs.validate_payload(pack([white, red]))["items"][0]["colors"][1]["id"] == "red"
for bad in ([white], [white, white], [white, {**red, "hex": "red"}], [white, {**red, "id": "Rot Rot"}]):
with pytest.raises(packs.PackError):
packs.validate_payload(pack(bad))
def test_mesh_id_of_an_item_is_checked() -> None:
def pack(mesh):
item = {
"id": "car",
"name": {"en": "Car"},
"size": [2, 4, 1.5],
"mesh": mesh,
"parts": [{"shape": "box", "x": 0, "z": 0, "w": 1, "d": 1, "y": 0, "h": 1, "color": "body"}],
}
return {**PAYLOAD, "items": [item]}
assert packs.validate_payload(pack("tesla_model_y"))["items"][0]["mesh"] == "tesla_model_y"
for bad in ("../etc/passwd", "Model Y", ""):
with pytest.raises(packs.PackError):
packs.validate_payload(pack(bad))
def test_builtin_thermostats_link_to_climate_entities() -> None:
"""The wall thermostat has a display, but it must still ask for a climate entity, not a TV."""
items = {i["id"]: i for p in packs.load_builtin_packs() for i in p["items"]}
assert items["thermostat_wall"]["climate"] is True
+254
View File
@@ -0,0 +1,254 @@
"""Schema details: start views of the house, a floor and a room (#206, #282), the map, sub-meters, plugins."""
import pytest
import voluptuous as vol
from custom_components.nextfloor.schema import (
ENERGY_SCHEMA,
FURNITURE_SCHEMA,
MAP_SCHEMA,
OPENING_SCHEMA,
PLACEMENT_SCHEMA,
PLUGIN_SCHEMA,
ROOM_SCHEMA,
SETTINGS_SCHEMA,
START_VIEW_SCHEMA,
image_ids,
)
ROOM = {"id": "r1", "name": "Bad", "area_id": None, "points": [[0, 0], [2, 0], [2, 2]], "floor_material": "tiles"}
def test_start_view_keeps_its_target() -> None:
view = START_VIEW_SCHEMA({"theta": 1, "phi": 0.8, "radius": 9, "target": {"x": 1, "y": 0.5, "z": -2}})
assert view["target"] == {"x": 1.0, "y": 0.5, "z": -2.0}
def test_start_view_without_target() -> None:
assert "target" not in START_VIEW_SCHEMA({"theta": 1, "phi": 0.8, "radius": 9})
def test_room_start_view() -> None:
assert ROOM_SCHEMA(ROOM)["start_view"] is None
view = {"theta": 0.5, "phi": 0.9, "radius": 4, "target": {"x": 1, "y": 0.3, "z": 1}}
room = ROOM_SCHEMA({**ROOM, "start_view": view})
assert room["start_view"]["radius"] == 4.0
def test_map_defaults_and_limits() -> None:
result = MAP_SCHEMA({"on": True, "lat": 50.1, "lon": 8.6})
assert (result["zoom"], result["opacity"], result["url"]) == (18, 0.5, None)
for bad in ({"lat": 99}, {"zoom": 25}, {"url": "http://tiles.example/{z}/{x}/{y}.png"}):
with pytest.raises(vol.Invalid):
MAP_SCHEMA({"on": True, "lat": 50.1, "lon": 8.6, **bad})
def test_sub_meter_fields_are_optional() -> None:
meter = {"id": "m2", "type": "meter", "x": 1, "z": 1, "rotation": 0, "w": 0.5, "d": 0.2, "h": 0.8, "variant": None}
plain = FURNITURE_SCHEMA(meter)
assert not {"parent_meter", "meter_invert", "meter_floors"} & plain.keys()
sub = FURNITURE_SCHEMA({**meter, "parent_meter": "m1", "meter_invert": True, "meter_floors": ["og", "dg"]})
assert (sub["parent_meter"], sub["meter_invert"], sub["meter_floors"]) == ("m1", True, ["og", "dg"])
with pytest.raises(vol.Invalid):
FURNITURE_SCHEMA({**meter, "meter_floors": "og"})
def test_advanced_energy_mode_is_optional() -> None:
assert "advanced" not in ENERGY_SCHEMA({})
assert ENERGY_SCHEMA({"advanced": True})["advanced"] is True
assert "show_unmetered" not in ENERGY_SCHEMA({"advanced": True})
assert ENERGY_SCHEMA({"show_unmetered": True})["show_unmetered"] is True
with pytest.raises(vol.Invalid):
ENERGY_SCHEMA({"advanced": "yes"})
def test_energy_routes() -> None:
assert "routes" not in ENERGY_SCHEMA({})
route = {"key": "solar:f1", "points": [{"floor_id": "eg", "x": 1, "z": 2}, {"floor_id": "kg", "x": 1, "z": 2}]}
result = ENERGY_SCHEMA({"routes": [route, {**route, "key": "grid", "cable": True}]})
assert result["routes"][0]["points"][1] == {"floor_id": "kg", "x": 1.0, "z": 2.0}
assert result["routes"][1]["cable"] is True
for bad in ({**route, "points": [{"floor_id": "eg", "x": 1}]}, {**route, "points": [route["points"][0]] * 31}):
with pytest.raises(vol.Invalid):
ENERGY_SCHEMA({"routes": [bad]})
SETTINGS = {"wall_exterior": 0.3, "wall_interior": 0.1, "grid": 0.1, "roof": {}}
def test_plugin_urls() -> None:
for url in ("/local/nf/glow.js", "/hacsfiles/nf-post/post.mjs", "https://example.org/p.js?v=2"):
assert PLUGIN_SCHEMA({"url": url, "enabled": True})["url"] == url
for url in ("http://example.org/p.js", "/config/secrets.js", "javascript:alert(1)", "/local/readme.txt"):
with pytest.raises(vol.Invalid):
PLUGIN_SCHEMA({"url": url, "enabled": True})
with pytest.raises(vol.Invalid):
PLUGIN_SCHEMA({"url": "/local/a.js", "enabled": True, "code": "alert(1)"})
def test_plugins_are_optional_and_limited() -> None:
assert "plugins" not in SETTINGS_SCHEMA(SETTINGS)
many = [{"url": f"/local/p{i}.js", "enabled": True} for i in range(21)]
with pytest.raises(vol.Invalid):
SETTINGS_SCHEMA({**SETTINGS, "plugins": many})
assert len(SETTINGS_SCHEMA({**SETTINGS, "plugins": many[:20]})["plugins"]) == 20
def test_furniture_tap_action() -> None:
item = {"id": "f1", "type": "table", "x": 1, "z": 1, "rotation": 0, "w": 0.5, "d": 0.5, "h": 0.8, "variant": None}
assert FURNITURE_SCHEMA(item)["tap"] is None
tap = FURNITURE_SCHEMA({**item, "tap": {"action": "more_info", "target": "sensor.pills"}})["tap"]
assert tap == {"action": "more_info", "target": "sensor.pills", "data": None}
popup = {"action": "fire_dom_event", "data": {"browser_mod": {"service": "browser_mod.popup"}}}
assert FURNITURE_SCHEMA({**item, "tap": popup})["tap"]["data"] == popup["data"]
with pytest.raises(vol.Invalid):
FURNITURE_SCHEMA({**item, "tap": {"action": "toggle"}})
def test_placement_plugin_settings() -> None:
placed = {"entity_id": "camera.hall", "x": 1, "z": 2, "y": None}
assert PLACEMENT_SCHEMA(placed)["plugin"] is None
data = {"cameras": {"fov": 90, "dome": False, "detect": "person"}}
assert PLACEMENT_SCHEMA({**placed, "plugin": data})["plugin"] == data
with pytest.raises(vol.Invalid):
PLACEMENT_SCHEMA({**placed, "plugin": {"cameras": {"bad key": 1}}})
with pytest.raises(vol.Invalid):
PLACEMENT_SCHEMA({**placed, "plugin": {"cameras": {"nested": {"a": 1}}}})
STAIRS = {"id": "s1", "type": "stairs", "x": 1, "z": 2, "rotation": 0, "w": 2.2, "d": 2.8, "h": 2.8, "variant": None}
def test_shaped_stair_round_trips() -> None:
stair = {
"shape": "l",
"turn": "left",
"build": "mono",
"risers": False,
"steps": 15,
"run_width": 1.0,
"down": False,
"rail": "both",
}
assert FURNITURE_SCHEMA({**STAIRS, "stair": stair})["stair"] == stair
assert "stair" not in FURNITURE_SCHEMA(STAIRS)
def test_shaped_stair_rejects_unknown_shapes() -> None:
for bad in ({"shape": "zigzag"}, {"steps": 99}, {"rail": "middle"}, {"build": "rope"}, {"opening": "wide"}):
with pytest.raises(vol.Invalid):
FURNITURE_SCHEMA({**STAIRS, "stair": bad})
FURN = {"id": "f1", "type": "plant", "x": 0, "z": 0, "rotation": 0, "w": 1, "d": 1, "h": 1, "variant": None}
def test_furniture_show_when() -> None:
assert "show_when" not in FURNITURE_SCHEMA(FURN)
cond = {"entity": "input_boolean.xmas", "state": "on, home", "invert": True}
assert FURNITURE_SCHEMA({**FURN, "show_when": cond})["show_when"] == cond
assert FURNITURE_SCHEMA({**FURN, "show_when": None})["show_when"] is None
with pytest.raises(vol.Invalid):
FURNITURE_SCHEMA({**FURN, "show_when": {"state": "on"}})
def test_picture_frames() -> None:
frame = FURNITURE_SCHEMA({**FURN, "picture": "image:img_7", "picture_border": 12, "picture_fit": "contain"})
assert frame["picture_border"] == 12.0
with pytest.raises(vol.Invalid):
FURNITURE_SCHEMA({**FURN, "picture_fit": "stretch"})
floors = [{"background": None, "furniture": [frame, {**FURN, "id": "f2", "picture": "/local/a.jpg"}]}]
assert image_ids({"floors": floors}) == {"img_7"}
def test_opening_blinds() -> None:
base = {
"id": "o1",
"room_id": "r1",
"edge": 0,
"offset": 1,
"width": 1.2,
"type": "window",
"sill": 0.9,
"height": 1.3,
}
base.update(
{"hinge": "left", "leaves": 1, "swing": "in", "contact2": None, "cover": None, "contact": None, "tilt": None}
)
o = OPENING_SCHEMA({**base, "cover2": "cover.right", "blind": "venetian", "my_position": 40})
assert (o["cover2"], o["blind"], o["my_position"]) == ("cover.right", "venetian", 40)
with pytest.raises(vol.Invalid):
OPENING_SCHEMA({**base, "blind": "curtain"})
def test_a_glass_pane_over_several_edges_and_its_pane_count() -> None:
"""A glass wall can say how many panes it has, and a pane over several edges names its pieces."""
base = {
"id": "o1",
"room_id": "r1",
"edge": 0,
"offset": 0.5,
"width": 1.0,
"type": "window",
"sill": 0,
"height": 2.4,
}
plain = OPENING_SCHEMA(base)
assert plain["panes"] is None and plain["front"] is None
one = OPENING_SCHEMA({**base, "panes": 0})
assert one["panes"] == 0
front = OPENING_SCHEMA({**base, "panes": 0, "front": "front_ab"})
assert front["front"] == "front_ab"
for bad in ({"panes": 41}, {"panes": -1}, {"front": "x" * 65}):
with pytest.raises(vol.Invalid):
OPENING_SCHEMA({**base, **bad})
def test_pin_offsets() -> None:
placed = PLACEMENT_SCHEMA({"entity_id": "light.a", "x": 1, "z": 1, "y": None, "pin_offset": {"x": 0.4, "y": -0.2}})
assert placed["pin_offset"] == {"x": 0.4, "y": -0.2}
assert FURNITURE_SCHEMA({**FURN, "pin_offset": {"z": 1}})["pin_offset"] == {"z": 1.0}
with pytest.raises(vol.Invalid):
PLACEMENT_SCHEMA({"entity_id": "light.a", "x": 1, "z": 1, "y": None, "pin_offset": {"x": 9}})
def test_card_templates_accept_names_and_limit_them() -> None:
settings = {
"wall_exterior": 0.24,
"wall_interior": 0.12,
"grid": 0.05,
"north": 0,
"roof": {"type": "none", "pitch": 35, "overhang": 0.4},
}
ok = SETTINGS_SCHEMA({**settings, "card_templates": {"kitchen_tablet": {"height": 520, "readable": True}}})
assert ok["card_templates"] == {"kitchen_tablet": {"height": 520, "readable": True}}
assert SETTINGS_SCHEMA(settings)["card_templates"] is None
with pytest.raises(vol.Invalid):
SETTINGS_SCHEMA({**settings, "card_templates": {"Küche Tablet!": {}}})
with pytest.raises(vol.Invalid):
SETTINGS_SCHEMA({**settings, "card_templates": {f"t{i}": {} for i in range(21)}})
def test_fence_gates_and_sloping_walls_and_roof_overhang_per_side() -> None:
from custom_components.nextfloor.schema import FENCE_GATE_SCHEMA, FREE_WALL_SCHEMA
gate = FENCE_GATE_SCHEMA(
{"id": "g", "edge": 1, "offset": 2.5, "width": 1.2, "kind": "sliding", "entity": "cover.tor"}
)
assert gate["contact"] is None and gate["kind"] == "sliding"
with pytest.raises(vol.Invalid):
FENCE_GATE_SCHEMA({"id": "g", "edge": 1, "offset": 2.5, "width": 1.2, "kind": "teleport"})
wall = FREE_WALL_SCHEMA({"id": "w", "a": [0, 0], "b": [2, 0], "height": 2.4, "height_end": 1.0})
assert wall["height_end"] == 1.0
assert FREE_WALL_SCHEMA({"id": "w", "a": [0, 0], "b": [2, 0]})["height_end"] is None
def test_outdoor_area_opacity() -> None:
from custom_components.nextfloor.schema import OUTDOOR_SCHEMA
base = {"id": "a", "type": "driveway", "points": [[0, 0], [4, 0], [4, 3]]}
assert OUTDOOR_SCHEMA(base)["opacity"] is None
assert OUTDOOR_SCHEMA({**base, "opacity": 0.4})["opacity"] == 0.4
for bad in (0, 0.05, 1.5):
with pytest.raises(vol.Invalid):
OUTDOOR_SCHEMA({**base, "opacity": bad})
+96
View File
@@ -0,0 +1,96 @@
"""Sensors from the plan: open windows and doors, lights on, per floor and for the house."""
from __future__ import annotations
import copy
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.nextfloor.const import DOMAIN
from custom_components.nextfloor.sensor import floor_lights, floor_openings
FLOOR = {
"id": "eg",
"name": "Erdgeschoss",
"elevation": 0,
"height": 2.5,
"cut_height": 1.15,
"rooms": [
{
"id": "r1",
"name": "Wohnen",
"area_id": None,
"points": [[0, 0], [4, 0], [4, 3], [0, 3]],
"floor_material": "wood",
}
],
"openings": [
{
"id": "w1",
"type": "window",
"room_id": "r1",
"edge": 0,
"offset": 1,
"width": 1,
"contact": "binary_sensor.window",
"tilt": None,
},
{"id": "g1", "type": "garage", "room_id": "r1", "edge": 1, "offset": 1, "width": 2.5, "cover": "cover.garage"},
],
"furniture": [
{"id": "l1", "type": "lamp_floor", "x": 1, "z": 1, "entity": "light.lamp", "extra_lights": ["light.ring"]}
],
"placements": [{"entity_id": "light.ceiling", "x": 2, "z": 2}, {"entity_id": "sensor.temp", "x": 1, "z": 2}],
"background": None,
}
def test_what_a_floor_counts() -> None:
assert floor_lights(FLOOR) == {"light.lamp", "light.ring", "light.ceiling"}
assert floor_openings(FLOOR) == [
{"sensors": ["binary_sensor.window"], "cover": None},
{"sensors": [], "cover": "cover.garage"},
]
async def test_sensors_follow_states_and_the_plan(hass: HomeAssistant) -> None:
await async_setup_component(hass, "http", {})
entry = MockConfigEntry(domain=DOMAIN, data={})
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
hass.states.async_set("light.lamp", "on")
hass.states.async_set("light.ring", "off")
hass.states.async_set("light.ceiling", "on")
hass.states.async_set("binary_sensor.window", "off")
hass.states.async_set("cover.garage", "open")
building = {"version": 1, "settings": {}, "floors": [copy.deepcopy(FLOOR)]}
await hass.data[DOMAIN].async_save_building(building)
await hass.async_block_till_done()
def value(kind: str, scope: str) -> str:
states = [s for s in hass.states.async_all("sensor") if s.entity_id.startswith("sensor.nextfloor")]
match = [
s
for s in states
if s.attributes.get("icon") == ("mdi:window-open-variant" if kind == "open" else "mdi:lightbulb-group")
]
match = [s for s in match if ("erdgeschoss" in s.entity_id) == (scope == "eg")]
assert len(match) == 1, [s.entity_id for s in states]
return match[0].state
assert value("lights_on", "eg") == "2"
assert value("open", "eg") == "1"
assert value("open", "house") == "1"
hass.states.async_set("binary_sensor.window", "on")
hass.states.async_set("light.ceiling", "off")
await hass.async_block_till_done()
assert value("open", "eg") == "2"
assert value("lights_on", "house") == "1"
# a floor that is gone leaves its sensors unavailable
await hass.data[DOMAIN].async_save_building({"version": 1, "settings": {}, "floors": []})
await hass.async_block_till_done()
assert value("open", "eg") == "unavailable"
assert value("open", "house") == "0"
+46
View File
@@ -0,0 +1,46 @@
"""The one-time note about the official HACS store."""
from __future__ import annotations
from datetime import UTC, datetime
from homeassistant.core import HomeAssistant
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.nextfloor.const import DOMAIN
from custom_components.nextfloor.store_notice import MESSAGE, NOTICE_ID, TITLE, async_notify_official_store
def _entry(created: datetime) -> MockConfigEntry:
entry = MockConfigEntry(domain=DOMAIN)
# created_at is no constructor argument; an old install is one whose entry was made earlier
object.__setattr__(entry, "created_at", created)
return entry
async def test_old_install_gets_the_note_once(hass: HomeAssistant, hass_storage) -> None:
entry = _entry(datetime(2026, 10, 1, tzinfo=UTC))
entry.add_to_hass(hass)
assert await async_notify_official_store(hass, entry) is True
note = hass.data["persistent_notification"][NOTICE_ID]
assert "HACS" in note["title"] and "NextFloor" in note["message"]
assert await async_notify_official_store(hass, entry) is False # not again, even after a restart
async def test_new_install_gets_nothing(hass: HomeAssistant, hass_storage) -> None:
entry = _entry(datetime(2026, 11, 5, tzinfo=UTC))
entry.add_to_hass(hass)
assert await async_notify_official_store(hass, entry) is False
assert NOTICE_ID not in hass.data.get("persistent_notification", {})
async def test_language_follows_home_assistant(hass: HomeAssistant, hass_storage) -> None:
hass.config.language = "de"
entry = _entry(datetime(2026, 10, 1, tzinfo=UTC))
entry.add_to_hass(hass)
await async_notify_official_store(hass, entry)
assert hass.data["persistent_notification"][NOTICE_ID]["title"] == TITLE["de"]
def test_every_language_has_title_and_message() -> None:
assert set(TITLE) == set(MESSAGE) == {"en", "de", "fr", "es", "it", "nl", "pl", "pt", "sv", "zh"}