feat: update-Entitaet fuer die Firmware und das Testgeruest
Aufgebaut wie ha-ninlight: die Abbilder liegen unter ninstrip_firmware im Konfigurationsverzeichnis, Home Assistant liefert sie selbst unter einer einmaligen Adresse aus, und zwar genau die Bytes, die vorher geprueft wurden. Dazu firmware.py (Anhaenger, Versionsreihenfolge, WLAN-Pruefung, Katalog), http.py, urls.py und shared.py. Drei Unterschiede zu ninlight, alle aus der Firmware heraus: * Verglichen wird device_type - die Platine -, nicht product. Letzteres ist bei allen Platinen 'ninstrip'; die Abbilder unterscheiden sich aber hart, die K1Y invertiert das Datensignal und die KL-RGBC3 nicht. Firmware ohne dieses Feld bekommt gar kein Angebot. * Die WLAN-Pruefung sucht die SSID unverpackt: ein ESP32-Abbild ist nicht gzip-verpackt wie das des W600. An einem mit sdkconfig.local gebauten Abbild gegengeprueft - die SSID steht genau einmal NUL-gerahmt drin. * Der Fehlerschluessel heisst device_url_too_long statt lamp_url_too_long. Dazu das Testgeruest, das es hier bisher gar nicht gab: 204 Tests in tests_unit/ (ohne HA-Instanz) und tests/ (mit), Abdeckung 97 %, dazu scripts/check.sh als Ersatz fuer die fehlende CI. Die Nutzdaten in tests_unit/samples.py sind an der Stehlampe abgefragt. Beim Gegenpruefen per Mutation fiel auf, dass die Platinenpruefung unmittelbar vor dem Senden ungeprueft war - der Test dazu ist jetzt da und faellt, wenn man die Pruefung entfernt.
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
"""Fixtures fuer die Tests, die gegen eine Home-Assistant-Instanz laufen."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Generator
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from homeassistant.const import CONF_HOST, CONF_TOKEN
|
||||
from homeassistant.core import HomeAssistant
|
||||
import pytest
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.ninstrip.api import NinstripClient
|
||||
from custom_components.ninstrip.const import DOMAIN
|
||||
from tests_unit.samples import (
|
||||
HOST_K1Y,
|
||||
INFO_K1Y,
|
||||
MAC_K1Y,
|
||||
PRESETS_K1Y,
|
||||
SETTINGS_COMPILED,
|
||||
STATE_K1Y,
|
||||
TOKEN,
|
||||
)
|
||||
|
||||
CLIENT_PATCH_TARGETS = [
|
||||
"custom_components.ninstrip.NinstripClient",
|
||||
"custom_components.ninstrip.config_flow.NinstripClient",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def auto_enable_custom_integrations(enable_custom_integrations: None) -> Generator[None]:
|
||||
"""custom_components/ in jedem Home-Assistant-Test laden."""
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def strip_state() -> dict[str, Any]:
|
||||
return deepcopy(STATE_K1Y)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def strip_info() -> dict[str, Any]:
|
||||
return deepcopy(INFO_K1Y)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def strip_settings() -> dict[str, Any]:
|
||||
return deepcopy(SETTINGS_COMPILED)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def strip_presets() -> dict[str, Any]:
|
||||
return deepcopy(PRESETS_K1Y)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_client(
|
||||
strip_state: dict[str, Any],
|
||||
strip_info: dict[str, Any],
|
||||
strip_settings: dict[str, Any],
|
||||
strip_presets: dict[str, Any],
|
||||
) -> Generator[MagicMock]:
|
||||
"""Ein Geraet, dessen Antworten den veraenderbaren strip_*-Fixtures folgen."""
|
||||
client = MagicMock(spec=NinstripClient)
|
||||
client.host = HOST_K1Y
|
||||
client.get_state = AsyncMock(side_effect=lambda: deepcopy(strip_state))
|
||||
client.get_info = AsyncMock(side_effect=lambda: deepcopy(strip_info))
|
||||
client.get_settings = AsyncMock(side_effect=lambda: deepcopy(strip_settings))
|
||||
client.get_presets = AsyncMock(side_effect=lambda: deepcopy(strip_presets))
|
||||
|
||||
async def set_state(**fields: Any) -> dict[str, Any]:
|
||||
strip_state.update(fields)
|
||||
return deepcopy(strip_state)
|
||||
|
||||
client.set_state = AsyncMock(side_effect=set_state)
|
||||
|
||||
async def set_sacn(**fields: Any) -> None:
|
||||
# Wie das Geraet: es merkt sich, was es annimmt, und der Aufrufer
|
||||
# liest den Block danach zurueck.
|
||||
strip_settings.setdefault("sacn", {}).update(fields)
|
||||
|
||||
client.set_sacn = AsyncMock(side_effect=set_sacn)
|
||||
client.apply_preset = AsyncMock(return_value=None)
|
||||
client.save_preset = AsyncMock(return_value=None)
|
||||
client.reboot = AsyncMock(return_value=None)
|
||||
client.fw_update = AsyncMock(return_value=None)
|
||||
patches = [patch(target, return_value=client) for target in CLIENT_PATCH_TARGETS]
|
||||
for p in patches:
|
||||
p.start()
|
||||
yield client
|
||||
for p in patches:
|
||||
p.stop()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config_entry() -> MockConfigEntry:
|
||||
return MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title="ninstrip ad4c",
|
||||
unique_id=MAC_K1Y,
|
||||
data={CONF_HOST: HOST_K1Y, CONF_TOKEN: TOKEN},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def init_integration(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_client: MagicMock
|
||||
) -> MockConfigEntry:
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
return mock_config_entry
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_setup_entry() -> Generator[AsyncMock]:
|
||||
"""Tests des Einrichtungsablaufs duerfen den Eintrag nicht wirklich aufsetzen."""
|
||||
with patch("custom_components.ninstrip.async_setup_entry", return_value=True) as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def firmware_dir(tmp_path: Path) -> Generator[Path]:
|
||||
"""Jeder Test bekommt seinen eigenen, anfangs leeren Firmware-Ordner."""
|
||||
verzeichnis = tmp_path / "ninstrip_firmware"
|
||||
with patch("custom_components.ninstrip.shared.firmware_directory", return_value=verzeichnis):
|
||||
yield verzeichnis
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Helfer fuer die Home-Assistant-Tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from custom_components.ninstrip.const import DOMAIN
|
||||
from tests_unit.samples import MAC_K1Y
|
||||
|
||||
|
||||
def entity_id_for(hass: HomeAssistant, platform: str, key: str, mac: str = MAC_K1Y) -> str:
|
||||
"""Entitaeten ueber ihre unique_id suchen, statt Namen zu raten."""
|
||||
entity_id = er.async_get(hass).async_get_entity_id(platform, DOMAIN, f"{mac}_{key}")
|
||||
assert entity_id is not None, f"keine {platform}-Entitaet mit dem Schluessel {key}"
|
||||
return entity_id
|
||||
|
||||
|
||||
async def abfragen(hass: HomeAssistant, freezer) -> None:
|
||||
"""Einen Abfragezyklus vorspulen (Vorgabe: 30 s)."""
|
||||
from datetime import timedelta
|
||||
|
||||
from pytest_homeassistant_custom_component.common import async_fire_time_changed
|
||||
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Neustart-Knopf."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from homeassistant.const import ATTR_ENTITY_ID
|
||||
from homeassistant.core import HomeAssistant
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from tests.helpers import entity_id_for
|
||||
|
||||
|
||||
async def test_knopf_startet_das_geraet_neu(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
await hass.services.async_call(
|
||||
"button",
|
||||
"press",
|
||||
{ATTR_ENTITY_ID: entity_id_for(hass, "button", "restart")},
|
||||
blocking=True,
|
||||
)
|
||||
mock_client.reboot.assert_awaited_once()
|
||||
@@ -0,0 +1,269 @@
|
||||
"""Einrichtungsablauf: von Hand, ueber mDNS, erneute Anmeldung und Einstellungen."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from ipaddress import ip_address
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF
|
||||
from homeassistant.const import CONF_HOST, CONF_TOKEN
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
|
||||
import pytest
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.ninstrip.api import (
|
||||
NinstripAuthError,
|
||||
NinstripConnectionError,
|
||||
NinstripResponseError,
|
||||
)
|
||||
from custom_components.ninstrip.const import (
|
||||
CONF_DEVICE_BASE_URL,
|
||||
CONF_SCAN_INTERVAL,
|
||||
DEFAULT_TOKEN,
|
||||
DOMAIN,
|
||||
)
|
||||
from tests_unit.samples import HOST_K1Y, MAC_K1Y, TOKEN
|
||||
|
||||
pytestmark = pytest.mark.usefixtures("mock_setup_entry")
|
||||
|
||||
NEUES_TOKEN = "b71e0c9d44a2f6e3"
|
||||
|
||||
|
||||
def zeroconf_info(ip: str = HOST_K1Y, **properties: Any) -> ZeroconfServiceInfo:
|
||||
props = {"mac": MAC_K1Y, "name": "Stehlampe"} | properties
|
||||
return ZeroconfServiceInfo(
|
||||
ip_address=ip_address(ip),
|
||||
ip_addresses=[ip_address(ip)],
|
||||
port=3333,
|
||||
hostname="ninstrip-ad4c.local.",
|
||||
type="_ninstrip._tcp.local.",
|
||||
name="ninstrip-ad4c._ninstrip._tcp.local.",
|
||||
properties={k: v for k, v in props.items() if v is not None},
|
||||
)
|
||||
|
||||
|
||||
def bestehender_eintrag(hass: HomeAssistant, host: str = HOST_K1Y) -> MockConfigEntry:
|
||||
eintrag = MockConfigEntry(
|
||||
domain=DOMAIN, title="Strip", unique_id=MAC_K1Y, data={CONF_HOST: host, CONF_TOKEN: TOKEN}
|
||||
)
|
||||
eintrag.add_to_hass(hass)
|
||||
return eintrag
|
||||
|
||||
|
||||
async def test_eintrag_von_hand(hass: HomeAssistant, mock_client: MagicMock) -> None:
|
||||
ergebnis = await hass.config_entries.flow.async_init(DOMAIN, context={"source": SOURCE_USER})
|
||||
assert ergebnis["type"] is FlowResultType.FORM
|
||||
assert ergebnis["step_id"] == "user"
|
||||
ergebnis = await hass.config_entries.flow.async_configure(
|
||||
ergebnis["flow_id"], {CONF_HOST: HOST_K1Y, CONF_TOKEN: TOKEN}
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert ergebnis["data"] == {CONF_HOST: HOST_K1Y, CONF_TOKEN: TOKEN}
|
||||
assert ergebnis["result"].unique_id == MAC_K1Y
|
||||
# system/info antwortet auch ohne Token - geprueft wird an system/settings.
|
||||
mock_client.get_settings.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_das_werks_token_ist_vorbelegt(hass: HomeAssistant, mock_client: MagicMock) -> None:
|
||||
ergebnis = await hass.config_entries.flow.async_init(DOMAIN, context={"source": SOURCE_USER})
|
||||
schluessel = next(k for k in ergebnis["data_schema"].schema if k == CONF_TOKEN)
|
||||
assert schluessel.default() == DEFAULT_TOKEN
|
||||
|
||||
|
||||
async def test_der_titel_kommt_vom_geraetenamen(
|
||||
hass: HomeAssistant, mock_client: MagicMock, strip_info: dict[str, Any]
|
||||
) -> None:
|
||||
strip_info["name"] = "Stehlampe"
|
||||
ergebnis = await hass.config_entries.flow.async_init(DOMAIN, context={"source": SOURCE_USER})
|
||||
ergebnis = await hass.config_entries.flow.async_configure(
|
||||
ergebnis["flow_id"], {CONF_HOST: HOST_K1Y, CONF_TOKEN: TOKEN}
|
||||
)
|
||||
assert ergebnis["title"] == "Stehlampe"
|
||||
|
||||
|
||||
async def test_ohne_namen_zaehlen_produkt_und_mac(
|
||||
hass: HomeAssistant, mock_client: MagicMock
|
||||
) -> None:
|
||||
ergebnis = await hass.config_entries.flow.async_init(DOMAIN, context={"source": SOURCE_USER})
|
||||
ergebnis = await hass.config_entries.flow.async_configure(
|
||||
ergebnis["flow_id"], {CONF_HOST: HOST_K1Y, CONF_TOKEN: TOKEN}
|
||||
)
|
||||
assert ergebnis["title"] == "ninstrip ad4c"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("methode", "fehler", "erwartet"),
|
||||
[
|
||||
("get_settings", NinstripAuthError("401"), "invalid_auth"),
|
||||
("get_settings", NinstripConnectionError("weg"), "cannot_connect"),
|
||||
("get_info", NinstripResponseError("kein JSON"), "not_ninstrip"),
|
||||
("get_settings", RuntimeError("peng"), "unknown"),
|
||||
],
|
||||
)
|
||||
async def test_fehler_und_zweiter_versuch(
|
||||
hass: HomeAssistant,
|
||||
mock_client: MagicMock,
|
||||
methode: str,
|
||||
fehler: Exception,
|
||||
erwartet: str,
|
||||
) -> None:
|
||||
mock = getattr(mock_client, methode)
|
||||
urspruenglich = mock.side_effect
|
||||
mock.side_effect = fehler
|
||||
ergebnis = await hass.config_entries.flow.async_init(DOMAIN, context={"source": SOURCE_USER})
|
||||
ergebnis = await hass.config_entries.flow.async_configure(
|
||||
ergebnis["flow_id"], {CONF_HOST: HOST_K1Y, CONF_TOKEN: TOKEN}
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.FORM
|
||||
assert ergebnis["errors"] == {"base": erwartet}
|
||||
mock.side_effect = urspruenglich
|
||||
ergebnis = await hass.config_entries.flow.async_configure(
|
||||
ergebnis["flow_id"], {CONF_HOST: HOST_K1Y, CONF_TOKEN: TOKEN}
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.CREATE_ENTRY
|
||||
|
||||
|
||||
async def test_dasselbe_geraet_unter_neuer_adresse_schreibt_den_host_um(
|
||||
hass: HomeAssistant, mock_client: MagicMock
|
||||
) -> None:
|
||||
eintrag = bestehender_eintrag(hass)
|
||||
ergebnis = await hass.config_entries.flow.async_init(DOMAIN, context={"source": SOURCE_USER})
|
||||
ergebnis = await hass.config_entries.flow.async_configure(
|
||||
ergebnis["flow_id"], {CONF_HOST: "192.168.2.99", CONF_TOKEN: TOKEN}
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.ABORT
|
||||
assert ergebnis["reason"] == "already_configured"
|
||||
assert eintrag.data[CONF_HOST] == "192.168.2.99"
|
||||
|
||||
|
||||
async def test_mdns_fragt_nur_nach_dem_token(hass: HomeAssistant, mock_client: MagicMock) -> None:
|
||||
ergebnis = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=zeroconf_info()
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.FORM
|
||||
assert ergebnis["step_id"] == "discovery_confirm"
|
||||
assert ergebnis["description_placeholders"] == {"name": "Stehlampe", "host": HOST_K1Y}
|
||||
assert set(ergebnis["data_schema"].schema) == {CONF_TOKEN}
|
||||
ergebnis = await hass.config_entries.flow.async_configure(
|
||||
ergebnis["flow_id"], {CONF_TOKEN: TOKEN}
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert ergebnis["data"] == {CONF_HOST: HOST_K1Y, CONF_TOKEN: TOKEN}
|
||||
|
||||
|
||||
async def test_mdns_ohne_namen_nimmt_den_dienstnamen(
|
||||
hass: HomeAssistant, mock_client: MagicMock
|
||||
) -> None:
|
||||
ergebnis = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=zeroconf_info(name=None)
|
||||
)
|
||||
assert ergebnis["description_placeholders"]["name"] == "ninstrip-ad4c"
|
||||
|
||||
|
||||
async def test_mdns_eines_bekannten_geraets_schreibt_den_host_um(
|
||||
hass: HomeAssistant, mock_client: MagicMock
|
||||
) -> None:
|
||||
eintrag = bestehender_eintrag(hass, "192.168.2.5")
|
||||
ergebnis = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=zeroconf_info()
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.ABORT
|
||||
assert ergebnis["reason"] == "already_configured"
|
||||
assert eintrag.data[CONF_HOST] == HOST_K1Y
|
||||
|
||||
|
||||
async def test_mdns_ohne_mac_faellt_auf_die_kennung_aus_info_zurueck(
|
||||
hass: HomeAssistant, mock_client: MagicMock
|
||||
) -> None:
|
||||
"""Ohne MAC in den mDNS-Eigenschaften entscheidet erst system/info."""
|
||||
ergebnis = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=zeroconf_info(mac=None)
|
||||
)
|
||||
ergebnis = await hass.config_entries.flow.async_configure(
|
||||
ergebnis["flow_id"], {CONF_TOKEN: TOKEN}
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert ergebnis["result"].unique_id == MAC_K1Y
|
||||
|
||||
|
||||
async def test_erneute_anmeldung_ersetzt_das_token(
|
||||
hass: HomeAssistant, mock_client: MagicMock
|
||||
) -> None:
|
||||
eintrag = bestehender_eintrag(hass)
|
||||
ergebnis = await eintrag.start_reauth_flow(hass)
|
||||
assert ergebnis["step_id"] == "reauth_confirm"
|
||||
# HA legt den Eintragstitel als "name" dazu.
|
||||
assert ergebnis["description_placeholders"]["host"] == HOST_K1Y
|
||||
ergebnis = await hass.config_entries.flow.async_configure(
|
||||
ergebnis["flow_id"], {CONF_TOKEN: NEUES_TOKEN}
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.ABORT
|
||||
assert ergebnis["reason"] == "reauth_successful"
|
||||
assert eintrag.data[CONF_TOKEN] == NEUES_TOKEN
|
||||
|
||||
|
||||
async def test_erneute_anmeldung_mit_falschem_token_bleibt_im_formular(
|
||||
hass: HomeAssistant, mock_client: MagicMock
|
||||
) -> None:
|
||||
eintrag = bestehender_eintrag(hass)
|
||||
mock_client.get_settings.side_effect = NinstripAuthError("401")
|
||||
ergebnis = await eintrag.start_reauth_flow(hass)
|
||||
ergebnis = await hass.config_entries.flow.async_configure(
|
||||
ergebnis["flow_id"], {CONF_TOKEN: "falsch"}
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.FORM
|
||||
assert ergebnis["errors"] == {"base": "invalid_auth"}
|
||||
assert eintrag.data[CONF_TOKEN] == TOKEN
|
||||
|
||||
|
||||
async def test_einstellungen_abfrageabstand_und_adresse(
|
||||
hass: HomeAssistant, mock_client: MagicMock
|
||||
) -> None:
|
||||
eintrag = bestehender_eintrag(hass)
|
||||
ergebnis = await hass.config_entries.options.async_init(eintrag.entry_id)
|
||||
ergebnis = await hass.config_entries.options.async_configure(
|
||||
ergebnis["flow_id"],
|
||||
{CONF_SCAN_INTERVAL: 45, CONF_DEVICE_BASE_URL: "http://192.168.1.50:8123/"},
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert eintrag.options == {
|
||||
CONF_SCAN_INTERVAL: 45,
|
||||
# Der abschliessende Schraegstrich faellt weg, sonst entstuende eine
|
||||
# Adresse mit zwei Schraegstrichen.
|
||||
CONF_DEVICE_BASE_URL: "http://192.168.1.50:8123",
|
||||
}
|
||||
|
||||
|
||||
async def test_einstellungen_ohne_adresse_lassen_sie_weg(
|
||||
hass: HomeAssistant, mock_client: MagicMock
|
||||
) -> None:
|
||||
eintrag = bestehender_eintrag(hass)
|
||||
ergebnis = await hass.config_entries.options.async_init(eintrag.entry_id)
|
||||
ergebnis = await hass.config_entries.options.async_configure(
|
||||
ergebnis["flow_id"], {CONF_SCAN_INTERVAL: 30}
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert CONF_DEVICE_BASE_URL not in eintrag.options
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("adresse", "fehler"),
|
||||
[
|
||||
("https://ha.local:8123", "invalid_base_url"),
|
||||
("http://ha.local:8123/pfad", "invalid_base_url"),
|
||||
("http://" + "a" * 183, "base_url_too_long"),
|
||||
],
|
||||
)
|
||||
async def test_einstellungen_weisen_unbrauchbare_adressen_ab(
|
||||
hass: HomeAssistant, mock_client: MagicMock, adresse: str, fehler: str
|
||||
) -> None:
|
||||
eintrag = bestehender_eintrag(hass)
|
||||
ergebnis = await hass.config_entries.options.async_init(eintrag.entry_id)
|
||||
ergebnis = await hass.config_entries.options.async_configure(
|
||||
ergebnis["flow_id"], {CONF_SCAN_INTERVAL: 30, CONF_DEVICE_BASE_URL: adresse}
|
||||
)
|
||||
assert ergebnis["type"] is FlowResultType.FORM
|
||||
assert ergebnis["errors"] == {CONF_DEVICE_BASE_URL: fehler}
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Verhalten des Koordinators, das an keiner einzelnen Plattform haengt."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import timedelta
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID,
|
||||
SERVICE_TURN_ON,
|
||||
STATE_ON,
|
||||
STATE_UNAVAILABLE,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
import pytest
|
||||
from pytest_homeassistant_custom_component.common import async_fire_time_changed
|
||||
|
||||
from custom_components.ninstrip.api import (
|
||||
NinstripBusyError,
|
||||
NinstripConnectionError,
|
||||
NinstripRequestError,
|
||||
)
|
||||
from tests.helpers import entity_id_for
|
||||
from tests_unit.samples import STATE_K1Y
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "key", "placeholders"),
|
||||
[
|
||||
(
|
||||
NinstripRequestError(400, "brightness"),
|
||||
"request_failed",
|
||||
{"message": "brightness"},
|
||||
),
|
||||
(NinstripBusyError(409, "Update laeuft schon"), "device_busy", None),
|
||||
(NinstripConnectionError("reset"), "cannot_connect", None),
|
||||
],
|
||||
)
|
||||
async def test_schreibfehler_werden_uebersetzt(
|
||||
hass: HomeAssistant, init_integration, mock_client: MagicMock, error, key, placeholders
|
||||
) -> None:
|
||||
mock_client.set_state.side_effect = error
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
await hass.services.async_call(
|
||||
LIGHT_DOMAIN,
|
||||
SERVICE_TURN_ON,
|
||||
{ATTR_ENTITY_ID: entity_id_for(hass, "light", "light")},
|
||||
blocking=True,
|
||||
)
|
||||
assert raised.value.translation_key == key
|
||||
assert raised.value.translation_placeholders == placeholders
|
||||
|
||||
|
||||
async def test_erste_zwei_fehlversuche_lassen_das_geraet_verfuegbar(
|
||||
hass: HomeAssistant, init_integration, mock_client: MagicMock, freezer: FrozenDateTimeFactory
|
||||
) -> None:
|
||||
entity_id = entity_id_for(hass, "light", "light")
|
||||
mock_client.get_state.side_effect = NinstripConnectionError("down")
|
||||
|
||||
reads = mock_client.get_state.await_count
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
assert mock_client.get_state.await_count == reads + 1
|
||||
assert hass.states.get(entity_id).state == STATE_ON
|
||||
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
assert mock_client.get_state.await_count == reads + 2
|
||||
assert hass.states.get(entity_id).state == STATE_ON
|
||||
|
||||
|
||||
async def test_dritter_fehlversuch_in_folge_macht_es_unverfuegbar(
|
||||
hass: HomeAssistant, init_integration, mock_client: MagicMock, freezer: FrozenDateTimeFactory
|
||||
) -> None:
|
||||
entity_id = entity_id_for(hass, "light", "light")
|
||||
mock_client.get_state.side_effect = NinstripConnectionError("down")
|
||||
|
||||
for _ in range(3):
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
|
||||
|
||||
|
||||
async def test_erfolgreiche_abfrage_setzt_den_zaehler_zurueck(
|
||||
hass: HomeAssistant, init_integration, mock_client: MagicMock, freezer: FrozenDateTimeFactory
|
||||
) -> None:
|
||||
entity_id = entity_id_for(hass, "light", "light")
|
||||
mock_client.get_state.side_effect = NinstripConnectionError("down")
|
||||
|
||||
# Zwei Fehlversuche werden geschluckt.
|
||||
for _ in range(2):
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
assert hass.states.get(entity_id).state == STATE_ON
|
||||
|
||||
# Ein erfolgreicher Durchlauf setzt den Zaehler zurueck.
|
||||
mock_client.get_state.side_effect = lambda: deepcopy(STATE_K1Y)
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
assert hass.states.get(entity_id).state == STATE_ON
|
||||
|
||||
# Zwei weitere Fehlversuche in Folge muessen wieder geschluckt werden.
|
||||
mock_client.get_state.side_effect = NinstripConnectionError("down")
|
||||
for _ in range(2):
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
assert hass.states.get(entity_id).state == STATE_ON
|
||||
|
||||
|
||||
async def test_einschalten_erreicht_das_geraet_trotz_geschluckter_fehlversuche(
|
||||
hass: HomeAssistant, init_integration, mock_client: MagicMock, freezer: FrozenDateTimeFactory
|
||||
) -> None:
|
||||
entity_id = entity_id_for(hass, "light", "light")
|
||||
mock_client.get_state.side_effect = NinstripConnectionError("down")
|
||||
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
assert hass.states.get(entity_id).state == STATE_ON
|
||||
|
||||
await hass.services.async_call(
|
||||
LIGHT_DOMAIN,
|
||||
SERVICE_TURN_ON,
|
||||
{ATTR_ENTITY_ID: entity_id},
|
||||
blocking=True,
|
||||
)
|
||||
mock_client.set_state.assert_awaited_with(on=True)
|
||||
|
||||
|
||||
async def test_erfolgreiches_schreiben_macht_es_wieder_verfuegbar(
|
||||
hass: HomeAssistant, init_integration, mock_client: MagicMock, freezer: FrozenDateTimeFactory
|
||||
) -> None:
|
||||
entity_id = entity_id_for(hass, "light", "light")
|
||||
mock_client.get_state.side_effect = NinstripConnectionError("down")
|
||||
|
||||
for _ in range(3):
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
|
||||
|
||||
await init_integration.runtime_data.async_set_state(on=True)
|
||||
await hass.async_block_till_done()
|
||||
assert hass.states.get(entity_id).state != STATE_UNAVAILABLE
|
||||
|
||||
# Das Schreiben hat den Zaehler zurueckgesetzt: ein Fehlversuch bleibt folgenlos.
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
assert hass.states.get(entity_id).state != STATE_UNAVAILABLE
|
||||
|
||||
|
||||
async def test_abfragen_pausiert_waehrend_einer_aktualisierung(
|
||||
hass: HomeAssistant, init_integration, mock_client: MagicMock, freezer: FrozenDateTimeFactory
|
||||
) -> None:
|
||||
init_integration.runtime_data.ota_in_progress = True
|
||||
mock_client.get_state.side_effect = NinstripConnectionError("rebooting")
|
||||
reads = mock_client.get_state.await_count
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
assert mock_client.get_state.await_count == reads
|
||||
assert hass.states.get(entity_id_for(hass, "light", "light")).state == STATE_ON
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Geraetename und Modellbeschreibung, auch wenn das Geraet wenig meldet."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from homeassistant.const import ATTR_ENTITY_ID, STATE_ON
|
||||
from homeassistant.core import HomeAssistant
|
||||
import pytest
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.ninstrip.entity import device_name, strip_model
|
||||
from tests.helpers import abfragen, entity_id_for
|
||||
|
||||
|
||||
def test_eigener_name_hat_vorrang() -> None:
|
||||
assert device_name({"name": " Stehlampe ", "mac": "b0:81:84:49:ad:4c"}) == "Stehlampe"
|
||||
|
||||
|
||||
def test_ohne_namen_zaehlen_produkt_und_die_letzten_vier_mac_stellen() -> None:
|
||||
assert device_name({"name": "", "mac": "b0:81:84:49:ad:4c"}) == "ninstrip ad4c"
|
||||
assert device_name({"mac": "b0:81:84:49:ad:4c", "product": "ninstrip"}) == "ninstrip ad4c"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("info", "erwartet"),
|
||||
[
|
||||
({"strip": {"chipset": "ws2805", "pixel_count": 40}}, "ws2805, 40 Pixel"),
|
||||
({"strip": {"chipset": "ws2805"}}, "ws2805"),
|
||||
({"strip": {}}, None),
|
||||
({}, None), # Geraet im Onboarding: noch kein strip-Block
|
||||
],
|
||||
)
|
||||
def test_modellbeschreibung(info: dict[str, Any], erwartet: str | None) -> None:
|
||||
assert strip_model(info) == erwartet
|
||||
|
||||
|
||||
async def test_sacn_schalter_laesst_sich_auch_einschalten(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_settings: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
strip_settings["sacn"]["enabled"] = False
|
||||
await abfragen(hass, freezer)
|
||||
entity_id = entity_id_for(hass, "switch", "sacn_enabled")
|
||||
await hass.services.async_call("switch", "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True)
|
||||
assert hass.states.get(entity_id).state == STATE_ON
|
||||
|
||||
|
||||
async def test_helligkeit_ohne_wert_bleibt_leer(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_state: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
strip_state["brightness"] = None
|
||||
await abfragen(hass, freezer)
|
||||
assert hass.states.get(entity_id_for(hass, "light", "light")).attributes["brightness"] is None
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Einmalige Firmware-Adressen und die Adresse, unter der Geraete HA erreichen."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.core_config import async_process_ha_core_config
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
import pytest
|
||||
from pytest_homeassistant_custom_component.typing import ClientSessionGenerator
|
||||
|
||||
from custom_components.ninstrip.const import CONF_DEVICE_BASE_URL
|
||||
from custom_components.ninstrip.http import OtaRegistry, device_base_url
|
||||
from custom_components.ninstrip.shared import DATA_SHARED
|
||||
from tests_unit.images import build_image
|
||||
|
||||
|
||||
def test_schluessel_sind_einmalig_und_43_zeichen_lang() -> None:
|
||||
registry = OtaRegistry()
|
||||
schluessel = {registry.create(b"nutzdaten") for _ in range(50)}
|
||||
assert len(schluessel) == 50
|
||||
assert all(len(k) == 43 for k in schluessel)
|
||||
assert len(registry) == 50
|
||||
|
||||
|
||||
async def test_die_ausgabe_liefert_nur_die_eigenen_bytes(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
init_integration,
|
||||
firmware_dir: Path,
|
||||
) -> None:
|
||||
registry = hass.data[DATA_SHARED].registry
|
||||
meins = build_image()
|
||||
anderes = build_image(version="0.1.1-rc1")
|
||||
schluessel = registry.create(meins)
|
||||
anderer = registry.create(anderes)
|
||||
client = await hass_client_no_auth()
|
||||
|
||||
antwort = await client.get(f"/api/ninstrip/firmware/{schluessel}")
|
||||
assert antwort.status == 200
|
||||
assert await antwort.read() == meins
|
||||
|
||||
andere_antwort = await client.get(f"/api/ninstrip/firmware/{anderer}")
|
||||
assert andere_antwort.status == 200
|
||||
assert await andere_antwort.read() == anderes
|
||||
|
||||
assert (await client.get("/api/ninstrip/firmware/" + "x" * 43)).status == 404
|
||||
registry.revoke(schluessel)
|
||||
assert (await client.get(f"/api/ninstrip/firmware/{schluessel}")).status == 404
|
||||
# Ein zurueckgezogener Schluessel zieht keinen anderen mit.
|
||||
assert (await client.get(f"/api/ninstrip/firmware/{anderer}")).status == 200
|
||||
|
||||
|
||||
async def test_die_eingestellte_adresse_hat_vorrang(hass: HomeAssistant) -> None:
|
||||
await async_process_ha_core_config(hass, {"internal_url": "http://192.168.1.60:8123"})
|
||||
assert (
|
||||
device_base_url(hass, {CONF_DEVICE_BASE_URL: "http://192.168.1.50:8123"})
|
||||
== "http://192.168.1.50:8123"
|
||||
)
|
||||
|
||||
|
||||
async def test_sonst_gilt_die_interne_http_adresse(hass: HomeAssistant) -> None:
|
||||
await async_process_ha_core_config(hass, {"internal_url": "http://192.168.1.60:8123"})
|
||||
assert device_base_url(hass, {}) == "http://192.168.1.60:8123"
|
||||
|
||||
|
||||
async def test_https_wird_abgelehnt(hass: HomeAssistant) -> None:
|
||||
"""Die Firmware laedt nur ueber schlichtes http (esp_https_ota mit ALLOW_HTTP)."""
|
||||
await async_process_ha_core_config(hass, {"internal_url": "https://ha.local:8123"})
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
device_base_url(hass, {})
|
||||
assert raised.value.translation_key == "no_http_url"
|
||||
|
||||
|
||||
async def test_ohne_jede_adresse(hass: HomeAssistant) -> None:
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
device_base_url(hass, {})
|
||||
assert raised.value.translation_key == "no_http_url"
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Einrichten, Entladen und das Geraet in der Registrierung."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.ninstrip.api import NinstripAuthError, NinstripConnectionError
|
||||
from custom_components.ninstrip.const import DOMAIN
|
||||
from tests_unit.samples import MAC_K1Y
|
||||
|
||||
|
||||
async def test_einrichten_und_entladen(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry
|
||||
) -> None:
|
||||
assert init_integration.state is ConfigEntryState.LOADED
|
||||
assert await hass.config_entries.async_unload(init_integration.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert init_integration.state is ConfigEntryState.NOT_LOADED
|
||||
|
||||
|
||||
async def test_geraet_traegt_mac_modell_und_version(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry
|
||||
) -> None:
|
||||
geraet = dr.async_get(hass).async_get_device_by_identifier(
|
||||
(DOMAIN, MAC_K1Y), init_integration.entry_id
|
||||
)
|
||||
assert geraet is not None
|
||||
assert geraet.manufacturer == "ninstrip"
|
||||
# Das Modell beschreibt den Strip, nicht das Produkt - das steht in model_id.
|
||||
assert geraet.model == "sk6812_rgbw, 60 Pixel"
|
||||
assert geraet.model_id == "ninstrip"
|
||||
assert geraet.sw_version == "0.1.0-12-g71a57"
|
||||
assert (dr.CONNECTION_NETWORK_MAC, MAC_K1Y) in geraet.connections
|
||||
|
||||
|
||||
async def test_unerreichbares_geraet_wird_spaeter_erneut_versucht(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
mock_client.get_state.side_effect = NinstripConnectionError("weg")
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
|
||||
|
||||
async def test_abgelehntes_token_verlangt_neue_anmeldung(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
mock_client.get_state.side_effect = NinstripAuthError("abgelehnt")
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
|
||||
assert any(
|
||||
flow["context"]["source"] == "reauth" for flow in hass.config_entries.flow.async_progress()
|
||||
)
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Hauptschalter und Helligkeit."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from homeassistant.components.light import ATTR_BRIGHTNESS, ColorMode
|
||||
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
|
||||
from homeassistant.core import HomeAssistant
|
||||
import pytest
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
from tests.helpers import entity_id_for
|
||||
|
||||
|
||||
def light_id(hass: HomeAssistant) -> str:
|
||||
return entity_id_for(hass, "light", "light")
|
||||
|
||||
|
||||
async def abfragen(hass: HomeAssistant, freezer: FrozenDateTimeFactory) -> None:
|
||||
"""Einen Abfragezyklus vorspulen."""
|
||||
freezer.tick(timedelta(seconds=31))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
async def test_zustand_und_helligkeit_aus_prozent(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry
|
||||
) -> None:
|
||||
state = hass.states.get(light_id(hass))
|
||||
assert state is not None
|
||||
assert state.state == STATE_ON
|
||||
# Das Geraet rechnet in Prozent: 100 % sind 255.
|
||||
assert state.attributes[ATTR_BRIGHTNESS] == 255
|
||||
assert state.attributes["color_mode"] == ColorMode.BRIGHTNESS
|
||||
assert state.attributes["pixel_count"] == 60
|
||||
assert state.attributes["segment_count"] == 1
|
||||
assert state.attributes["preset"] == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("prozent", "erwartet"), [(0, 0), (1, 3), (37, 94), (50, 128), (99, 252), (100, 255)]
|
||||
)
|
||||
async def test_prozent_werden_auf_0_bis_255_umgerechnet(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_state: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
prozent: int,
|
||||
erwartet: int,
|
||||
) -> None:
|
||||
strip_state["brightness"] = prozent
|
||||
await abfragen(hass, freezer)
|
||||
assert hass.states.get(light_id(hass)).attributes[ATTR_BRIGHTNESS] == erwartet
|
||||
|
||||
|
||||
@pytest.mark.parametrize("wert", [-5, 150])
|
||||
async def test_unsinnige_helligkeit_wird_gekappt(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_state: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
wert: int,
|
||||
) -> None:
|
||||
"""Ein Geraet, das ausserhalb von 0..100 antwortet, darf HA nicht sprengen."""
|
||||
strip_state["brightness"] = wert
|
||||
await abfragen(hass, freezer)
|
||||
assert hass.states.get(light_id(hass)).attributes[ATTR_BRIGHTNESS] in (0, 255)
|
||||
|
||||
|
||||
async def test_einschalten_ohne_helligkeit_schickt_nur_on(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
await hass.services.async_call(
|
||||
"light", "turn_on", {ATTR_ENTITY_ID: light_id(hass)}, blocking=True
|
||||
)
|
||||
mock_client.set_state.assert_awaited_once_with(on=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("ha_wert", "prozent"), [(255, 100), (128, 50), (3, 1), (1, 0)])
|
||||
async def test_einschalten_mit_helligkeit_rechnet_in_prozent(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
mock_client: MagicMock,
|
||||
ha_wert: int,
|
||||
prozent: int,
|
||||
) -> None:
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{ATTR_ENTITY_ID: light_id(hass), ATTR_BRIGHTNESS: ha_wert},
|
||||
blocking=True,
|
||||
)
|
||||
mock_client.set_state.assert_awaited_once_with(on=True, brightness=prozent)
|
||||
|
||||
|
||||
async def test_ausschalten(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
await hass.services.async_call(
|
||||
"light", "turn_off", {ATTR_ENTITY_ID: light_id(hass)}, blocking=True
|
||||
)
|
||||
mock_client.set_state.assert_awaited_once_with(on=False)
|
||||
assert hass.states.get(light_id(hass)).state == STATE_OFF
|
||||
|
||||
|
||||
async def test_die_antwort_des_geraets_zaehlt_nicht_die_anfrage(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
"""Das Geraet darf die Helligkeit abweichend beantworten - dann gilt seine."""
|
||||
|
||||
async def antwortet_anders(**fields: Any) -> dict[str, Any]:
|
||||
return {**mock_client.get_state.side_effect(), **fields, "brightness": 20}
|
||||
|
||||
mock_client.set_state.side_effect = antwortet_anders
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{ATTR_ENTITY_ID: light_id(hass), ATTR_BRIGHTNESS: 255},
|
||||
blocking=True,
|
||||
)
|
||||
assert hass.states.get(light_id(hass)).attributes[ATTR_BRIGHTNESS] == 51
|
||||
@@ -0,0 +1,160 @@
|
||||
"""sACN: Schalter, Universe, Startslot, Verhalten nach dem Stromende, Merker."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON, STATE_UNAVAILABLE
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ServiceValidationError
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
import pytest
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from tests.helpers import abfragen, entity_id_for
|
||||
|
||||
|
||||
async def test_schalter_zeigt_den_eingestellten_zustand(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry
|
||||
) -> None:
|
||||
assert hass.states.get(entity_id_for(hass, "switch", "sacn_enabled")).state == STATE_ON
|
||||
|
||||
|
||||
async def test_schalter_schreibt_und_liest_zurueck(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
entity_id = entity_id_for(hass, "switch", "sacn_enabled")
|
||||
await hass.services.async_call("switch", "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True)
|
||||
mock_client.set_sacn.assert_awaited_once_with(enabled=False)
|
||||
# Nicht geraten, sondern zurueckgelesen: das Geraet antwortet nur mit "ok".
|
||||
assert mock_client.get_settings.await_count >= 2
|
||||
assert hass.states.get(entity_id).state == STATE_OFF
|
||||
|
||||
|
||||
async def test_universe_und_startslot(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
universe = entity_id_for(hass, "number", "sacn_universe")
|
||||
slot = entity_id_for(hass, "number", "sacn_start_slot")
|
||||
assert hass.states.get(universe).state == "1.0"
|
||||
assert hass.states.get(slot).state == "1.0"
|
||||
await hass.services.async_call(
|
||||
"number", "set_value", {ATTR_ENTITY_ID: universe, "value": 7}, blocking=True
|
||||
)
|
||||
mock_client.set_sacn.assert_awaited_with(universe=7)
|
||||
await hass.services.async_call(
|
||||
"number", "set_value", {ATTR_ENTITY_ID: slot, "value": 4}, blocking=True
|
||||
)
|
||||
mock_client.set_sacn.assert_awaited_with(start_slot=4)
|
||||
|
||||
|
||||
async def test_startslot_endet_bei_510(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
"""Hinter 510 passt bei drei Kanaeln kein ganzes Pixel mehr ins Universe."""
|
||||
slot = entity_id_for(hass, "number", "sacn_start_slot")
|
||||
assert hass.states.get(slot).attributes["max"] == 510
|
||||
with pytest.raises(ServiceValidationError):
|
||||
await hass.services.async_call(
|
||||
"number", "set_value", {ATTR_ENTITY_ID: slot, "value": 511}, blocking=True
|
||||
)
|
||||
mock_client.set_sacn.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("kanaele", "grenze"), [(3, 510), (4, 509), (5, 508)])
|
||||
async def test_die_grenze_folgt_den_kanaelen_je_pixel(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_settings: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
kanaele: int,
|
||||
grenze: int,
|
||||
) -> None:
|
||||
strip_settings["sacn"]["channels_per_pixel"] = kanaele
|
||||
await abfragen(hass, freezer)
|
||||
slot = entity_id_for(hass, "number", "sacn_start_slot")
|
||||
assert hass.states.get(slot).attributes["max"] == grenze
|
||||
|
||||
|
||||
async def test_unsinnige_kanalzahl_faellt_auf_drei_zurueck(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_settings: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
strip_settings["sacn"]["channels_per_pixel"] = "drei"
|
||||
await abfragen(hass, freezer)
|
||||
slot = entity_id_for(hass, "number", "sacn_start_slot")
|
||||
assert hass.states.get(slot).attributes["max"] == 510
|
||||
|
||||
|
||||
async def test_verhalten_nach_dem_stromende(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
entity_id = entity_id_for(hass, "select", "sacn_on_timeout")
|
||||
state = hass.states.get(entity_id)
|
||||
assert state.state == "release"
|
||||
assert state.attributes["options"] == ["release", "hold"]
|
||||
await hass.services.async_call(
|
||||
"select", "select_option", {ATTR_ENTITY_ID: entity_id, "option": "hold"}, blocking=True
|
||||
)
|
||||
mock_client.set_sacn.assert_awaited_once_with(on_timeout="hold")
|
||||
assert hass.states.get(entity_id).state == "hold"
|
||||
|
||||
|
||||
async def test_unbekanntes_verhalten_zeigt_keinen_wert(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_settings: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
strip_settings["sacn"]["on_timeout"] = "irgendwas"
|
||||
await abfragen(hass, freezer)
|
||||
assert hass.states.get(entity_id_for(hass, "select", "sacn_on_timeout")).state == "unknown"
|
||||
|
||||
|
||||
async def test_aktiv_merker_folgt_dem_strom(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_info: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
entity_id = entity_id_for(hass, "binary_sensor", "sacn_active")
|
||||
assert hass.states.get(entity_id).state == STATE_OFF
|
||||
strip_info["sacn"]["active"] = True
|
||||
await abfragen(hass, freezer)
|
||||
assert hass.states.get(entity_id).state == STATE_ON
|
||||
|
||||
|
||||
async def test_multicast_merker_ist_von_haus_aus_aus(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry
|
||||
) -> None:
|
||||
eintrag = er.async_get(hass).async_get(entity_id_for(hass, "binary_sensor", "sacn_multicast"))
|
||||
assert eintrag.disabled_by is er.RegistryEntryDisabler.INTEGRATION
|
||||
|
||||
|
||||
async def test_firmware_ohne_sacn_laesst_die_entitaeten_unverfuegbar(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_client: MagicMock,
|
||||
strip_settings: dict[str, Any],
|
||||
strip_info: dict[str, Any],
|
||||
) -> None:
|
||||
"""Die Entitaeten entstehen trotzdem - nach einem Firmware-Update werden
|
||||
sie beim naechsten Abfragen lebendig, ohne die Integration neu zu laden."""
|
||||
strip_settings.pop("sacn")
|
||||
strip_info.pop("sacn")
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
for platform, key in (
|
||||
("switch", "sacn_enabled"),
|
||||
("number", "sacn_universe"),
|
||||
("number", "sacn_start_slot"),
|
||||
("select", "sacn_on_timeout"),
|
||||
("binary_sensor", "sacn_active"),
|
||||
):
|
||||
entity_id = entity_id_for(hass, platform, key)
|
||||
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE, entity_id
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Szenenauswahl."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from homeassistant.const import ATTR_ENTITY_ID
|
||||
from homeassistant.core import HomeAssistant
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.ninstrip.select import NONE_OPTION
|
||||
from tests.helpers import abfragen, entity_id_for
|
||||
|
||||
|
||||
def preset_id(hass: HomeAssistant) -> str:
|
||||
return entity_id_for(hass, "select", "preset")
|
||||
|
||||
|
||||
async def test_nur_belegte_szenen_stehen_zur_wahl(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry
|
||||
) -> None:
|
||||
state = hass.states.get(preset_id(hass))
|
||||
assert state.attributes["options"] == [
|
||||
NONE_OPTION,
|
||||
"Warmweiss",
|
||||
"Kaltweiss",
|
||||
"Regenbogen",
|
||||
"Feuer",
|
||||
]
|
||||
assert state.state == "Regenbogen"
|
||||
|
||||
|
||||
async def test_geaenderte_segmente_zeigen_keine_szene_mehr(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_state: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
strip_state["preset_modified"] = True
|
||||
await abfragen(hass, freezer)
|
||||
assert hass.states.get(preset_id(hass)).state == NONE_OPTION
|
||||
|
||||
|
||||
async def test_unbekannte_szenennummer_zeigt_keine_szene(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_state: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
strip_state["preset"] = 6 # vorhanden, aber unbelegt
|
||||
await abfragen(hass, freezer)
|
||||
assert hass.states.get(preset_id(hass)).state == NONE_OPTION
|
||||
|
||||
|
||||
async def test_namenlose_szene_bekommt_eine_nummer(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_presets: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
strip_presets["presets"][2]["name"] = ""
|
||||
await abfragen(hass, freezer)
|
||||
state = hass.states.get(preset_id(hass))
|
||||
assert "Szene 3" in state.attributes["options"]
|
||||
assert state.state == "Szene 3"
|
||||
|
||||
|
||||
async def test_szene_waehlen_schaltet_sie_auf(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
await hass.services.async_call(
|
||||
"select",
|
||||
"select_option",
|
||||
{ATTR_ENTITY_ID: preset_id(hass), "option": "Feuer"},
|
||||
blocking=True,
|
||||
)
|
||||
mock_client.apply_preset.assert_awaited_once_with(3)
|
||||
|
||||
|
||||
async def test_die_leere_wahl_schaltet_aus(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
"""Es gibt kein 'Szene abwaehlen' - das Gegenstueck ist Ausschalten."""
|
||||
await hass.services.async_call(
|
||||
"select",
|
||||
"select_option",
|
||||
{ATTR_ENTITY_ID: preset_id(hass), "option": NONE_OPTION},
|
||||
blocking=True,
|
||||
)
|
||||
mock_client.set_state.assert_awaited_once_with(on=False)
|
||||
mock_client.apply_preset.assert_not_awaited()
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Diagnosesensoren."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
import pytest
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from tests.helpers import abfragen, entity_id_for
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("key", "wert"),
|
||||
[("rssi", "-68"), ("uptime", "1459"), ("free_heap", "156848"), ("power_scale", "100")],
|
||||
)
|
||||
async def test_werte(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry, key: str, wert: str
|
||||
) -> None:
|
||||
registry = er.async_get(hass)
|
||||
entity_id = entity_id_for(hass, "sensor", key)
|
||||
eintrag = registry.async_get(entity_id)
|
||||
assert eintrag is not None
|
||||
if eintrag.disabled:
|
||||
# Die drei Diagnosesensoren sind standardmaessig aus; dann gibt es
|
||||
# keinen Zustand, und mehr ist hier nicht zu pruefen.
|
||||
assert key in ("rssi", "uptime", "free_heap")
|
||||
return
|
||||
assert hass.states.get(entity_id).state == wert
|
||||
|
||||
|
||||
async def test_nur_die_leistungsbegrenzung_ist_von_haus_aus_an(
|
||||
hass: HomeAssistant, init_integration: MockConfigEntry
|
||||
) -> None:
|
||||
registry = er.async_get(hass)
|
||||
an = [
|
||||
registry.async_get(entity_id_for(hass, "sensor", key)).disabled_by is None
|
||||
for key in ("rssi", "uptime", "free_heap", "power_scale")
|
||||
]
|
||||
assert an == [False, False, False, True]
|
||||
|
||||
|
||||
async def test_fehlender_wifi_block_ergibt_keinen_wert(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
strip_info: dict[str, Any],
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Ein Geraet im Onboarding meldet keinen strip-Block mit power_scale."""
|
||||
strip_info.pop("strip")
|
||||
await abfragen(hass, freezer)
|
||||
assert hass.states.get(entity_id_for(hass, "sensor", "power_scale")).state == "unknown"
|
||||
@@ -0,0 +1,578 @@
|
||||
"""Die Update-Entitaet: Angebot, WLAN-Sicherung, Ablauf der Aktualisierung."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from homeassistant.components.update import (
|
||||
ATTR_IN_PROGRESS,
|
||||
ATTR_INSTALLED_VERSION,
|
||||
ATTR_LATEST_VERSION,
|
||||
SERVICE_INSTALL,
|
||||
)
|
||||
from homeassistant.components.update import (
|
||||
DOMAIN as UPDATE_DOMAIN,
|
||||
)
|
||||
from homeassistant.const import ATTR_ENTITY_ID, CONF_HOST, CONF_TOKEN, STATE_OFF, STATE_ON
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.core_config import async_process_ha_core_config
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers import issue_registry as ir
|
||||
import pytest
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
from pytest_homeassistant_custom_component.typing import ClientSessionGenerator
|
||||
|
||||
from custom_components.ninstrip import update as update_module
|
||||
from custom_components.ninstrip.api import NinstripBusyError, NinstripConnectionError
|
||||
from custom_components.ninstrip.const import CONF_DEVICE_BASE_URL, DOMAIN
|
||||
from custom_components.ninstrip.shared import DATA_SHARED, async_scan_catalog
|
||||
from custom_components.ninstrip.update import haengt_an_kompiliertem_wlan
|
||||
from tests.helpers import entity_id_for
|
||||
from tests_unit.images import CONTENT_WITH_SSID, CONTENT_WITHOUT_SSID, build_image
|
||||
from tests_unit.samples import HOST_K1Y, MAC_K1Y, SETTINGS_COMPILED, SETTINGS_STORED, TOKEN
|
||||
|
||||
BASE = "http://192.168.1.50:8123"
|
||||
INSTALLED = "0.1.0-12-g71a57"
|
||||
NEWER = "0.1.0-47-g71a57"
|
||||
NEWEST = "0.1.1-rc1"
|
||||
EVEN_NEWER = "0.1.1-rc2" # newer than NEWEST
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config_entry() -> MockConfigEntry:
|
||||
return MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title="ninstrip ad4c",
|
||||
unique_id=MAC_K1Y,
|
||||
data={CONF_HOST: HOST_K1Y, CONF_TOKEN: TOKEN},
|
||||
options={CONF_DEVICE_BASE_URL: BASE},
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fast_polling(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(update_module, "OTA_POLL_INTERVAL_S", 0)
|
||||
|
||||
|
||||
def put(directory: Path, name: str, **kwargs: Any) -> Path:
|
||||
path = directory / name
|
||||
path.write_bytes(build_image(**kwargs))
|
||||
return path
|
||||
|
||||
|
||||
async def rescan(hass: HomeAssistant) -> None:
|
||||
await async_scan_catalog(hass, hass.data[DATA_SHARED])
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
def wifi_issue(hass: HomeAssistant, entry: MockConfigEntry) -> ir.IssueEntry | None:
|
||||
return ir.async_get(hass).async_get_issue(DOMAIN, f"wifi_guard_{entry.entry_id}")
|
||||
|
||||
|
||||
async def install(hass: HomeAssistant) -> None:
|
||||
await hass.services.async_call(
|
||||
UPDATE_DOMAIN,
|
||||
SERVICE_INSTALL,
|
||||
{ATTR_ENTITY_ID: entity_id_for(hass, "update", "firmware")},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
|
||||
def test_nur_gespeichertes_wlan_ist_unabhaengig() -> None:
|
||||
assert not haengt_an_kompiliertem_wlan(SETTINGS_STORED)
|
||||
assert haengt_an_kompiliertem_wlan(SETTINGS_COMPILED)
|
||||
assert haengt_an_kompiliertem_wlan({"wifi": {"ssid": ""}})
|
||||
assert haengt_an_kompiliertem_wlan({"wifi": {"source": "flash"}})
|
||||
assert haengt_an_kompiliertem_wlan({})
|
||||
|
||||
|
||||
async def test_ohne_abbilder_kein_update(hass: HomeAssistant, init_integration) -> None:
|
||||
state = hass.states.get(entity_id_for(hass, "update", "firmware"))
|
||||
assert state.state == STATE_OFF
|
||||
assert state.attributes[ATTR_INSTALLED_VERSION] == INSTALLED
|
||||
assert state.attributes[ATTR_LATEST_VERSION] == INSTALLED
|
||||
|
||||
|
||||
async def test_neueres_abbild_mit_zugangsdaten_wird_angeboten(
|
||||
hass: HomeAssistant, init_integration, firmware_dir: Path
|
||||
) -> None:
|
||||
# Zugleich die Probe auf den eigenen Versionsvergleich: HA haelt
|
||||
# 0.1.0-12-g71a57 und 0.1.0-47-g71a57 fuer denselben Versionskern und
|
||||
# vergleicht dann Zeichenketten - damit bliebe das hier aus.
|
||||
put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
state = hass.states.get(entity_id_for(hass, "update", "firmware"))
|
||||
assert state.state == STATE_ON
|
||||
assert state.attributes[ATTR_LATEST_VERSION] == NEWER
|
||||
assert wifi_issue(hass, init_integration) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"image",
|
||||
[
|
||||
{
|
||||
"device_type": "ninstrip-rgbc3",
|
||||
"version": "0.2.0",
|
||||
}, # other type that only differs in the suffix
|
||||
{"device_type": "ninstrip-k1y", "version": "0.1.0-12-gffff0"}, # same version, other hash
|
||||
{"device_type": "ninstrip-k1y", "version": "0.1.0"}, # older
|
||||
],
|
||||
)
|
||||
async def test_unpassende_abbilder_werden_nicht_angeboten(
|
||||
hass: HomeAssistant, init_integration, firmware_dir: Path, image: dict[str, str]
|
||||
) -> None:
|
||||
put(firmware_dir, "a.img", payload=CONTENT_WITH_SSID, **image)
|
||||
await rescan(hass)
|
||||
assert hass.states.get(entity_id_for(hass, "update", "firmware")).state == STATE_OFF
|
||||
|
||||
|
||||
async def test_wlan_sicherung_haelt_abbild_ohne_zugangsdaten_zurueck(
|
||||
hass: HomeAssistant, init_integration, firmware_dir: Path
|
||||
) -> None:
|
||||
nocreds = put(firmware_dir, "nocreds.img", version=NEWEST, payload=CONTENT_WITHOUT_SSID)
|
||||
await rescan(hass)
|
||||
entity_id = entity_id_for(hass, "update", "firmware")
|
||||
assert hass.states.get(entity_id).state == STATE_OFF
|
||||
issue = wifi_issue(hass, init_integration)
|
||||
assert issue is not None
|
||||
assert issue.translation_placeholders == {
|
||||
"name": "ninstrip ad4c",
|
||||
"version": NEWEST,
|
||||
"device_type": "ninstrip-k1y",
|
||||
"ssid": "ninIOT",
|
||||
}
|
||||
|
||||
put(firmware_dir, "creds.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
assert hass.states.get(entity_id).attributes[ATTR_LATEST_VERSION] == NEWER
|
||||
assert wifi_issue(hass, init_integration) is not None # the newer, blocked one is still there
|
||||
|
||||
nocreds.unlink()
|
||||
await rescan(hass)
|
||||
assert hass.states.get(entity_id).attributes[ATTR_LATEST_VERSION] == NEWER
|
||||
assert wifi_issue(hass, init_integration) is None
|
||||
|
||||
|
||||
async def test_geraet_mit_gespeichertem_wlan_bekommt_auch_abbilder_ohne_zugangsdaten(
|
||||
hass: HomeAssistant, init_integration, firmware_dir: Path, strip_settings: dict[str, Any]
|
||||
) -> None:
|
||||
strip_settings.clear()
|
||||
strip_settings.update(SETTINGS_STORED)
|
||||
put(firmware_dir, "nocreds.img", version=NEWEST, payload=CONTENT_WITHOUT_SSID)
|
||||
await rescan(hass)
|
||||
assert (
|
||||
hass.states.get(entity_id_for(hass, "update", "firmware")).attributes[ATTR_LATEST_VERSION]
|
||||
== NEWEST
|
||||
)
|
||||
assert wifi_issue(hass, init_integration) is None
|
||||
|
||||
|
||||
async def test_geraet_ohne_ssid_bekommt_nichts(
|
||||
hass: HomeAssistant, init_integration, firmware_dir: Path, strip_info: dict[str, Any]
|
||||
) -> None:
|
||||
strip_info["wifi"]["ssid"] = ""
|
||||
await init_integration.runtime_data.async_refresh()
|
||||
put(firmware_dir, "creds.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
assert hass.states.get(entity_id_for(hass, "update", "firmware")).state == STATE_OFF
|
||||
|
||||
|
||||
async def test_unlesbare_einstellungen_lassen_das_bisherige_angebot_stehen(
|
||||
hass: HomeAssistant, init_integration, firmware_dir: Path, mock_client: MagicMock
|
||||
) -> None:
|
||||
mock_client.get_settings.side_effect = NinstripConnectionError("down")
|
||||
put(firmware_dir, "creds.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
assert hass.states.get(entity_id_for(hass, "update", "firmware")).state == STATE_OFF
|
||||
|
||||
|
||||
async def test_aktualisierung_liefert_das_abbild_einmal_und_wartet_auf_die_neue_version(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
init_integration,
|
||||
mock_client: MagicMock,
|
||||
strip_info: dict[str, Any],
|
||||
firmware_dir: Path,
|
||||
) -> None:
|
||||
path = put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
client = await hass_client_no_auth()
|
||||
served: dict[str, Any] = {}
|
||||
|
||||
async def geraet_laedt(url: str) -> None:
|
||||
served["url"] = url
|
||||
response = await client.get(urlsplit(url).path)
|
||||
served["status"] = response.status
|
||||
served["body"] = await response.read()
|
||||
served["ota_flag"] = init_integration.runtime_data.ota_in_progress
|
||||
strip_info["fw_version"] = NEWER
|
||||
strip_info["uptime"] = 4
|
||||
|
||||
mock_client.fw_update.side_effect = geraet_laedt
|
||||
await install(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert served["url"].startswith(f"{BASE}/api/ninstrip/firmware/")
|
||||
assert (served["status"], served["body"]) == (200, path.read_bytes())
|
||||
assert served["ota_flag"] is True
|
||||
assert (await client.get(urlsplit(served["url"]).path)).status == 404
|
||||
assert len(hass.data[DATA_SHARED].registry) == 0
|
||||
state = hass.states.get(entity_id_for(hass, "update", "firmware"))
|
||||
assert state.attributes[ATTR_INSTALLED_VERSION] == NEWER
|
||||
assert state.attributes[ATTR_IN_PROGRESS] is False
|
||||
assert state.state == STATE_OFF
|
||||
assert init_integration.runtime_data.ota_in_progress is False
|
||||
|
||||
|
||||
async def test_ausgeliefert_werden_genau_die_geprueften_bytes(
|
||||
hass: HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
init_integration,
|
||||
mock_client: MagicMock,
|
||||
strip_info: dict[str, Any],
|
||||
firmware_dir: Path,
|
||||
) -> None:
|
||||
"""F1: the strip must receive exactly the bytes checked (Wi-Fi guard, type, hash) at install
|
||||
time, even if the file on disk is replaced by something else afterwards - e.g. a build script
|
||||
that writes the no-credentials variant over the same filename mid-update.
|
||||
"""
|
||||
path = put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
verified_bytes = path.read_bytes()
|
||||
await rescan(hass)
|
||||
client = await hass_client_no_auth()
|
||||
served: dict[str, Any] = {}
|
||||
|
||||
async def geraet_laedt(url: str) -> None:
|
||||
# Swap in a different, otherwise-valid image for the same device type right before the
|
||||
# strip "fetches" it. The Wi-Fi guard already passed for `verified_bytes`; this replacement
|
||||
# has no credentials at all and must never reach the strip.
|
||||
path.write_bytes(build_image(version=NEWER, payload=CONTENT_WITHOUT_SSID))
|
||||
served["url"] = url
|
||||
response = await client.get(urlsplit(url).path)
|
||||
served["status"] = response.status
|
||||
served["body"] = await response.read()
|
||||
strip_info["fw_version"] = NEWER
|
||||
strip_info["uptime"] = 4
|
||||
|
||||
mock_client.fw_update.side_effect = geraet_laedt
|
||||
await install(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert served["status"] == 200
|
||||
assert served["body"] == verified_bytes
|
||||
assert served["body"] != path.read_bytes() # the swapped-in file, not what was served
|
||||
|
||||
|
||||
async def test_katalogdurchlauf_waehrend_der_aktualisierung_prueft_nicht(
|
||||
hass: HomeAssistant,
|
||||
init_integration,
|
||||
mock_client: MagicMock,
|
||||
strip_info: dict[str, Any],
|
||||
firmware_dir: Path,
|
||||
) -> None:
|
||||
"""M2: a catalog rescan landing while an install is in progress must not evaluate offers
|
||||
against the (currently flashing) strip - that would mean extra requests to it and could churn
|
||||
the offer/issue underneath the install.
|
||||
"""
|
||||
put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
calls_before_rescan: dict[str, int] = {}
|
||||
|
||||
async def geraet_flasht(url: str) -> None:
|
||||
# a periodic catalog scan happens to land while this install is in progress
|
||||
before = mock_client.get_settings.await_count
|
||||
await rescan(hass)
|
||||
# Measured around the rescan itself, not after the install: once the install is
|
||||
# done the coordinator polls again anyway, and since the sACN settings became
|
||||
# entities that poll reads system/settings too. Comparing after the fact would
|
||||
# count that poll and fail for a reason this test does not care about.
|
||||
calls_before_rescan["delta"] = mock_client.get_settings.await_count - before
|
||||
strip_info["fw_version"] = NEWER
|
||||
strip_info["uptime"] = 4
|
||||
|
||||
mock_client.fw_update.side_effect = geraet_flasht
|
||||
await install(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert calls_before_rescan["delta"] == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("geraet_reaktion", "key", "reason_part"),
|
||||
[
|
||||
({"last_ota_error": "hash"}, "update_failed", "hash"),
|
||||
({"uptime": 3}, "update_failed", INSTALLED), # rebooted, still the old firmware
|
||||
],
|
||||
)
|
||||
async def test_fehler_des_geraets_werden_gemeldet(
|
||||
hass: HomeAssistant,
|
||||
init_integration,
|
||||
mock_client: MagicMock,
|
||||
strip_info: dict[str, Any],
|
||||
firmware_dir: Path,
|
||||
geraet_reaktion: dict[str, Any],
|
||||
key: str,
|
||||
reason_part: str,
|
||||
) -> None:
|
||||
put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
|
||||
async def geraet_scheitert(url: str) -> None:
|
||||
strip_info.update(geraet_reaktion)
|
||||
|
||||
mock_client.fw_update.side_effect = geraet_scheitert
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
await install(hass)
|
||||
assert raised.value.translation_key == key
|
||||
assert reason_part in raised.value.translation_placeholders["reason"]
|
||||
assert len(hass.data[DATA_SHARED].registry) == 0
|
||||
assert init_integration.runtime_data.ota_in_progress is False
|
||||
|
||||
|
||||
async def test_beschaeftigtes_geraet(
|
||||
hass: HomeAssistant, init_integration, mock_client: MagicMock, firmware_dir: Path
|
||||
) -> None:
|
||||
put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
mock_client.fw_update.side_effect = NinstripBusyError(409, "Update laeuft schon")
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
await install(hass)
|
||||
# "update_busy" meldet nur der eigene Riegel gegen zwei gleichzeitige
|
||||
# Aufrufe; ein 409 vom Geraet kommt als "device_busy" aus dem Koordinator.
|
||||
assert raised.value.translation_key == "device_busy"
|
||||
assert len(hass.data[DATA_SHARED].registry) == 0
|
||||
|
||||
|
||||
async def test_zeitueberschreitung(
|
||||
hass: HomeAssistant, init_integration, firmware_dir: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(update_module, "OTA_TIMEOUT_S", 0)
|
||||
put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
await install(hass)
|
||||
assert raised.value.translation_key == "update_timeout"
|
||||
|
||||
|
||||
async def test_ohne_http_adresse_geht_nichts(
|
||||
hass: HomeAssistant, mock_client: MagicMock, firmware_dir: Path
|
||||
) -> None:
|
||||
await async_process_ha_core_config(hass, {"internal_url": "https://ha.local:8123"})
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN, unique_id=MAC_K1Y, data={CONF_HOST: HOST_K1Y, CONF_TOKEN: TOKEN}
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(entry.entry_id)
|
||||
put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
await install(hass)
|
||||
assert raised.value.translation_key == "no_http_url"
|
||||
mock_client.fw_update.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_wlan_wird_unmittelbar_vor_dem_senden_nochmal_geprueft(
|
||||
hass: HomeAssistant,
|
||||
init_integration,
|
||||
mock_client: MagicMock,
|
||||
firmware_dir: Path,
|
||||
strip_settings: dict[str, Any],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
# Guards against a regression that would let this install slip past the re-check into the
|
||||
# wait loop: without this it would hang for the full OTA_TIMEOUT_S (12 min) instead of failing
|
||||
# fast with "wifi_guard".
|
||||
monkeypatch.setattr(update_module, "OTA_TIMEOUT_S", 0)
|
||||
strip_settings.clear()
|
||||
strip_settings.update(SETTINGS_STORED)
|
||||
put(firmware_dir, "nocreds.img", version=NEWEST, payload=CONTENT_WITHOUT_SSID)
|
||||
await rescan(hass)
|
||||
assert hass.states.get(entity_id_for(hass, "update", "firmware")).state == STATE_ON
|
||||
|
||||
strip_settings["wifi"]["source"] = "compiled" # the strip forgot its stored Wi-Fi meanwhile
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
await install(hass)
|
||||
assert raised.value.translation_key == "wifi_guard"
|
||||
assert raised.value.translation_placeholders == {"ssid": "ninIOT"}
|
||||
mock_client.fw_update.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_geaenderte_datei_wird_abgelehnt(
|
||||
hass: HomeAssistant, init_integration, mock_client: MagicMock, firmware_dir: Path
|
||||
) -> None:
|
||||
path = put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
path.write_bytes(build_image(version=NEWEST, payload=CONTENT_WITH_SSID))
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
await install(hass)
|
||||
assert raised.value.translation_key == "image_invalid"
|
||||
mock_client.fw_update.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_rueckschritt_wird_abgelehnt(
|
||||
hass: HomeAssistant,
|
||||
init_integration,
|
||||
mock_client: MagicMock,
|
||||
strip_info: dict[str, Any],
|
||||
firmware_dir: Path,
|
||||
) -> None:
|
||||
"""The strip may have been reflashed by another route since the offer was computed."""
|
||||
put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
entity_id = entity_id_for(hass, "update", "firmware")
|
||||
assert hass.states.get(entity_id).attributes[ATTR_LATEST_VERSION] == NEWER
|
||||
|
||||
# A newer image also appears on disk, and the strip is reflashed by another route to a version
|
||||
# newer than our stale offer - but the follow-up evaluation (triggered by the catalog scan)
|
||||
# fails at get_settings and returns early, so the stale NEWER offer survives untouched.
|
||||
put(firmware_dir, "b.img", version=EVEN_NEWER, payload=CONTENT_WITH_SSID)
|
||||
mock_client.get_settings.side_effect = NinstripConnectionError("down")
|
||||
strip_info["fw_version"] = NEWEST
|
||||
await rescan(hass)
|
||||
assert hass.states.get(entity_id).attributes[ATTR_LATEST_VERSION] == NEWER
|
||||
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
await install(hass)
|
||||
assert raised.value.translation_key == "no_update"
|
||||
mock_client.fw_update.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_zwei_gleichzeitige_aufrufe_werden_abgewiesen(
|
||||
hass: HomeAssistant,
|
||||
init_integration,
|
||||
mock_client: MagicMock,
|
||||
strip_info: dict[str, Any],
|
||||
firmware_dir: Path,
|
||||
) -> None:
|
||||
"""A second call arriving in the pre-flag window (before in_progress is set) must be
|
||||
rejected by our own lock rather than allowed to touch OTA state.
|
||||
|
||||
HA's own service-level "already in progress" guard only helps once `_attr_in_progress` is
|
||||
already True (it is a `cached_property` that HA invalidates whenever `_attr_in_progress` is
|
||||
set, so it is never stale) - by the time that guard would fire, a second concurrent call is
|
||||
already blocked by HA itself with translation_key "update_in_progress", not "update_busy".
|
||||
The real gap I2 describes is *before* that: image verification, `get_info` and `get_settings`
|
||||
are all awaited before we ever set the flags, and HA's guard does not protect that window. This
|
||||
test
|
||||
blocks the first `get_info()` re-check inside that window to reach it deterministically.
|
||||
"""
|
||||
put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
entity_id = entity_id_for(hass, "update", "firmware")
|
||||
|
||||
entered = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
first_call = True
|
||||
|
||||
async def blocking_get_info() -> dict[str, Any]:
|
||||
nonlocal first_call
|
||||
if first_call:
|
||||
first_call = False
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return deepcopy(strip_info)
|
||||
|
||||
async def geraet_flasht(url: str) -> None:
|
||||
strip_info["fw_version"] = NEWER
|
||||
strip_info["uptime"] = 4
|
||||
|
||||
mock_client.get_info.side_effect = blocking_get_info
|
||||
mock_client.fw_update.side_effect = geraet_flasht
|
||||
|
||||
task1 = hass.async_create_task(install(hass), name="install #1")
|
||||
async with asyncio.timeout(5):
|
||||
await entered.wait()
|
||||
|
||||
# Install #1 is blocked inside its pre-flag get_info() re-check: the lock is held, but
|
||||
# in_progress/ota_in_progress are still untouched.
|
||||
assert init_integration.runtime_data.ota_in_progress is False
|
||||
assert hass.states.get(entity_id).attributes[ATTR_IN_PROGRESS] is False
|
||||
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
await install(hass)
|
||||
assert raised.value.translation_key == "update_busy"
|
||||
assert init_integration.runtime_data.ota_in_progress is False
|
||||
assert hass.states.get(entity_id).attributes[ATTR_IN_PROGRESS] is False
|
||||
|
||||
release.set()
|
||||
async with asyncio.timeout(5):
|
||||
await task1
|
||||
assert init_integration.runtime_data.ota_in_progress is False
|
||||
assert hass.states.get(entity_id).attributes[ATTR_IN_PROGRESS] is False
|
||||
assert hass.states.get(entity_id).attributes[ATTR_INSTALLED_VERSION] == NEWER
|
||||
|
||||
|
||||
async def test_das_loeschen_des_eintrags_raeumt_den_wlan_hinweis_weg(
|
||||
hass: HomeAssistant, init_integration, firmware_dir: Path
|
||||
) -> None:
|
||||
put(firmware_dir, "nocreds.img", version=NEWEST, payload=CONTENT_WITHOUT_SSID)
|
||||
await rescan(hass)
|
||||
assert wifi_issue(hass, init_integration) is not None
|
||||
assert await hass.config_entries.async_remove(init_integration.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert wifi_issue(hass, init_integration) is None
|
||||
|
||||
|
||||
async def test_firmware_ohne_device_type_bekommt_kein_angebot(
|
||||
hass: HomeAssistant, init_integration, strip_info: dict[str, Any], firmware_dir: Path
|
||||
) -> None:
|
||||
"""Firmware vor v0.1.0 nennt ihre Platine nicht.
|
||||
|
||||
Dann bleibt offen, wofuer sie gebaut wurde - und ein K1Y-Abbild auf einer
|
||||
KL-RGBC3 invertiert das Datensignal nicht, der Strip bliebe dunkel. Lieber
|
||||
kein Angebot als das falsche.
|
||||
"""
|
||||
strip_info.pop("device_type")
|
||||
strip_info["fw_version"] = "0.1.0-12-g71a57"
|
||||
await init_integration.runtime_data.async_refresh()
|
||||
put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
put(
|
||||
firmware_dir,
|
||||
"b.img",
|
||||
device_type="ninstrip-rgbc3",
|
||||
version=NEWER,
|
||||
payload=CONTENT_WITH_SSID,
|
||||
)
|
||||
await rescan(hass)
|
||||
assert hass.states.get(entity_id_for(hass, "update", "firmware")).state == STATE_OFF
|
||||
|
||||
|
||||
async def test_unvergleichbare_version_bekommt_kein_angebot(
|
||||
hass: HomeAssistant, init_integration, strip_info: dict[str, Any], firmware_dir: Path
|
||||
) -> None:
|
||||
"""Ein Geraet mit dem alten Hash-Stand: welcher neuer ist, weiss niemand."""
|
||||
strip_info["fw_version"] = "652b2e2-dirty"
|
||||
await init_integration.runtime_data.async_refresh()
|
||||
put(firmware_dir, "a.img", version=NEWEST, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
assert hass.states.get(entity_id_for(hass, "update", "firmware")).state == STATE_OFF
|
||||
|
||||
|
||||
async def test_platine_wird_unmittelbar_vor_dem_senden_nochmal_geprueft(
|
||||
hass: HomeAssistant,
|
||||
init_integration,
|
||||
mock_client: MagicMock,
|
||||
strip_info: dict[str, Any],
|
||||
firmware_dir: Path,
|
||||
) -> None:
|
||||
"""Das Angebot galt fuer die Platine von vorhin.
|
||||
|
||||
Meldet das Geraet inzwischen eine andere - etwa weil an derselben Adresse
|
||||
ein anderes Geraet haengt -, darf das Abbild nicht mehr hinaus: ein
|
||||
K1Y-Abbild auf einer KL-RGBC3 invertiert das Datensignal nicht.
|
||||
"""
|
||||
put(firmware_dir, "a.img", version=NEWER, payload=CONTENT_WITH_SSID)
|
||||
await rescan(hass)
|
||||
assert hass.states.get(entity_id_for(hass, "update", "firmware")).state == STATE_ON
|
||||
|
||||
strip_info["device_type"] = "ninstrip-rgbc3"
|
||||
with pytest.raises(HomeAssistantError) as raised:
|
||||
await install(hass)
|
||||
assert raised.value.translation_key == "image_invalid"
|
||||
mock_client.fw_update.assert_not_awaited()
|
||||
assert len(hass.data[DATA_SHARED].registry) == 0
|
||||
Reference in New Issue
Block a user