Refactor some mqtt tests not the just use schema validation (#94330)

Remove help_test_validate_platform_config
This commit is contained in:
Jan Bouwhuis 2023-06-09 12:30:26 +02:00 committed by GitHub
parent 5fb41777fd
commit c984604a6c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 47 additions and 72 deletions

View file

@ -64,7 +64,6 @@ from .test_common import (
help_test_unload_config_entry_with_platform, help_test_unload_config_entry_with_platform,
help_test_update_with_json_attrs_bad_json, help_test_update_with_json_attrs_bad_json,
help_test_update_with_json_attrs_not_dict, help_test_update_with_json_attrs_not_dict,
help_test_validate_platform_config,
) )
from tests.common import async_fire_mqtt_message from tests.common import async_fire_mqtt_message
@ -131,7 +130,7 @@ def alarm_control_panel_platform_only():
@pytest.mark.parametrize( @pytest.mark.parametrize(
("config", "valid"), ("hass_config", "valid"),
[ [
( (
{ {
@ -170,10 +169,14 @@ def alarm_control_panel_platform_only():
], ],
) )
async def test_fail_setup_without_state_or_command_topic( async def test_fail_setup_without_state_or_command_topic(
hass: HomeAssistant, config, valid hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator, valid
) -> None: ) -> None:
"""Test for failing setup with no state or command topic.""" """Test for failing setup with no state or command topic."""
assert help_test_validate_platform_config(hass, config) == valid if valid:
await mqtt_mock_entry()
return
with pytest.raises(AssertionError):
await mqtt_mock_entry()
@pytest.mark.parametrize("hass_config", [DEFAULT_CONFIG]) @pytest.mark.parametrize("hass_config", [DEFAULT_CONFIG])

View file

@ -9,17 +9,14 @@ from typing import Any
from unittest.mock import ANY, MagicMock, patch from unittest.mock import ANY, MagicMock, patch
import pytest import pytest
import voluptuous as vol
import yaml import yaml
from homeassistant import config as module_hass_config from homeassistant import config as module_hass_config
from homeassistant.components import mqtt from homeassistant.components import mqtt
from homeassistant.components.mqtt import debug_info from homeassistant.components.mqtt import debug_info
from homeassistant.components.mqtt.config_integration import PLATFORM_CONFIG_SCHEMA_BASE
from homeassistant.components.mqtt.const import MQTT_DISCONNECTED from homeassistant.components.mqtt.const import MQTT_DISCONNECTED
from homeassistant.components.mqtt.mixins import MQTT_ATTRIBUTES_BLOCKED from homeassistant.components.mqtt.mixins import MQTT_ATTRIBUTES_BLOCKED
from homeassistant.components.mqtt.models import PublishPayloadType from homeassistant.components.mqtt.models import PublishPayloadType
from homeassistant.config import async_log_exception
from homeassistant.config_entries import ConfigEntryState from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ( from homeassistant.const import (
ATTR_ASSUMED_STATE, ATTR_ASSUMED_STATE,
@ -70,8 +67,6 @@ _MqttMessageType = list[tuple[str, str]]
_AttributesType = list[tuple[str, Any]] _AttributesType = list[tuple[str, Any]]
_StateDataType = list[tuple[_MqttMessageType, str | None, _AttributesType | None]] _StateDataType = list[tuple[_MqttMessageType, str | None, _AttributesType | None]]
MQTT_YAML_SCHEMA = vol.Schema({mqtt.DOMAIN: PLATFORM_CONFIG_SCHEMA_BASE})
def help_all_subscribe_calls(mqtt_client_mock: MqttMockPahoClient) -> list[Any]: def help_all_subscribe_calls(mqtt_client_mock: MqttMockPahoClient) -> list[Any]:
"""Test of a call.""" """Test of a call."""
@ -82,20 +77,6 @@ def help_all_subscribe_calls(mqtt_client_mock: MqttMockPahoClient) -> list[Any]:
return all_calls return all_calls
def help_test_validate_platform_config(
hass: HomeAssistant, config: ConfigType
) -> ConfigType | None:
"""Test the schema validation."""
try:
# validate the schema
MQTT_YAML_SCHEMA(config)
return True
except vol.Error as exc:
# log schema exceptions
async_log_exception(exc, mqtt.DOMAIN, config, hass)
return False
async def help_setup_component( async def help_setup_component(
hass: HomeAssistant, hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator | None, mqtt_mock_entry: MqttMockHAClientGenerator | None,
@ -428,10 +409,14 @@ async def help_test_default_availability_list_single(
{"topic": "availability-topic1"}, {"topic": "availability-topic1"},
] ]
config[mqtt.DOMAIN][domain]["availability_topic"] = "availability-topic" config[mqtt.DOMAIN][domain]["availability_topic"] = "availability-topic"
help_test_validate_platform_config(hass, config)
entry = MockConfigEntry(domain=mqtt.DOMAIN, data={mqtt.CONF_BROKER: "test-broker"})
entry.add_to_hass(hass)
with patch("homeassistant.config.load_yaml_config_file", return_value=config):
await entry.async_setup(hass)
assert ( assert (
"Invalid config for [mqtt]: two or more values in the same group of exclusion 'availability'" "two or more values in the same group of exclusion 'availability'"
in caplog.text in caplog.text
) )

View file

@ -97,10 +97,7 @@ async def test_fail_setup_if_no_command_topic(
"""Test if command fails with command topic.""" """Test if command fails with command topic."""
with pytest.raises(AssertionError): with pytest.raises(AssertionError):
await mqtt_mock_entry() await mqtt_mock_entry()
assert ( assert "Invalid config for [mqtt]: required key not provided" in caplog.text
"Invalid config for [mqtt]: required key not provided @ data['mqtt']['fan'][0]['command_topic']"
in caplog.text
)
@pytest.mark.parametrize( @pytest.mark.parametrize(

View file

@ -139,10 +139,7 @@ async def test_fail_setup_if_no_command_topic(
"""Test if command fails with command topic.""" """Test if command fails with command topic."""
with pytest.raises(AssertionError): with pytest.raises(AssertionError):
await mqtt_mock_entry() await mqtt_mock_entry()
assert ( assert "Invalid config for [mqtt]: required key not provided" in caplog.text
"Invalid config for [mqtt]: required key not provided @ data['mqtt']['humidifier'][0]['command_topic']. Got None"
in caplog.text
)
@pytest.mark.parametrize( @pytest.mark.parametrize(

View file

@ -37,7 +37,7 @@ from homeassistant.helpers.typing import ConfigType
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
from .test_common import help_all_subscribe_calls, help_test_validate_platform_config from .test_common import help_all_subscribe_calls
from tests.common import ( from tests.common import (
MockConfigEntry, MockConfigEntry,
@ -2066,50 +2066,52 @@ async def test_handle_message_callback(
assert callbacks[0].payload == "test-payload" assert callbacks[0].payload == "test-payload"
@patch("homeassistant.components.mqtt.PLATFORMS", []) @pytest.mark.parametrize(
async def test_setup_manual_mqtt_with_platform_key( "hass_config",
hass: HomeAssistant, caplog: pytest.LogCaptureFixture [
) -> None: {
"""Test set up a manual MQTT item with a platform key.""" mqtt.DOMAIN: {
config = { "light": {
mqtt.DOMAIN: { "platform": "mqtt",
"light": { "name": "test",
"platform": "mqtt", "command_topic": "test-topic",
"name": "test", }
"command_topic": "test-topic",
} }
} }
} ],
help_test_validate_platform_config(hass, config) )
@patch("homeassistant.components.mqtt.PLATFORMS", [])
async def test_setup_manual_mqtt_with_platform_key(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test set up a manual MQTT item with a platform key."""
with pytest.raises(AssertionError):
await mqtt_mock_entry()
assert ( assert (
"Invalid config for [mqtt]: [platform] is an invalid option for [mqtt]" "Invalid config for [mqtt]: [platform] is an invalid option for [mqtt]"
in caplog.text in caplog.text
) )
@pytest.mark.parametrize("hass_config", [{mqtt.DOMAIN: {"light": {"name": "test"}}}])
@pytest.mark.xfail(reason="Invalid config for [mqtt]: required key not provided")
@patch("homeassistant.components.mqtt.PLATFORMS", []) @patch("homeassistant.components.mqtt.PLATFORMS", [])
async def test_setup_manual_mqtt_with_invalid_config( async def test_setup_manual_mqtt_with_invalid_config(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
caplog: pytest.LogCaptureFixture,
) -> None: ) -> None:
"""Test set up a manual MQTT item with an invalid config.""" """Test set up a manual MQTT item with an invalid config."""
config = {mqtt.DOMAIN: {"light": {"name": "test"}}} with pytest.raises(AssertionError):
help_test_validate_platform_config(hass, config) await mqtt_mock_entry()
assert ( assert (
"Invalid config for [mqtt]: required key not provided @ data['mqtt']['light'][0]['command_topic']." "Invalid config for [mqtt]: required key not provided @ data['mqtt']['light'][0]['command_topic']."
" Got None. (See ?, line ?)" in caplog.text " Got None. (See ?, line ?)" in caplog.text
) )
@patch("homeassistant.components.mqtt.PLATFORMS", [])
async def test_setup_manual_mqtt_empty_platform(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test set up a manual MQTT platform without items."""
config: ConfigType = {mqtt.DOMAIN: {"light": []}}
help_test_validate_platform_config(hass, config)
assert "voluptuous.error.MultipleInvalid" not in caplog.text
@patch("homeassistant.components.mqtt.PLATFORMS", []) @patch("homeassistant.components.mqtt.PLATFORMS", [])
@pytest.mark.parametrize( @pytest.mark.parametrize(
("mqtt_config_entry_data", "protocol"), ("mqtt_config_entry_data", "protocol"),

View file

@ -253,10 +253,7 @@ async def test_fail_setup_if_no_command_topic(
"""Test if command fails with command topic.""" """Test if command fails with command topic."""
with pytest.raises(AssertionError): with pytest.raises(AssertionError):
await mqtt_mock_entry() await mqtt_mock_entry()
assert ( assert "Invalid config for [mqtt]: required key not provided" in caplog.text
"Invalid config for [mqtt]: required key not provided @ data['mqtt']['light'][0]['command_topic']. Got None."
in caplog.text
)
@pytest.mark.parametrize( @pytest.mark.parametrize(

View file

@ -198,10 +198,7 @@ async def test_fail_setup_if_no_command_topic(
"""Test if setup fails with no command topic.""" """Test if setup fails with no command topic."""
with pytest.raises(AssertionError): with pytest.raises(AssertionError):
await mqtt_mock_entry() await mqtt_mock_entry()
assert ( assert "Invalid config for [mqtt]: required key not provided" in caplog.text
"Invalid config for [mqtt]: required key not provided @ data['mqtt']['light'][0]['command_topic']. Got None."
in caplog.text
)
@pytest.mark.parametrize( @pytest.mark.parametrize(

View file

@ -692,10 +692,7 @@ async def test_default_availability_list_single(
) -> None: ) -> None:
"""Test availability list and availability_topic are mutually exclusive.""" """Test availability list and availability_topic are mutually exclusive."""
await help_test_default_availability_list_single( await help_test_default_availability_list_single(
hass, hass, caplog, sensor.DOMAIN, DEFAULT_CONFIG
caplog,
sensor.DOMAIN,
DEFAULT_CONFIG,
) )