diff --git a/tests/conftest.py b/tests/conftest.py index 130ce74dd5b..a07e659378a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -99,6 +99,7 @@ from homeassistant.helpers import ( translation as translation_helper, ) from homeassistant.helpers.dispatcher import async_dispatcher_send +from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo from homeassistant.helpers.translation import _TranslationsCacheData from homeassistant.helpers.typing import ConfigType from homeassistant.setup import async_setup_component @@ -2090,3 +2091,21 @@ def disable_block_async_io() -> Generator[None]: blocking_call.object, blocking_call.function, blocking_call.original_func ) calls.clear() + + +# Ensure that incorrectly formatted mac addresses are rejected during +# DhcpServiceInfo initialisation +_real_dhcp_service_info_init = DhcpServiceInfo.__init__ + + +def _dhcp_service_info_init(self: DhcpServiceInfo, *args: Any, **kwargs: Any) -> None: + """Override __init__ for DhcpServiceInfo. + + Ensure that the macaddress is always in lowercase and without colons to match DHCP service. + """ + _real_dhcp_service_info_init(self, *args, **kwargs) + if self.macaddress != self.macaddress.lower().replace(":", ""): + raise ValueError("macaddress is not correctly formatted") + + +DhcpServiceInfo.__init__ = _dhcp_service_info_init diff --git a/tests/helpers/test_service_info.py b/tests/helpers/test_service_info.py new file mode 100644 index 00000000000..249ceb0e637 --- /dev/null +++ b/tests/helpers/test_service_info.py @@ -0,0 +1,23 @@ +"""Test service_info helpers.""" + +import pytest + +from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo + +# Ensure that incorrectly formatted mac addresses are rejected, even +# on a constant outside of a test +try: + _ = DhcpServiceInfo(ip="", hostname="", macaddress="AA:BB:CC:DD:EE:FF") +except ValueError: + pass +else: + raise RuntimeError( + "DhcpServiceInfo incorrectly formatted mac address was not rejected. " + "Please ensure that the DhcpServiceInfo is correctly patched." + ) + + +def test_invalid_macaddress() -> None: + """Test that DhcpServiceInfo raises ValueError for unformatted macaddress.""" + with pytest.raises(ValueError): + DhcpServiceInfo(ip="", hostname="", macaddress="AA:BB:CC:DD:EE:FF")