Skip to content

Commit

Permalink
Fix mqtt text text min max config params can not be equal (#107738)
Browse files Browse the repository at this point in the history
Fix mqtt text text min max kan not be equal
  • Loading branch information
jbouwh committed Jan 11, 2024
1 parent b83f5b5 commit e045759
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
4 changes: 2 additions & 2 deletions homeassistant/components/mqtt/text.py
Expand Up @@ -70,8 +70,8 @@

def valid_text_size_configuration(config: ConfigType) -> ConfigType:
"""Validate that the text length configuration is valid, throws if it isn't."""
if config[CONF_MIN] >= config[CONF_MAX]:
raise vol.Invalid("text length min must be >= max")
if config[CONF_MIN] > config[CONF_MAX]:
raise vol.Invalid("text length min must be <= max")
if config[CONF_MAX] > MAX_LENGTH_STATE_STATE:
raise vol.Invalid(f"max text length must be <= {MAX_LENGTH_STATE_STATE}")

Expand Down
59 changes: 58 additions & 1 deletion tests/components/mqtt/test_text.py
Expand Up @@ -115,6 +115,63 @@ async def test_controlling_state_via_topic(
assert state.state == ""


@pytest.mark.parametrize(
"hass_config",
[
{
mqtt.DOMAIN: {
text.DOMAIN: {
"name": "test",
"state_topic": "state-topic",
"command_topic": "command-topic",
"min": 5,
"max": 5,
}
}
}
],
)
async def test_forced_text_length(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test a text entity that only allows a fixed length."""
await mqtt_mock_entry()

state = hass.states.get("text.test")
assert state.state == STATE_UNKNOWN
assert not state.attributes.get(ATTR_ASSUMED_STATE)

async_fire_mqtt_message(hass, "state-topic", "12345")
state = hass.states.get("text.test")
assert state.state == "12345"

caplog.clear()
# Text too long
async_fire_mqtt_message(hass, "state-topic", "123456")
state = hass.states.get("text.test")
assert state.state == "12345"
assert (
"ValueError: Entity text.test provides state 123456 "
"which is too long (maximum length 5)" in caplog.text
)

caplog.clear()
# Text too short
async_fire_mqtt_message(hass, "state-topic", "1")
state = hass.states.get("text.test")
assert state.state == "12345"
assert (
"ValueError: Entity text.test provides state 1 "
"which is too short (minimum length 5)" in caplog.text
)
# Valid update
async_fire_mqtt_message(hass, "state-topic", "54321")
state = hass.states.get("text.test")
assert state.state == "54321"


@pytest.mark.parametrize(
"hass_config",
[
Expand Down Expand Up @@ -211,7 +268,7 @@ async def test_attribute_validation_max_greater_then_min(
) -> None:
"""Test the validation of min and max configuration attributes."""
assert await mqtt_mock_entry()
assert "text length min must be >= max" in caplog.text
assert "text length min must be <= max" in caplog.text


@pytest.mark.parametrize(
Expand Down

0 comments on commit e045759

Please sign in to comment.