diff --git a/CHANGELOG.md b/CHANGELOG.md index ae45bfb..347ca94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ All notable changes to `ebus-sdk` are recorded here. Format follows [Keep a Chan - Invalid ids, topics and domains are warned about, once per object, and still published ([#92](https://github.com/electrification-bus/python-sdk/issues/92), part of [#91](https://github.com/electrification-bus/python-sdk/issues/91)): a device, node or property id that is empty, starts with `$` or has a character outside `a-z`, `0-9` and `-` (convention.md:39, :41); a second node with an existing id in `Device.add_node()` or property in `Node.add_property()` whose `$description` differs from the first, which it still replaces (:294, :326; an identical re-declaration is not warned about); a device id already used on another branch of the same tree (:194; an ancestor or sibling with the id still raises `ValueError`); a root `homie_domain` that is `""` (still published as `ebus`), starts with `$` or contains `/`, `+` or `#` (:157, :161); and a `Controller.broadcast()` subtopic with a segment that is not a valid id (:533). `sanitize_homie_id()` documents that distinct inputs can map to the same id. - `Controller`: a zero-length property value removes the stored value from `DiscoveredDevice.properties` and fires the property-changed callback with `new_value=None`; it was stored as `""`. A zero-length `$target` removes the entry from `property_targets`. A single `0x00` byte still decodes to `""` (convention.md:62-63, :613; [#93](https://github.com/electrification-bus/python-sdk/issues/93)). - `Controller.set_property()` publishes at QoS 0 when the device's discovered `$description` marks the property `retained: false` (convention.md:49, :695); an explicit `qos=` still wins ([#93](https://github.com/electrification-bus/python-sdk/issues/93)). +- Breaking: invalid producer input that 0.25.0 warned about raises `ValueError`, before anything is published or attached, with the same `reason=` and id fields the warning carried ([#91](https://github.com/electrification-bus/python-sdk/issues/91)). A `homie.Property` raises from its constructor, so `Property(from_dict=...)`, `Node.add_property_from_dict()` and the declaration builders do too, for `propertyRetainedNull` (`retained=None`, which was published as `false`), `propertyDatatypeMissing`, `propertyDatatypeUnknown`, `propertyFormatMissing` (an `enum` or `color` with no `format`), `propertyEnumFormatEmptyValue`, `propertyEnumFormatDuplicate` and `propertyColorFormatInvalid`; `Property.set_format()` raises for the format checks and keeps the old format. `PropertySpec` raises the same reasons at declaration time, except for an `internal_only` spec, which never becomes a Homie property; `PropertySpec(retained=None)`, which the builder published as non-retained without a warning, also raises. `Device(description_extras=...)` with a Homie core `$description` key raises `deviceDescriptionExtrasCoreFieldDropped` (the key was dropped), and a child that raises is not attached to its parent. `Device.publish_alert()` raises `devicePublishAlertIdFormat` for an id outside `a-z`, `0-9`, `-` (it was published) and `devicePublishAlertEmptyMessage` for an empty or non-string message (it returned `False`); an id containing `/`, `+` or `#`, or an empty one, still returns `False`. ### Fixed diff --git a/README.md b/README.md index bc14bff..8b8c0c1 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,10 @@ temp.set_value(None) # retracts the retained topic (subscribers see nothing) label.set_value("") # publishes an empty-string VALUE (0x00 on the wire) ``` +#### Invalid declarations raise + +A property or device declaration that Homie 5 rejects raises `ValueError` before anything is published, with a `reason=` naming the problem: a property with no `datatype` or an unknown one, `retained=None`, an `enum` or `color` with no `format`, an enum `format` with an empty or duplicate value, a `color` `format` listing anything but `rgb`, `hsv`, `xyz`, and `description_extras` that set a core `$description` field. This applies to `homie.Property(...)`, `add_property_from_dict()`, `Property.set_format()`, `PropertySpec` and `Device(description_extras=...)`. + #### Values the datatype cannot represent are refused A value is encoded for its property's datatype before it is published (convention.md:74-150 at [homieiot/convention@7edc221](https://github.com/homieiot/convention/blob/7edc221336f1644a9f04445cbc50c5af695bb047/convention.md)). A value the datatype cannot represent is refused: nothing is published, the retained topic keeps the last good value, `set_value()` returns `False`, and a `reason=propertyValueRefused` warning names the problem. Refused: NaN and infinities on `float`, a `bool` on `integer` or `float`, an `integer` that is not whole or does not fit in 64 bits, an `enum` value not in its `format`, a `float` beyond the 64-bit float range, a `json` value that is not an array or object or contains NaN, and `""` on anything but `string`. Floats are written without `+` in the exponent (`1e20`, not `1e+20`). @@ -146,7 +150,7 @@ A property with `retained=False` publishes non-retained at QoS 0, as Homie 5 req #### Alerts -`device.publish_alert("battery", "Battery is low, at 8%")` raises a retained alert at `$alert/battery`; `device.clear_alert("battery")` deletes it. Alerts are republished on reconnect and cleared by `delete()`. `publish("$alert", ...)` without an alert id publishes nothing and logs a warning. +`device.publish_alert("battery", "Battery is low, at 8%")` raises a retained alert at `$alert/battery`; `device.clear_alert("battery")` deletes it. Alerts are republished on reconnect and cleared by `delete()`. `publish("$alert", ...)` without an alert id publishes nothing and logs a warning. An alert id outside `a-z`, `0-9`, `-`, or an empty message, raises `ValueError`. #### Inbound `/set` is validated diff --git a/src/ebus_sdk/declaration.py b/src/ebus_sdk/declaration.py index 1059646..1a05554 100644 --- a/src/ebus_sdk/declaration.py +++ b/src/ebus_sdk/declaration.py @@ -26,7 +26,7 @@ from typing import Any, Callable, Iterable, Optional, Sequence, Union from .adapter import bind_property_to_homie -from .homie import Device, PropertyDatatype, Unit +from .homie import Device, PropertyDatatype, Unit, _check_property_description from .property import GroupedPropertyDict from .property import Property as ObservableProperty @@ -129,6 +129,10 @@ def __post_init__(self) -> None: f"{self.capability}/{self.prop_id}: an internal_only property is never published, so it " "has no /set topic and cannot be settable" ) + # The Homie property this spec builds would raise the same ValueError, but + # mid-materialization, after earlier nodes and model entries exist (#91). + if not self.internal_only: + _check_property_description(self.prop_id, self.datatype, self.format, self.retained) @property def model_key(self) -> str: diff --git a/src/ebus_sdk/homie.py b/src/ebus_sdk/homie.py index ad7a6f0..937b231 100644 --- a/src/ebus_sdk/homie.py +++ b/src/ebus_sdk/homie.py @@ -239,6 +239,37 @@ def validate_json_format(value: Any, format_schema: Union[str, dict, None]) -> O ) +def _check_property_description(pid: Any, datatype: Any, fmt: Any, retained: Any = True) -> None: + """Raise ``ValueError`` for property ``$description`` fields Homie 5 rejects (#91). + + ``retained`` is a non-null boolean (convention.md:343); ``datatype`` is + required (:340) and must be a Homie 5 datatype; ``enum`` and ``color`` require + a ``format``; an enum format lists at least one value, none empty and none + duplicated (:392); a color format lists only ``rgb``, ``hsv`` and ``xyz`` (:393). + """ + if retained is None: + raise ValueError(f"reason=propertyRetainedNull,propertyID={pid},hint=retained must be True or False") + if datatype is None: + raise ValueError(f"reason=propertyDatatypeMissing,propertyID={pid},hint=datatype is required") + if datatype not in PropertyDatatype._value2member_map_: + raise ValueError(f"reason=propertyDatatypeUnknown,propertyID={pid},datatype={datatype}") + if datatype in (PropertyDatatype.ENUM, PropertyDatatype.COLOR) and not fmt: + raise ValueError( + f"reason=propertyFormatMissing,propertyID={pid},datatype={datatype},hint={datatype} requires a format" + ) + if datatype == PropertyDatatype.ENUM and isinstance(fmt, str): + values = fmt.split(",") + if "" in values: + raise ValueError(f"reason=propertyEnumFormatEmptyValue,propertyID={pid},format={fmt}") + if len(set(values)) != len(values): + raise ValueError(f"reason=propertyEnumFormatDuplicate,propertyID={pid},format={fmt}") + if datatype == PropertyDatatype.COLOR and isinstance(fmt, str): + if not set(fmt.split(",")) <= _COLOR_FORMATS: + raise ValueError( + f"reason=propertyColorFormatInvalid,propertyID={pid},format={fmt},hint=allowed: rgb, hsv, xyz" + ) + + @dataclass(frozen=True) class JsonFieldConstraint: """The control-surface constraint on one field of a ``json`` ``$format`` schema. @@ -753,7 +784,7 @@ def _encode_property_value(value: Any, datatype: Any, format_: Any = None) -> tu return _encode_duration(value) if datatype == PropertyDatatype.JSON: return _encode_json(value) - # string, and a missing or unknown datatype (already warned about). + # string, and a missing or unknown datatype. return (str(value.value) if isinstance(value, Enum) else str(value)), None @@ -895,7 +926,7 @@ def _parse_set_payload(text: str, datatype: Any, format_: Any, current: Any) -> return _encode_duration(text) if datatype == PropertyDatatype.DATETIME: return _encode_datetime(text) - # string, and a missing or unknown datatype (already warned about). + # string, and a missing or unknown datatype. return decode_empty_string(text), None @@ -1061,6 +1092,8 @@ def __init__( device = from_dict.get("device", None) set_callback = from_dict.get("set_callback", None) async_loop = from_dict.get("async_loop", None) + # Invalid Homie 5 input raises before anything is assigned or published (#91). + _check_property_description(id, datatype, format, retained) # Regardless of how we got this info, construct it # AKA, the "business logic" of the constructor _warn_invalid_id(self, "property", id) @@ -1079,10 +1112,6 @@ def __init__( self._set_callback = set_callback else: self._set_callback = None - if retained is None: - # `retained` is a non-nullable boolean in $description (convention.md:343). - # The publish path always treated None as non-retained, so keep that. - _warn_invalid_once(self, "retainedNull", f"reason=propertyRetainedNull,propertyID={id},treatedAs=false") self._retained = bool(retained) self._unit = unit self._supports_target = supports_target @@ -1141,43 +1170,6 @@ def __init__( self._initial_value_was_none = value is None # Check for skip_initial_publish flag from dict self._skip_initial_publish = from_dict.get("skip_initial_publish", False) if from_dict else False - self._check_description_fields() - - def _check_description_fields(self) -> None: - """Warn (once per problem) about $description fields Homie 5 rejects. - - ``datatype`` is required (convention.md:340); ``enum`` and ``color`` require - a ``format``; an enum format lists at least one value, none empty and none - duplicated (:392); a color format lists only ``rgb``, ``hsv`` and ``xyz`` - (:393). - """ - pid = self._id - datatype = self._datatype - if datatype is None: - _warn_invalid_once(self, "datatypeMissing", f"reason=propertyDatatypeMissing,propertyID={pid}") - return - if datatype not in PropertyDatatype._value2member_map_: - _warn_invalid_once( - self, "datatypeUnknown", f"reason=propertyDatatypeUnknown,propertyID={pid},datatype={datatype}" - ) - return - fmt = self._format - if datatype in (PropertyDatatype.ENUM, PropertyDatatype.COLOR) and not fmt: - _warn_invalid_once( - self, "formatMissing", f"reason=propertyFormatMissing,propertyID={pid},datatype={datatype}" - ) - return - if datatype == PropertyDatatype.ENUM and isinstance(fmt, str): - values = fmt.split(",") - if "" in values: - _warn_invalid_once(self, "enumEmptyValue", f"reason=propertyEnumFormatEmptyValue,propertyID={pid}") - if len(set(values)) != len(values): - _warn_invalid_once(self, "enumDuplicate", f"reason=propertyEnumFormatDuplicate,propertyID={pid}") - if datatype == PropertyDatatype.COLOR and isinstance(fmt, str): - if not set(fmt.split(",")) <= _COLOR_FORMATS: - _warn_invalid_once( - self, "colorFormatInvalid", f"reason=propertyColorFormatInvalid,propertyID={pid},format={fmt}" - ) def as_dict(self) -> dict: return { @@ -1315,9 +1307,12 @@ def set_format(self, new_format: Optional[str]) -> None: it; the SDK does not republish a single property attribute on its own. This is the public replacement for adapters that previously assigned the private ``_format`` because no setter existed (SDK-6do.2). + + A format Homie 5 rejects for this datatype raises ``ValueError`` and the + format is left unchanged. """ + _check_property_description(self._id, self._datatype, new_format) self._format = new_format - self._check_description_fields() def coerced_value(self) -> Optional[str]: """ @@ -1524,8 +1519,7 @@ def publish_value(self, *, force: bool = False) -> bool: # Encode an empty-string value as a single 0x00 byte so the broker # does not mistake it for a zero-length "clear retained" payload. Only # for string (convention.md:65-67); another datatype never encodes to - # "" because its encoder refuses an empty value. A missing datatype was - # warned about at construction and keeps the string behavior. + # "" because its encoder refuses an empty value. payload = encode_empty_string(value) # GH #50: skip a republish whose final wire payload is byte-identical to # the one already sitting on this topic. Compared AFTER coercion and @@ -1667,8 +1661,7 @@ def description(self) -> dict: property = dict() property["name"] = self._name if self._datatype is not None: - # Required (convention.md:340); a missing datatype was warned about at - # construction, and null is not a valid value for it. + # Required (convention.md:340); the constructor refuses a missing one. property["datatype"] = self.datatype() if self._format: fmt = self.format() @@ -2311,6 +2304,15 @@ def __init__( f"Device id={id}: cannot pass both mqtt_cfg= and mqttc=; pass mqtt_cfg to have the SDK " "build and own a client, or mqttc to inject one whose lifecycle you own" ) + # A core field is the SDK's to compute: an extra could otherwise add + # `root`/`parent` to a root device (convention.md:220) or a `type` the SDK + # omits (#91). + core_extras = sorted((description_extras or {}).keys() & _DESCRIPTION_CORE_FIELDS) + if core_extras: + raise ValueError( + f"reason=deviceDescriptionExtrasCoreFieldDropped,id={id},field={','.join(core_extras)}," + "hint=description_extras cannot set a Homie core $description field" + ) # The `_mqtt_cfg` term separates "root never started" (an error) from "root built # transport-free" (mqtt_cfg=None), which must still take children. Drop it and the # transport-free tree can only ever be a single node. @@ -2384,16 +2386,8 @@ def __init__( # `imported-from` attribute of the `energy.ebus.imported` extension). # Homie 5 forward-compat requires controllers to ignore unknown # description fields (convention §Forward compatibility), so these are - # safe; core fields always take precedence over an extra of the same key. + # safe; an extra naming a core field was refused above. self._description_extras = dict(description_extras) if description_extras else {} - for key in sorted(self._description_extras.keys() & _DESCRIPTION_CORE_FIELDS): - # A core field is the SDK's to compute: an extra could otherwise add - # `root`/`parent` to a root device (convention.md:220) or a `type` the - # SDK omits. Dropped, with a warning per the invalid-input policy. - del self._description_extras[key] - _warn_invalid_once( - self, f"extrasCoreField:{key}", f"reason=deviceDescriptionExtrasCoreFieldDropped,id={id},field={key}" - ) # Counter of how many state_transition() / delete() scopes are currently active # on this device. >0 means "a transition is in progress" — suppresses child-induced # parent flaps and makes nested state_transition()s reentrant (only the outermost @@ -2832,8 +2826,8 @@ def description(self) -> dict: # Required if the parent is NOT the root device. Defaults to the value of the root property. description["parent"] = self._parent.id() description["extensions"] = self._extensions - # Merge extension-defined device attributes (core fields were dropped from - # the extras at construction). + # Merge extension-defined device attributes (an extra naming a core field + # was refused at construction). for key, value in self._description_extras.items(): description.setdefault(key, value) # A new version whenever the document changes (convention.md:215), and the @@ -3412,20 +3406,22 @@ def publish_alert(self, alert_id: str, message: str) -> bool: ``alert_id`` must be a single topic level; one containing ``/``, ``+`` or ``#``, or an empty one, is refused. An id outside the Homie ID format - (``a-z``, ``0-9``, ``-``) is warned about and still published. ``message`` - must be a non-empty string: an empty payload deletes the topic, so clear an - alert with ``clear_alert()``. Returns True if published. + (``a-z``, ``0-9``, ``-``) raises ``ValueError``, and so does a ``message`` + that is not a non-empty string: an empty payload deletes the topic, so clear + an alert with ``clear_alert()``. Returns True if published. """ if not alert_id or not isinstance(alert_id, str) or any(c in alert_id for c in "/+#"): logger.warning(f"reason=devicePublishAlertInvalidId,id={self._id},alertId={alert_id!r}") return False if not re.fullmatch(r"[a-z0-9-]+", alert_id): - _warn_invalid_once( - self, f"alertId:{alert_id}", f"reason=devicePublishAlertIdFormat,id={self._id},alertId={alert_id}" + raise ValueError( + f"reason=devicePublishAlertIdFormat,id={self._id},alertId={alert_id},hint=use a-z, 0-9 and -" ) if not isinstance(message, str) or message == "": - logger.warning(f"reason=devicePublishAlertEmptyMessage,id={self._id},alertId={alert_id}") - return False + raise ValueError( + f"reason=devicePublishAlertEmptyMessage,id={self._id},alertId={alert_id}," + "hint=message must be a non-empty string; use clear_alert() to remove an alert" + ) self._alerts[alert_id] = message return self._publish_alert_topic(alert_id, message) diff --git a/tests/test_declaration.py b/tests/test_declaration.py index 4e9a18a..ad59a5e 100644 --- a/tests/test_declaration.py +++ b/tests/test_declaration.py @@ -331,6 +331,29 @@ def test_contradictory_settability_is_refused_at_declaration_time(): PropertySpec("control", "limit", PropertyDatatype.FLOAT, conditionally_settable=True, internal_only=True) +@pytest.mark.parametrize( + ("datatype", "kwargs", "reason"), + [ + (PropertyDatatype.FLOAT, {"retained": None}, "propertyRetainedNull"), + (None, {}, "propertyDatatypeMissing"), + ("decimal", {}, "propertyDatatypeUnknown"), + (PropertyDatatype.ENUM, {}, "propertyFormatMissing"), + (PropertyDatatype.COLOR, {}, "propertyFormatMissing"), + (PropertyDatatype.ENUM, {"format": "a,,b"}, "propertyEnumFormatEmptyValue"), + (PropertyDatatype.ENUM, {"format": "a,b,a"}, "propertyEnumFormatDuplicate"), + (PropertyDatatype.COLOR, {"format": "rgb,cmyk"}, "propertyColorFormatInvalid"), + ], +) +def test_invalid_homie_input_is_refused_at_declaration_time(datatype, kwargs, reason): + """The Homie property would raise mid-build, after earlier nodes exist (#91).""" + with pytest.raises(ValueError, match=rf"reason={reason},propertyID=mode\b"): + PropertySpec("control", "mode", datatype, **kwargs) + + +def test_an_internal_only_spec_is_not_checked_as_a_homie_property(): + PropertySpec("control", "mode", PropertyDatatype.ENUM, internal_only=True) + + def test_identity_is_fused_by_default(): spec = PropertySpec("meter", "active-power", PropertyDatatype.FLOAT) assert spec.model_key == "active-power" diff --git a/tests/test_device_tree.py b/tests/test_device_tree.py index b51c28d..1b731c7 100644 --- a/tests/test_device_tree.py +++ b/tests/test_device_tree.py @@ -393,7 +393,7 @@ def test_extend_gives_a_built_device_a_new_capability(root, mock_paho): builder.add(spec) assert builder.device_for(spec).get_node("shed") is None - props = builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM)]) + props = builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM, format="NORMAL,SHED")]) device = builder.device_for(spec) assert device.get_node("shed") is not None @@ -408,10 +408,10 @@ def test_extend_is_idempotent(root, mock_paho): builder = DeviceTreeBuilder(root, model) spec = DeviceSpec("bess", INFO, device_id="bess-1") builder.add(spec) - builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM)]) + builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM, format="NORMAL,SHED")]) quiet = len(mock_paho.publish.call_args_list) - builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM)]) + builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM, format="NORMAL,SHED")]) assert len(mock_paho.publish.call_args_list) == quiet @@ -438,7 +438,7 @@ def test_extend_folds_into_the_bookkeeping_remove_uses(root, mock_paho): builder = DeviceTreeBuilder(root, model) spec = DeviceSpec("bess", INFO, device_id="bess-1") builder.add(spec) - builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM)]) + builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM, format="NORMAL,SHED")]) builder.remove(spec) # Both the original and the extended model entries are gone. @@ -453,7 +453,7 @@ def test_extend_refuses_a_device_that_is_not_built(root): spec = DeviceSpec("bess", INFO, device_id=lambda: None) builder.add(spec) # deferred, so no tree to extend with pytest.raises(KeyError, match="not built"): - builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM)]) + builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM, format="NORMAL,SHED")]) # --- Teardown and bookkeeping robustness (GH #73, #75, #76) ------------------ @@ -566,7 +566,7 @@ def test_remove_capabilities_is_the_inverse_of_extend(root, mock_paho): builder = DeviceTreeBuilder(root, model) spec = DeviceSpec("bess", INFO, device_id="bess-1") builder.add(spec) - builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM)]) + builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM, format="NORMAL,SHED")]) device = builder.device_for(spec) assert device.get_node("shed") is not None @@ -588,7 +588,7 @@ def test_remove_capabilities_clears_the_retained_topics(root, mock_paho): builder = DeviceTreeBuilder(root, model) spec = DeviceSpec("bess", INFO, device_id="bess-1") builder.add(spec) - builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM)]) + builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM, format="NORMAL,SHED")]) model.set_value("bess-1", "shed-state", "SHED") before = len(mock_paho.publish.call_args_list) @@ -604,7 +604,7 @@ def test_remove_capabilities_is_idempotent(root, mock_paho): builder = DeviceTreeBuilder(root, model) spec = DeviceSpec("bess", INFO, device_id="bess-1") builder.add(spec) - builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM)]) + builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM, format="NORMAL,SHED")]) builder.remove_capabilities(spec, ["shed"]) quiet = len(mock_paho.publish.call_args_list) @@ -618,7 +618,7 @@ def test_a_capability_can_be_added_removed_and_added_again(root, mock_paho): builder = DeviceTreeBuilder(root, model) spec = DeviceSpec("bess", INFO, device_id="bess-1") builder.add(spec) - shed = [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM)] + shed = [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM, format="NORMAL,SHED")] builder.extend(spec, shed) builder.remove_capabilities(spec, ["shed"]) @@ -637,7 +637,7 @@ def test_remove_after_remove_capabilities_stays_consistent(root, mock_paho): builder = DeviceTreeBuilder(root, model) spec = DeviceSpec("bess", INFO, device_id="bess-1") builder.add(spec) - builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM)]) + builder.extend(spec, [PropertySpec("shed", "shed-state", PropertyDatatype.ENUM, format="NORMAL,SHED")]) builder.remove_capabilities(spec, ["shed"]) builder.remove(spec) diff --git a/tests/test_homie_compliance.py b/tests/test_homie_compliance.py index 03c55e5..60df0fa 100644 --- a/tests/test_homie_compliance.py +++ b/tests/test_homie_compliance.py @@ -25,10 +25,11 @@ Node, Property, PropertyDatatype, - _has_iso_week_53, _exact_number, + _has_iso_week_53, _numeric_format, _parse_set_payload, + _warn_invalid_once, ) BASE = f"{EBUS_HOMIE_DOMAIN}/{EBUS_HOMIE_VERSION_MAJOR}" @@ -426,6 +427,21 @@ def _invalid_input_warnings(caplog): return [r for r in caplog.records if "next minor release" in r.getMessage()] +class TestWarnInvalidOnce: + """The warn-one-release step of the #91 policy, for checks not yet raising.""" + + def test_once_per_owner_and_problem_with_the_hint(self, caplog): + a, b = Device(id="a"), Device(id="b") + with caplog.at_level(logging.WARNING, logger="homie"): + _warn_invalid_once(a, "p1", "reason=p1,id=a") + _warn_invalid_once(a, "p1", "reason=p1,id=a") + _warn_invalid_once(a, "p2", "reason=p2,id=a") + _warn_invalid_once(b, "p1", "reason=p1,id=b") + messages = [r.getMessage() for r in _invalid_input_warnings(caplog)] + assert [m.split(",hint=")[0] for m in messages] == ["reason=p1,id=a", "reason=p2,id=a", "reason=p1,id=b"] + assert all(m.endswith("this will raise in the next minor release") for m in messages) + + class TestDescriptionVersion: """:215: a new version whenever the document changes, and only then.""" @@ -505,72 +521,91 @@ def test_set_types_are_kept(self): assert device.description()["type"] == "t" assert device.description()["nodes"]["n"]["type"] == "nt" - def test_missing_datatype_warns_and_is_omitted(self, caplog): - """:340: `datatype` is required.""" - with caplog.at_level(logging.WARNING, logger="homie"): - prop = Property(id="p") - assert "datatype" not in prop.description() - assert len(_invalid_input_warnings(caplog)) == 1 - - def test_null_retained_warns_and_is_published_as_false(self, caplog): - """:343: `retained` is a non-null boolean; None always published non-retained.""" - with caplog.at_level(logging.WARNING, logger="homie"): - prop = Property(id="p", datatype=PropertyDatatype.FLOAT, retained=None) - assert prop.description()["retained"] is False - assert prop.retained() is False - assert len(_invalid_input_warnings(caplog)) == 1 - def test_json_format_dict_is_published_as_a_string(self): """:395: the JSONschema is a string, not a nested object.""" schema = {"type": "object"} prop = Property(id="j", datatype=PropertyDatatype.JSON, format=schema) assert prop.description()["format"] == json.dumps(schema) - def test_enum_and_color_without_format_warn(self, caplog): - """:392-393: `enum` and `color` require a format.""" - with caplog.at_level(logging.WARNING, logger="homie"): - Property(id="e", datatype=PropertyDatatype.ENUM) - Property(id="c", datatype=PropertyDatatype.COLOR) - assert len(_invalid_input_warnings(caplog)) == 2 + def test_extras_cannot_add_root_or_parent_to_a_root(self): + """:220: `root` MUST be omitted on the root device.""" + with pytest.raises(ValueError, match=r"reason=deviceDescriptionExtrasCoreFieldDropped,id=r,field=parent,root"): + Device(id="r", description_extras={"root": "x", "parent": "y", "imported-from": "z"}) - def test_enum_format_with_empty_or_duplicate_values_warns(self, caplog): - """:392: at least one value, none empty, no duplicates.""" - with caplog.at_level(logging.WARNING, logger="homie"): - Property(id="e1", datatype=PropertyDatatype.ENUM, format="a,,b") - Property(id="e2", datatype=PropertyDatatype.ENUM, format="a,b,a") - Property(id="ok", datatype=PropertyDatatype.ENUM, format="a,b") - reasons = [r.getMessage() for r in _invalid_input_warnings(caplog)] - assert len(reasons) == 2 - assert "propertyID=e1" in reasons[0] and "propertyID=e2" in reasons[1] - - def test_the_warning_is_once_per_object(self, caplog): - with caplog.at_level(logging.WARNING, logger="homie"): - prop = Property(id="e", datatype=PropertyDatatype.ENUM) - prop.set_format(None) - prop.set_format("") - assert len(_invalid_input_warnings(caplog)) == 1 + @pytest.mark.parametrize("field", ["homie", "version", "nodes", "name", "type", "children", "extensions"]) + def test_extras_cannot_set_any_core_field(self, field): + with pytest.raises(ValueError, match=rf"reason=deviceDescriptionExtrasCoreFieldDropped,id=r,field={field}\b"): + Device(id="r", description_extras={field: "x"}) - def test_set_format_checks_the_new_format(self, caplog): - prop = Property(id="e", datatype=PropertyDatatype.ENUM, format="a,b") - with caplog.at_level(logging.WARNING, logger="homie"): - prop.set_format("a,a") - assert len(_invalid_input_warnings(caplog)) == 1 + def test_a_child_with_core_extras_is_not_attached_and_publishes_nothing(self): + root, client = _make_root() + client.publish.reset_mock() + with pytest.raises(ValueError, match="reason=deviceDescriptionExtrasCoreFieldDropped,id=child"): + Device(id="child", parent=root, description_extras={"root": "elsewhere"}) + assert root.children() == [] + assert client.publish.call_args_list == [] - def test_extras_cannot_add_root_or_parent_to_a_root(self, caplog): - """:220: `root` MUST be omitted on the root device.""" - with caplog.at_level(logging.WARNING, logger="homie"): - device = Device(id="r", description_extras={"root": "x", "parent": "y", "imported-from": "z"}) - description = device.description() - assert "root" not in description and "parent" not in description - assert description["imported-from"] == "z" - assert len(_invalid_input_warnings(caplog)) == 2 + def test_extension_extras_are_kept(self): + device = Device(id="r", description_extras={"imported-from": "z"}) + assert device.description()["imported-from"] == "z" - def test_extras_cannot_override_core_fields(self): - device = Device(id="r", description_extras={"version": 1, "type": "x", "homie": "4.0"}) - description = device.description() - assert description["homie"] == "5.0" - assert description["version"] != 1 - assert "type" not in description + +# Invalid property $description input (#91): (kwargs, reason). Each raises ValueError. +_INVALID_PROPERTY_INPUT = [ + ({"datatype": PropertyDatatype.FLOAT, "retained": None}, "propertyRetainedNull"), # :343 + ({}, "propertyDatatypeMissing"), # :340 + ({"datatype": "decimal"}, "propertyDatatypeUnknown"), + ({"datatype": PropertyDatatype.ENUM}, "propertyFormatMissing"), # :392 + ({"datatype": PropertyDatatype.COLOR}, "propertyFormatMissing"), # :393 + ({"datatype": PropertyDatatype.ENUM, "format": "a,,b"}, "propertyEnumFormatEmptyValue"), # :392 + ({"datatype": PropertyDatatype.ENUM, "format": "a,b,a"}, "propertyEnumFormatDuplicate"), # :392 + ({"datatype": PropertyDatatype.COLOR, "format": "rgb,cmyk"}, "propertyColorFormatInvalid"), # :393 +] +_INVALID_IDS = [f"{reason}-{kwargs.get('datatype')}" for kwargs, reason in _INVALID_PROPERTY_INPUT] + + +class TestInvalidPropertyInputRaises: + """Invalid producer input raises at every entry point, before anything is published (#91).""" + + @pytest.mark.parametrize(("kwargs", "reason"), _INVALID_PROPERTY_INPUT, ids=_INVALID_IDS) + def test_constructor(self, kwargs, reason): + with pytest.raises(ValueError, match=rf"reason={reason},propertyID=p\b"): + Property(id="p", **kwargs) + + @pytest.mark.parametrize(("kwargs", "reason"), _INVALID_PROPERTY_INPUT, ids=_INVALID_IDS) + def test_from_dict(self, kwargs, reason): + with pytest.raises(ValueError, match=rf"reason={reason},propertyID=p\b"): + Property(from_dict={"id": "p", **kwargs}) + + @pytest.mark.parametrize(("kwargs", "reason"), _INVALID_PROPERTY_INPUT, ids=_INVALID_IDS) + def test_add_property_from_dict_publishes_and_adds_nothing(self, kwargs, reason): + root, client = _make_root() + node = root.new_node("n") + root.add_node(node) + client.publish.reset_mock() + + with pytest.raises(ValueError, match=rf"reason={reason},propertyID=p\b"): + node.add_property_from_dict({"id": "p", **kwargs}) + + assert node.get_property("p") is None + assert client.publish.call_args_list == [] + assert root.state() == DeviceState.READY + + @pytest.mark.parametrize( + ("fmt", "reason"), + [(None, "propertyFormatMissing"), ("", "propertyFormatMissing"), ("a,a", "propertyEnumFormatDuplicate")], + ) + def test_set_format_raises_and_keeps_the_old_format(self, fmt, reason): + prop = Property(id="e", datatype=PropertyDatatype.ENUM, format="a,b") + with pytest.raises(ValueError, match=rf"reason={reason},propertyID=e\b"): + prop.set_format(fmt) + assert prop.format() == "a,b" + + def test_valid_input_still_constructs(self): + Property(id="e", datatype=PropertyDatatype.ENUM, format="a,b") + Property(id="c", datatype=PropertyDatatype.COLOR, format="rgb,hsv,xyz") + Property(id="j", datatype=PropertyDatatype.JSON) + Property(id="f", datatype="float", retained=False) class TestNewValuesPrecedeReady: @@ -918,9 +953,25 @@ def test_bare_alert_and_bad_input_publish_nothing(self): root.publish("$alert", "no id") assert root.publish_alert("a/b", "x") is False assert root.publish_alert("", "x") is False - assert root.publish_alert("battery", "") is False assert client.publish.call_args_list == [] + @pytest.mark.parametrize( + ("alert_id", "message", "reason"), + [ + ("Battery_Low", "low", "devicePublishAlertIdFormat"), + ("battery", "", "devicePublishAlertEmptyMessage"), + ("battery", None, "devicePublishAlertEmptyMessage"), + ], + ) + def test_invalid_alert_raises_and_records_nothing(self, alert_id, message, reason): + """:517 (alert ids follow the ID format); an empty payload deletes the topic.""" + root, client = _make_root() + client.publish.reset_mock() + with pytest.raises(ValueError, match=rf"reason={reason},id=root,alertId={alert_id}"): + root.publish_alert(alert_id, message) + assert client.publish.call_args_list == [] + assert root.alerts() == {} + # ── D. /set on the device ──────────────────────────────────────────────── diff --git a/tests/test_homie_device.py b/tests/test_homie_device.py index 91cda7f..0b75bf0 100644 --- a/tests/test_homie_device.py +++ b/tests/test_homie_device.py @@ -195,7 +195,7 @@ def test_basic_init(self): assert p.retained() is True def test_name_defaults_to_id(self): - p = Property(id="temp") + p = Property(id="temp", datatype=PropertyDatatype.FLOAT) assert p.name() == "temp" def test_from_dict(self): @@ -225,16 +225,16 @@ def test_set_format_updates_format_and_description(self): def test_set_callback_ignored_when_not_settable(self): cb = MagicMock() - p = Property(id="temp", settable=False, set_callback=cb) + p = Property(id="temp", datatype=PropertyDatatype.FLOAT, settable=False, set_callback=cb) assert p.get_set_callback() is None def test_set_callback_stored_when_settable(self): cb = MagicMock() - p = Property(id="temp", settable=True, set_callback=cb) + p = Property(id="temp", datatype=PropertyDatatype.FLOAT, settable=True, set_callback=cb) assert p.get_set_callback() is cb def test_set_set_callback(self): - p = Property(id="temp", settable=True) + p = Property(id="temp", datatype=PropertyDatatype.FLOAT, settable=True) cb = MagicMock() p.set_set_callback(cb) assert p.get_set_callback() is cb @@ -245,19 +245,19 @@ def test_round_to(self): assert p.round() == 1 def test_no_round(self): - p = Property(id="temp", value=72.456) + p = Property(id="temp", value=72.456, datatype=PropertyDatatype.FLOAT) assert p.value() == 72.456 def test_ever_published_initially_false(self): - p = Property(id="temp", value=72) + p = Property(id="temp", value=72, datatype=PropertyDatatype.INTEGER) assert p.was_ever_published() is False def test_skip_initial_publish_from_dict(self): - p = Property(from_dict={"id": "temp", "skip_initial_publish": True}) + p = Property(from_dict={"id": "temp", "datatype": PropertyDatatype.FLOAT, "skip_initial_publish": True}) assert p._skip_initial_publish is True def test_supports_target(self): - p = Property(id="temp", supports_target=True) + p = Property(id="temp", datatype=PropertyDatatype.FLOAT, supports_target=True) assert p.supports_target() is True def test_is_json_datatype(self): @@ -274,7 +274,7 @@ def test_set_settable_from_false_to_true(self): assert prop.settable() is True def test_set_settable_noop_same_value(self): - p = Property(id="temp", settable=False) + p = Property(id="temp", datatype=PropertyDatatype.FLOAT, settable=False) p.set_settable(False) assert p.settable() is False @@ -341,7 +341,7 @@ def test_coerced_value_enum(self): class Color(Enum): RED = "red" - p = Property(id="color", value=Color.RED, datatype=PropertyDatatype.ENUM) + p = Property(id="color", value=Color.RED, datatype=PropertyDatatype.ENUM, format="red") assert p.coerced_value() == "red" def test_coerced_value_json_dict(self): @@ -576,16 +576,12 @@ def test_a_non_retained_property_publishes_every_identical_value(self): assert mock_client.publish.call_count == 3 - def test_retained_none_is_never_deduped(self): - # retained is Optional[bool] and reachable as None; the publish call already - # treats that as non-retained, so the gate must too (truthiness, not `is True`). + def test_retained_none_is_refused(self): + # retained is a non-null boolean (convention.md:343), so None never reaches the gate. mock_client = _mock_mqtt_client() - prop = _make_wired_property(mock_client, retained=None) - - prop.set_value(99.0) - prop.set_value(99.0) - - assert mock_client.publish.call_count == 2 + with pytest.raises(ValueError, match="reason=propertyRetainedNull"): + _make_wired_property(mock_client, retained=None) + mock_client.publish.assert_not_called() def test_clear_then_the_same_value_republishes(self): # publish x -> retract -> set x again. Without a memo reset in clear_value() @@ -1010,7 +1006,7 @@ def test_get_mqtt_client_no_device(self): def test_get_property(self): n = Node(id="core") - p = Property(id="temp", value=72) + p = Property(id="temp", value=72, datatype=PropertyDatatype.INTEGER) n._properties["temp"] = p assert n.get_property("temp") is p @@ -2395,11 +2391,9 @@ def test_description_extras_merged(self, mock_paho): d, _ = _make_device(mock_paho, description_extras={"imported-from": "ha"}) assert d.description()["imported-from"] == "ha" - def test_description_extras_never_clobber_core_fields(self, mock_paho): - d, _ = _make_device(mock_paho, description_extras={"name": "HACKED", "nodes": {"x": {}}}) - desc = d.description() - assert desc["name"] != "HACKED" # core name wins over an extra of the same key - assert desc["nodes"] == {} # core nodes win + def test_description_extras_cannot_set_core_fields(self, mock_paho): + with pytest.raises(ValueError, match="reason=deviceDescriptionExtrasCoreFieldDropped.*field=name,nodes"): + _make_device(mock_paho, description_extras={"name": "HACKED", "nodes": {"x": {}}}) class TestDeviceStop: @@ -2814,7 +2808,7 @@ class TestInboundAsyncLoop: def test_async_loop_default_is_none(self): # Was `Optional[...] = False` (a bool against the loop annotation); now None. - assert Property(id="mode").async_loop is None + assert Property(id="mode", datatype=PropertyDatatype.STRING).async_loop is None def test_device_async_loop_propagates_via_add_node(self): loop = MagicMock() @@ -2851,7 +2845,7 @@ async def cb(payload): return None loop = MagicMock() - prop = Property(id="mode", settable=True, set_callback=cb) + prop = Property(id="mode", datatype=PropertyDatatype.STRING, settable=True, set_callback=cb) prop.async_loop = loop with patch("asyncio.run_coroutine_threadsafe") as rct, patch("asyncio.ensure_future") as ef: prop._settable_callback("ebus/5/dev/node/mode/set", b"LOAD_UP") @@ -2862,7 +2856,9 @@ async def cb(payload): def test_sync_dispatch_when_no_loop(self): seen = [] - prop = Property(id="mode", settable=True, set_callback=lambda v: seen.append(v)) + prop = Property( + id="mode", datatype=PropertyDatatype.STRING, settable=True, set_callback=lambda v: seen.append(v) + ) assert prop.async_loop is None with patch("asyncio.run_coroutine_threadsafe") as rct: prop._settable_callback("ebus/5/dev/node/mode/set", b"LOAD_UP") @@ -2874,7 +2870,9 @@ def test_sync_callback_stays_inline_under_device_loop(self): dispatch branches on the callback's return, not on the loop's presence (#15).""" loop = MagicMock() seen = [] - prop = Property(id="mode", settable=True, set_callback=lambda v: seen.append(v)) + prop = Property( + id="mode", datatype=PropertyDatatype.STRING, settable=True, set_callback=lambda v: seen.append(v) + ) prop.async_loop = loop # a device-level loop is propagated to every property with patch("asyncio.run_coroutine_threadsafe") as rct: prop._settable_callback("ebus/5/dev/node/mode/set", b"ON") @@ -2899,7 +2897,7 @@ def test_device_loop_overrides_per_property_loop(self): def test_async_set_callback_exception_is_surfaced(self): """A raising async /set handler is logged, not swallowed by the discarded Future.""" - prop = Property(id="mode") + prop = Property(id="mode", datatype=PropertyDatatype.STRING) future = MagicMock() future.cancelled.return_value = False future.exception.return_value = ValueError("bad setpoint")