init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
"""Tests for command_line component."""
import asyncio
from contextlib import contextmanager
from unittest.mock import MagicMock, patch
@contextmanager
def mock_asyncio_subprocess_run(
response: bytes = b"", returncode: int = 0, exception: Exception | None = None
):
"""Mock create_subprocess_shell."""
class MockProcess(asyncio.subprocess.Process):
@property
def returncode(self):
return returncode
async def communicate(self):
if exception:
raise exception
return response, b""
mock_process = MockProcess(MagicMock(), MagicMock(), MagicMock())
with patch(
"homeassistant.components.command_line.utils.asyncio.create_subprocess_shell",
return_value=mock_process,
) as mock:
yield mock

View File

@@ -0,0 +1,72 @@
"""Fixtures for command_line."""
from typing import Any
import pytest
from homeassistant import setup
from homeassistant.components.command_line.const import DOMAIN
from homeassistant.core import HomeAssistant
@pytest.fixture(name="get_config")
async def get_config_to_integration_load() -> dict[str, Any]:
"""Return default minimal configuration.
To override the config, tests can be marked with:
@pytest.mark.parametrize("get_config", [{...}])
"""
return {
"command_line": [
{
"binary_sensor": {
"name": "Test",
"command": "echo 1",
"payload_on": "1",
"payload_off": "0",
"command_timeout": 15,
}
},
{
"cover": {
"name": "Test",
"command_state": "echo 1",
"command_timeout": 15,
}
},
{
"notify": {
"name": "Test",
"command": "echo 1",
"command_timeout": 15,
}
},
{
"sensor": {
"name": "Test",
"command": "echo 5",
"unit_of_measurement": "in",
"command_timeout": 15,
}
},
{
"switch": {
"name": "Test",
"command_state": "echo 1",
"command_timeout": 15,
}
},
]
}
@pytest.fixture(name="load_yaml_integration")
async def load_int(hass: HomeAssistant, get_config: dict[str, Any]) -> None:
"""Set up the Command Line integration in Home Assistant."""
await setup.async_setup_component(
hass,
DOMAIN,
get_config,
)
await hass.async_block_till_done()

View File

@@ -0,0 +1,7 @@
command_line:
- "binary_sensor":
"name": "Test"
"command": "echo 1"
"payload_on": "1"
"payload_off": "0"
"command_timeout": 15

View File

@@ -0,0 +1,368 @@
"""The tests for the Command line Binary sensor platform."""
from __future__ import annotations
import asyncio
from datetime import timedelta
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant import setup
from homeassistant.components.command_line.binary_sensor import CommandBinarySensor
from homeassistant.components.command_line.const import DOMAIN
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from . import mock_asyncio_subprocess_run
from tests.common import async_fire_time_changed
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"binary_sensor": {
"name": "Test",
"command": "echo 1",
"payload_on": "1",
"payload_off": "0",
"command_timeout": 15,
}
}
]
}
],
)
async def test_setup_integration_yaml(
hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test sensor setup."""
entity_state = hass.states.get("binary_sensor.test")
assert entity_state
assert entity_state.state == STATE_ON
assert entity_state.name == "Test"
async def test_setup_platform_yaml(hass: HomeAssistant) -> None:
"""Test setting up the platform with platform yaml."""
await setup.async_setup_component(
hass,
"binary_sensor",
{
"binary_sensor": {
"platform": "command_line",
"command": "echo 1",
"payload_on": "1",
"payload_off": "0",
}
},
)
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 0
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"binary_sensor": {
"name": "Test",
"command": "echo 10",
"payload_on": "1.0",
"payload_off": "0",
"value_template": "{{ value | multiply(0.1) }}",
"icon": (
'{% if this.attributes.icon=="mdi:icon2" %} mdi:icon1 {% else %} mdi:icon2 {% endif %}'
),
}
}
]
}
],
)
async def test_template(hass: HomeAssistant, load_yaml_integration: None) -> None:
"""Test setting the state with a template."""
entity_state = hass.states.get("binary_sensor.test")
assert entity_state
assert entity_state.state == STATE_ON
assert entity_state.attributes.get("icon") == "mdi:icon2"
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=30))
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("binary_sensor.test")
assert entity_state
assert entity_state.state == STATE_ON
assert entity_state.attributes.get("icon") == "mdi:icon1"
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"binary_sensor": {
"name": "Test",
"command": "echo 0",
"payload_on": "1",
"payload_off": "0",
}
}
]
}
],
)
async def test_sensor_off(hass: HomeAssistant, load_yaml_integration: None) -> None:
"""Test setting the state with a template."""
entity_state = hass.states.get("binary_sensor.test")
assert entity_state
assert entity_state.state == STATE_OFF
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"binary_sensor": {
"unique_id": "unique",
"command": "echo 0",
}
},
{
"binary_sensor": {
"unique_id": "not-so-unique-anymore",
"command": "echo 1",
}
},
{
"binary_sensor": {
"unique_id": "not-so-unique-anymore",
"command": "echo 2",
}
},
]
}
],
)
async def test_unique_id(
hass: HomeAssistant, entity_registry: er.EntityRegistry, load_yaml_integration: None
) -> None:
"""Test unique_id option and if it only creates one binary sensor per id."""
assert len(hass.states.async_all()) == 2
assert len(entity_registry.entities) == 2
assert entity_registry.async_get_entity_id(
"binary_sensor", "command_line", "unique"
)
assert entity_registry.async_get_entity_id(
"binary_sensor", "command_line", "not-so-unique-anymore"
)
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"binary_sensor": {
"command": "exit 33",
}
}
]
}
],
)
async def test_return_code(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, get_config: dict[str, Any]
) -> None:
"""Test setting the state with a template."""
await setup.async_setup_component(
hass,
DOMAIN,
get_config,
)
await hass.async_block_till_done()
assert "return code 33" in caplog.text
async def test_updating_to_often(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test handling updating when command already running."""
wait_till_event = asyncio.Event()
wait_till_event.set()
called = []
class MockCommandBinarySensor(CommandBinarySensor):
"""Mock entity that updates."""
async def _async_update(self) -> None:
"""Update the entity."""
called.append(1)
# Wait till event is set
await wait_till_event.wait()
with patch(
"homeassistant.components.command_line.binary_sensor.CommandBinarySensor",
side_effect=MockCommandBinarySensor,
):
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"binary_sensor": {
"name": "Test",
"command": "echo 1",
"payload_on": "1",
"payload_off": "0",
"scan_interval": 10,
}
}
]
},
)
await hass.async_block_till_done()
assert called
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=15))
wait_till_event.set()
await asyncio.sleep(0)
assert (
"Updating Command Line Binary Sensor Test took longer than the scheduled update interval"
not in caplog.text
)
# Simulate update takes too long
wait_till_event.clear()
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=10))
await asyncio.sleep(0)
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=10))
wait_till_event.set()
await asyncio.sleep(0)
assert (
"Updating Command Line Binary Sensor Test took longer than the scheduled update interval"
in caplog.text
)
async def test_updating_manually(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test handling manual updating using homeassistant udate_entity service."""
await setup.async_setup_component(hass, HA_DOMAIN, {})
called = []
class MockCommandBinarySensor(CommandBinarySensor):
"""Mock entity that updates."""
async def _async_update(self) -> None:
"""Update."""
called.append(1)
with patch(
"homeassistant.components.command_line.binary_sensor.CommandBinarySensor",
side_effect=MockCommandBinarySensor,
):
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"binary_sensor": {
"name": "Test",
"command": "echo 1",
"payload_on": "1",
"payload_off": "0",
"scan_interval": 10,
}
}
]
},
)
await hass.async_block_till_done()
assert called
called.clear()
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: ["binary_sensor.test"]},
blocking=True,
)
await hass.async_block_till_done()
assert called
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"binary_sensor": {
"name": "Test",
"command": "echo 10",
"payload_on": "1.0",
"payload_off": "0",
"value_template": "{{ value | multiply(0.1) }}",
"availability": '{{ states("sensor.input1")=="on" }}',
}
}
]
}
],
)
async def test_availability(
hass: HomeAssistant,
load_yaml_integration: None,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test availability."""
hass.states.async_set("sensor.input1", "on")
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("binary_sensor.test")
assert entity_state
assert entity_state.state == STATE_ON
hass.states.async_set("sensor.input1", "off")
await hass.async_block_till_done()
with mock_asyncio_subprocess_run(b"0"):
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("binary_sensor.test")
assert entity_state
assert entity_state.state == STATE_UNAVAILABLE

View File

@@ -0,0 +1,457 @@
"""The tests the cover command line platform."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import os
import tempfile
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant import setup
from homeassistant.components.command_line import DOMAIN
from homeassistant.components.command_line.cover import CommandCover
from homeassistant.components.cover import (
DOMAIN as COVER_DOMAIN,
SCAN_INTERVAL,
CoverState,
)
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_CLOSE_COVER,
SERVICE_OPEN_COVER,
SERVICE_STOP_COVER,
STATE_UNAVAILABLE,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
import homeassistant.util.dt as dt_util
from . import mock_asyncio_subprocess_run
from tests.common import async_fire_time_changed
async def test_setup_platform_yaml(hass: HomeAssistant) -> None:
"""Test setting up the platform with platform yaml."""
await setup.async_setup_component(
hass,
"cover",
{
"cover": {
"platform": "command_line",
"command": "echo 1",
"payload_on": "1",
"payload_off": "0",
}
},
)
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 0
async def test_no_poll_when_cover_has_no_command_state(hass: HomeAssistant) -> None:
"""Test that the cover does not polls when there's no state command."""
with mock_asyncio_subprocess_run(b"50\n") as mock_subprocess_run:
assert await setup.async_setup_component(
hass,
COVER_DOMAIN,
{
COVER_DOMAIN: [
{"platform": "command_line", "covers": {"test": {}}},
]
},
)
async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL)
await hass.async_block_till_done()
assert not mock_subprocess_run.called
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"cover": {
"command_state": "echo state",
"name": "Test",
},
}
]
}
],
)
async def test_poll_when_cover_has_command_state(
hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test that the cover polls when there's a state command."""
with mock_asyncio_subprocess_run(b"50\n") as mock_subprocess_run:
async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL)
await hass.async_block_till_done()
mock_subprocess_run.assert_called_once_with(
"echo state",
close_fds=False,
stdout=-1,
)
async def test_state_value(hass: HomeAssistant) -> None:
"""Test with state value."""
with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "cover_status")
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"cover": {
"command_state": f"cat {path}",
"command_open": f"echo 1 > {path}",
"command_close": f"echo 1 > {path}",
"command_stop": f"echo 0 > {path}",
"value_template": "{{ value }}",
"name": "Test",
}
}
]
},
)
await hass.async_block_till_done()
entity_state = hass.states.get("cover.test")
assert entity_state
assert entity_state.state == "unknown"
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
entity_state = hass.states.get("cover.test")
assert entity_state
assert entity_state.state == "open"
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
entity_state = hass.states.get("cover.test")
assert entity_state
assert entity_state.state == "open"
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_STOP_COVER,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
entity_state = hass.states.get("cover.test")
assert entity_state
assert entity_state.state == "closed"
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"cover": {
"command_open": "exit 1",
"name": "Test",
}
}
]
}
],
)
async def test_move_cover_failure(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test command failure."""
await hass.services.async_call(
COVER_DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: "cover.test"}, blocking=True
)
assert "Command failed" in caplog.text
assert "return code 1" in caplog.text
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"cover": {
"command_open": "echo open",
"command_close": "echo close",
"command_stop": "echo stop",
"unique_id": "unique",
"name": "Test",
}
},
{
"cover": {
"command_open": "echo open",
"command_close": "echo close",
"command_stop": "echo stop",
"unique_id": "not-so-unique-anymore",
"name": "Test2",
}
},
{
"cover": {
"command_open": "echo open",
"command_close": "echo close",
"command_stop": "echo stop",
"unique_id": "not-so-unique-anymore",
"name": "Test3",
}
},
]
}
],
)
async def test_unique_id(
hass: HomeAssistant, entity_registry: er.EntityRegistry, load_yaml_integration: None
) -> None:
"""Test unique_id option and if it only creates one cover per id."""
assert len(hass.states.async_all()) == 2
assert len(entity_registry.entities) == 2
assert entity_registry.async_get_entity_id("cover", "command_line", "unique")
assert entity_registry.async_get_entity_id(
"cover", "command_line", "not-so-unique-anymore"
)
async def test_updating_to_often(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test handling updating when command already running."""
called = []
wait_till_event = asyncio.Event()
wait_till_event.set()
class MockCommandCover(CommandCover):
"""Mock entity that updates."""
async def _async_update(self) -> None:
"""Update the entity."""
called.append(1)
# Add waiting time
await wait_till_event.wait()
with patch(
"homeassistant.components.command_line.cover.CommandCover",
side_effect=MockCommandCover,
):
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"cover": {
"command_state": "echo 1",
"value_template": "{{ value }}",
"name": "Test",
"scan_interval": 10,
}
}
]
},
)
await hass.async_block_till_done()
assert not called
assert (
"Updating Command Line Cover Test took longer than the scheduled update interval"
not in caplog.text
)
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=11))
await hass.async_block_till_done(wait_background_tasks=True)
assert called
called.clear()
assert (
"Updating Command Line Cover Test took longer than the scheduled update interval"
not in caplog.text
)
# Simulate update takes too long
wait_till_event.clear()
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=10))
await asyncio.sleep(0)
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=10))
wait_till_event.set()
# Finish processing update
await hass.async_block_till_done(wait_background_tasks=True)
assert called
assert (
"Updating Command Line Cover Test took longer than the scheduled update interval"
in caplog.text
)
async def test_updating_manually(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test handling manual updating using homeassistant udate_entity service."""
await setup.async_setup_component(hass, HA_DOMAIN, {})
called = []
class MockCommandCover(CommandCover):
"""Mock entity that updates."""
async def _async_update(self) -> None:
"""Update."""
called.append(1)
with patch(
"homeassistant.components.command_line.cover.CommandCover",
side_effect=MockCommandCover,
):
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"cover": {
"command_state": "echo 1",
"value_template": "{{ value }}",
"name": "Test",
"scan_interval": 10,
}
}
]
},
)
await hass.async_block_till_done()
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=10))
await hass.async_block_till_done(wait_background_tasks=True)
assert called
called.clear()
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: ["cover.test"]},
blocking=True,
)
await hass.async_block_till_done()
assert called
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"cover": {
"command_state": "echo 10",
"name": "Test",
"availability": '{{ states("sensor.input1")=="on" }}',
},
}
]
}
],
)
async def test_availability(
hass: HomeAssistant,
load_yaml_integration: None,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test availability."""
hass.states.async_set("sensor.input1", "on")
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("cover.test")
assert entity_state
assert entity_state.state == CoverState.OPEN
hass.states.async_set("sensor.input1", "off")
await hass.async_block_till_done()
with mock_asyncio_subprocess_run(b"50\n"):
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("cover.test")
assert entity_state
assert entity_state.state == STATE_UNAVAILABLE
async def test_icon_template(hass: HomeAssistant) -> None:
"""Test with state value."""
with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "cover_status_icon")
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"cover": {
"command_state": f"cat {path}",
"command_open": f"echo 100 > {path}",
"command_close": f"echo 0 > {path}",
"command_stop": f"echo 0 > {path}",
"name": "Test",
"icon": '{% if this.attributes.icon=="mdi:icon2" %} mdi:icon1 {% else %} mdi:icon2 {% endif %}',
}
}
]
},
)
await hass.async_block_till_done()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
entity_state = hass.states.get("cover.test")
assert entity_state
assert entity_state.attributes.get("icon") == "mdi:icon1"
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
{ATTR_ENTITY_ID: "cover.test"},
blocking=True,
)
entity_state = hass.states.get("cover.test")
assert entity_state
assert entity_state.attributes.get("icon") == "mdi:icon2"

View File

@@ -0,0 +1,85 @@
"""Test Command line component setup process."""
from __future__ import annotations
from datetime import timedelta
from unittest.mock import patch
import pytest
from homeassistant import config as hass_config
from homeassistant.components.command_line.const import DOMAIN
from homeassistant.const import SERVICE_RELOAD, STATE_ON, STATE_OPEN
from homeassistant.core import HomeAssistant
import homeassistant.util.dt as dt_util
from tests.common import async_fire_time_changed, get_fixture_path
async def test_setup_config(hass: HomeAssistant, load_yaml_integration: None) -> None:
"""Test setup from yaml."""
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=10))
await hass.async_block_till_done(wait_background_tasks=True)
state_binary_sensor = hass.states.get("binary_sensor.test")
state_sensor = hass.states.get("sensor.test")
state_cover = hass.states.get("cover.test")
state_switch = hass.states.get("switch.test")
assert state_binary_sensor.state == STATE_ON
assert state_sensor.state == "5"
assert state_cover.state == STATE_OPEN
assert state_switch.state == STATE_ON
async def test_reload_service(
hass: HomeAssistant, load_yaml_integration: None, caplog: pytest.LogCaptureFixture
) -> None:
"""Test reload serviice."""
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=10))
await hass.async_block_till_done()
state_binary_sensor = hass.states.get("binary_sensor.test")
state_sensor = hass.states.get("sensor.test")
assert state_binary_sensor.state == STATE_ON
assert state_sensor.state == "5"
caplog.clear()
yaml_path = get_fixture_path("configuration.yaml", "command_line")
with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(
DOMAIN,
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
assert "Loading config" in caplog.text
state_binary_sensor = hass.states.get("binary_sensor.test")
state_sensor = hass.states.get("sensor.test")
assert state_binary_sensor.state == STATE_ON
assert not state_sensor
caplog.clear()
yaml_path = get_fixture_path("configuration_empty.yaml", "command_line")
with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path):
await hass.services.async_call(
DOMAIN,
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
state_binary_sensor = hass.states.get("binary_sensor.test")
state_sensor = hass.states.get("sensor.test")
assert not state_binary_sensor
assert not state_sensor
assert "Loading config" not in caplog.text

View File

@@ -0,0 +1,196 @@
"""The tests for the command line notification platform."""
from __future__ import annotations
import os
from pathlib import Path
import subprocess
import tempfile
from unittest.mock import patch
import pytest
from homeassistant import setup
from homeassistant.components.command_line import DOMAIN
from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN
from homeassistant.core import HomeAssistant
async def test_setup_platform_yaml(hass: HomeAssistant) -> None:
"""Test setting up the platform with platform yaml."""
await setup.async_setup_component(
hass,
"notify",
{
"notify": {
"platform": "command_line",
"command": "echo 1",
"payload_on": "1",
"payload_off": "0",
}
},
)
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 0
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"notify": {
"command": "exit 0",
"name": "Test2",
}
}
]
}
],
)
async def test_setup_integration_yaml(
hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test sensor setup."""
assert hass.services.has_service(NOTIFY_DOMAIN, "test2")
async def test_bad_config(hass: HomeAssistant) -> None:
"""Test set up the platform with bad/missing configuration."""
assert await setup.async_setup_component(
hass,
NOTIFY_DOMAIN,
{
NOTIFY_DOMAIN: [
{"platform": "command_line"},
]
},
)
await hass.async_block_till_done()
assert not hass.services.has_service(NOTIFY_DOMAIN, "test")
async def test_command_line_output(hass: HomeAssistant) -> None:
"""Test the command line output."""
with tempfile.TemporaryDirectory() as tempdirname:
filename = os.path.join(tempdirname, "message.txt")
message = "one, two, testing, testing"
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"notify": {
"command": f"cat > {filename}",
"name": "Test3",
}
}
]
},
)
await hass.async_block_till_done()
assert hass.services.has_service(NOTIFY_DOMAIN, "test3")
await hass.services.async_call(
NOTIFY_DOMAIN, "test3", {"message": message}, blocking=True
)
assert message == await hass.async_add_executor_job(Path(filename).read_text)
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"notify": {
"command": "exit 1",
"name": "Test4",
}
}
]
}
],
)
async def test_error_for_none_zero_exit_code(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test if an error is logged for non zero exit codes."""
await hass.services.async_call(
NOTIFY_DOMAIN, "test4", {"message": "error"}, blocking=True
)
assert "Command failed" in caplog.text
assert "return code 1" in caplog.text
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"notify": {
"command": "sleep 10000",
"command_timeout": 0.0000001,
"name": "Test5",
}
}
]
}
],
)
async def test_timeout(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test blocking is not forever."""
await hass.services.async_call(
NOTIFY_DOMAIN, "test5", {"message": "error"}, blocking=True
)
assert "Timeout" in caplog.text
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"notify": {
"command": "exit 0",
"name": "Test6",
}
}
]
}
],
)
async def test_subprocess_exceptions(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test that notify subprocess exceptions are handled correctly."""
with patch(
"homeassistant.components.command_line.notify.subprocess.Popen"
) as check_output:
check_output.return_value.__enter__ = check_output
check_output.return_value.communicate.side_effect = [
subprocess.TimeoutExpired("cmd", 10),
None,
subprocess.SubprocessError(),
]
await hass.services.async_call(
NOTIFY_DOMAIN, "test6", {"message": "error"}, blocking=True
)
assert check_output.call_count == 2
assert "Timeout for command" in caplog.text
await hass.services.async_call(
NOTIFY_DOMAIN, "test6", {"message": "error"}, blocking=True
)
assert check_output.call_count == 4
assert "Error trying to exec command" in caplog.text

View File

@@ -0,0 +1,810 @@
"""The tests for the Command line sensor platform."""
from __future__ import annotations
import asyncio
from datetime import timedelta
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant import setup
from homeassistant.components.command_line import DOMAIN
from homeassistant.components.command_line.sensor import CommandSensor
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from . import mock_asyncio_subprocess_run
from tests.common import async_fire_time_changed
async def test_setup_platform_yaml(hass: HomeAssistant) -> None:
"""Test setting up the platform with platform yaml."""
await setup.async_setup_component(
hass,
"sensor",
{
"sensor": {
"platform": "command_line",
"command": "echo 1",
"payload_on": "1",
"payload_off": "0",
}
},
)
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 0
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo 5",
"unit_of_measurement": "in",
}
}
]
}
],
)
async def test_setup_integration_yaml(
hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test sensor setup."""
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == "5"
assert entity_state.name == "Test"
assert entity_state.attributes["unit_of_measurement"] == "in"
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo 50",
"unit_of_measurement": "in",
"value_template": "{{ value | multiply(0.1) }}",
"icon": "mdi:console",
}
}
]
}
],
)
async def test_template(hass: HomeAssistant, load_yaml_integration: None) -> None:
"""Test command sensor with template."""
entity_state = hass.states.get("sensor.test")
assert entity_state
assert float(entity_state.state) == 5
assert entity_state.attributes.get("icon") == "mdi:console"
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo {{ states.sensor.input_sensor.state }}",
}
}
]
}
],
)
async def test_template_render(
hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Ensure command with templates get rendered properly."""
hass.states.async_set("sensor.input_sensor", "sensor_value")
# Give time for template to load
async_fire_time_changed(
hass,
dt_util.utcnow() + timedelta(minutes=1),
)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == "sensor_value"
async def test_template_render_with_quote(hass: HomeAssistant) -> None:
"""Ensure command with templates and quotes get rendered properly."""
hass.states.async_set("sensor.input_sensor", "sensor_value")
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": 'echo "{{ states.sensor.input_sensor.state }}" "3 4"',
}
}
]
},
)
await hass.async_block_till_done()
with mock_asyncio_subprocess_run(b"Works\n") as mock_subprocess_run:
# Give time for template to load
async_fire_time_changed(
hass,
dt_util.utcnow() + timedelta(minutes=1),
)
await hass.async_block_till_done(wait_background_tasks=True)
assert len(mock_subprocess_run.mock_calls) == 1
mock_subprocess_run.assert_called_with(
'echo "sensor_value" "3 4"',
stdout=-1,
close_fds=False,
)
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo {{ this template doesn't parse",
}
}
]
}
],
)
async def test_bad_template_render(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant, get_config: dict[str, Any]
) -> None:
"""Test rendering a broken template."""
await setup.async_setup_component(
hass,
DOMAIN,
get_config,
)
await hass.async_block_till_done()
assert "Error rendering command template" in caplog.text
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "asdfasdf",
}
}
]
}
],
)
async def test_bad_command(hass: HomeAssistant, get_config: dict[str, Any]) -> None:
"""Test bad command."""
await setup.async_setup_component(
hass,
DOMAIN,
get_config,
)
await hass.async_block_till_done()
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == "unknown"
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "exit 33",
}
}
]
}
],
)
async def test_return_code(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant, get_config: dict[str, Any]
) -> None:
"""Test that an error return code is logged."""
await setup.async_setup_component(
hass,
DOMAIN,
get_config,
)
await hass.async_block_till_done()
assert "return code 33" in caplog.text
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": (
'echo { \\"key\\": \\"some_json_value\\", \\"another_key\\": '
'\\"another_json_value\\", \\"key_three\\": \\"value_three\\" }'
),
"json_attributes": ["key", "another_key", "key_three"],
}
}
]
}
],
)
async def test_update_with_json_attrs(
hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test attributes get extracted from a JSON result."""
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == "unknown"
assert entity_state.attributes["key"] == "some_json_value"
assert entity_state.attributes["another_key"] == "another_json_value"
assert entity_state.attributes["key_three"] == "value_three"
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": (
'echo { \\"key\\": \\"some_json_value\\", \\"another_key\\": '
'\\"another_json_value\\", \\"key_three\\": \\"value_three\\" }'
),
"json_attributes": ["key", "another_key", "key_three"],
"value_template": '{{ value_json["key"] }}',
}
}
]
}
],
)
async def test_update_with_json_attrs_and_value_template(
hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test json_attributes can be used together with value_template."""
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == "some_json_value"
assert entity_state.attributes["key"] == "some_json_value"
assert entity_state.attributes["another_key"] == "another_json_value"
assert entity_state.attributes["key_three"] == "value_three"
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo",
"json_attributes": ["key"],
}
}
]
}
],
)
async def test_update_with_json_attrs_no_data(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant, get_config: dict[str, Any]
) -> None:
"""Test attributes when no JSON result fetched."""
await setup.async_setup_component(
hass,
DOMAIN,
get_config,
)
await hass.async_block_till_done()
entity_state = hass.states.get("sensor.test")
assert entity_state
assert "key" not in entity_state.attributes
assert "Empty reply found when expecting JSON data" in caplog.text
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo [1, 2, 3]",
"json_attributes": ["key"],
}
}
]
}
],
)
async def test_update_with_json_attrs_not_dict(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant, get_config: dict[str, Any]
) -> None:
"""Test attributes when the return value not a dict."""
await setup.async_setup_component(
hass,
DOMAIN,
get_config,
)
await hass.async_block_till_done()
entity_state = hass.states.get("sensor.test")
assert entity_state
assert "key" not in entity_state.attributes
assert "JSON result was not a dictionary" in caplog.text
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo This is text rather than JSON data.",
"json_attributes": ["key"],
}
}
]
}
],
)
async def test_update_with_json_attrs_bad_json(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant, get_config: dict[str, Any]
) -> None:
"""Test attributes when the return value is invalid JSON."""
await setup.async_setup_component(
hass,
DOMAIN,
get_config,
)
await hass.async_block_till_done()
entity_state = hass.states.get("sensor.test")
assert entity_state
assert "key" not in entity_state.attributes
assert "Unable to parse output as JSON" in caplog.text
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": (
'echo { \\"key\\": \\"some_json_value\\", \\"another_key\\": '
'\\"another_json_value\\", \\"key_three\\": \\"value_three\\" }'
),
"json_attributes": [
"key",
"another_key",
"key_three",
"missing_key",
],
}
}
]
}
],
)
async def test_update_with_missing_json_attrs(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test attributes when an expected key is missing."""
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.attributes["key"] == "some_json_value"
assert entity_state.attributes["another_key"] == "another_json_value"
assert entity_state.attributes["key_three"] == "value_three"
assert "missing_key" not in entity_state.attributes
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": (
'echo { \\"key\\": \\"some_json_value\\", \\"another_key\\": '
'\\"another_json_value\\", \\"key_three\\": \\"value_three\\" }'
),
"json_attributes": ["key", "another_key"],
}
}
]
}
],
)
async def test_update_with_unnecessary_json_attrs(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test attributes when an expected key is missing."""
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.attributes["key"] == "some_json_value"
assert entity_state.attributes["another_key"] == "another_json_value"
assert "key_three" not in entity_state.attributes
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": 'echo \
{\
\\"top_level\\": {\
\\"second_level\\": {\
\\"key\\": \\"some_json_value\\",\
\\"another_key\\": \\"another_json_value\\",\
\\"key_three\\": \\"value_three\\"\
}\
}\
}',
"json_attributes": ["key", "another_key", "key_three"],
"json_attributes_path": "$.top_level.second_level",
}
}
]
}
],
)
async def test_update_with_json_attrs_with_json_attrs_path(
hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test using json_attributes_path to select a different part of the json object as root."""
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.attributes["key"] == "some_json_value"
assert entity_state.attributes["another_key"] == "another_json_value"
assert entity_state.attributes["key_three"] == "value_three"
assert "top_level" not in entity_state.attributes
assert "second_level" not in entity_state.attributes
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"unique_id": "unique",
"command": "echo 0",
}
},
{
"sensor": {
"name": "Test",
"unique_id": "not-so-unique-anymore",
"command": "echo 1",
}
},
{
"sensor": {
"name": "Test",
"unique_id": "not-so-unique-anymore",
"command": "echo 2",
},
},
]
}
],
)
async def test_unique_id(
hass: HomeAssistant, entity_registry: er.EntityRegistry, load_yaml_integration: None
) -> None:
"""Test unique_id option and if it only creates one sensor per id."""
assert len(hass.states.async_all()) == 2
assert len(entity_registry.entities) == 2
assert entity_registry.async_get_entity_id("sensor", "command_line", "unique")
assert entity_registry.async_get_entity_id(
"sensor", "command_line", "not-so-unique-anymore"
)
async def test_updating_to_often(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test handling updating when command already running."""
wait_till_event = asyncio.Event()
wait_till_event.set()
called = []
class MockCommandSensor(CommandSensor):
"""Mock entity that updates."""
async def _async_update(self) -> None:
"""Update entity."""
called.append(1)
# Wait till event is set
await wait_till_event.wait()
with patch(
"homeassistant.components.command_line.sensor.CommandSensor",
side_effect=MockCommandSensor,
):
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo 1",
"scan_interval": 10,
}
}
]
},
)
await hass.async_block_till_done()
assert called
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=15))
wait_till_event.set()
await asyncio.sleep(0)
assert (
"Updating Command Line Sensor Test took longer than the scheduled update interval"
not in caplog.text
)
# Simulate update takes too long
wait_till_event.clear()
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=10))
await asyncio.sleep(0)
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=10))
wait_till_event.set()
await asyncio.sleep(0)
assert (
"Updating Command Line Sensor Test took longer than the scheduled update interval"
in caplog.text
)
async def test_updating_manually(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test handling manual updating using homeassistant udate_entity service."""
await setup.async_setup_component(hass, HA_DOMAIN, {})
called = []
class MockCommandSensor(CommandSensor):
"""Mock entity that updates."""
async def _async_update(self) -> None:
"""Update slow."""
called.append(1)
with patch(
"homeassistant.components.command_line.sensor.CommandSensor",
side_effect=MockCommandSensor,
):
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo 1",
"scan_interval": 10,
}
}
]
},
)
await hass.async_block_till_done()
assert called
called.clear()
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: ["sensor.test"]},
blocking=True,
)
await hass.async_block_till_done()
assert called
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo 2022-12-22T13:15:30Z",
"device_class": "timestamp",
}
}
]
}
],
)
async def test_scrape_sensor_device_timestamp(
hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test Command Line sensor with a device of type TIMESTAMP."""
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == "2022-12-22T13:15:30+00:00"
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo January 17, 2022",
"device_class": "date",
"value_template": "{{ strptime(value, '%B %d, %Y').strftime('%Y-%m-%d') }}",
}
}
]
}
],
)
async def test_scrape_sensor_device_date(
hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Test Command Line sensor with a device of type DATE."""
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == "2022-01-17"
async def test_template_not_error_when_data_is_none(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test command sensor with template not logging error when data is None."""
with mock_asyncio_subprocess_run(returncode=1):
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "failed command",
"unit_of_measurement": "MB",
"value_template": "{{ (value.split('\t')[0]|int(0)/1000)|round(3) }}",
}
}
]
},
)
await hass.async_block_till_done()
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == STATE_UNKNOWN
assert (
"Template variable error: 'None' has no attribute 'split' when rendering"
not in caplog.text
)
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo January 17, 2022",
"device_class": "date",
"value_template": "{{ strptime(value, '%B %d, %Y').strftime('%Y-%m-%d') }}",
"availability": '{{ states("sensor.input1")=="on" }}',
}
}
]
}
],
)
async def test_availability(
hass: HomeAssistant,
load_yaml_integration: None,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test availability."""
hass.states.async_set("sensor.input1", "on")
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == "2022-01-17"
hass.states.async_set("sensor.input1", "off")
await hass.async_block_till_done()
with mock_asyncio_subprocess_run(b"January 17, 2022"):
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == STATE_UNAVAILABLE

View File

@@ -0,0 +1,770 @@
"""The tests for the Command line switch platform."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import json
import os
import tempfile
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant import setup
from homeassistant.components.command_line import DOMAIN
from homeassistant.components.command_line.switch import CommandSwitch
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN, SCAN_INTERVAL
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
import homeassistant.util.dt as dt_util
from . import mock_asyncio_subprocess_run
from tests.common import async_fire_time_changed
async def test_setup_platform_yaml(hass: HomeAssistant) -> None:
"""Test setting up the platform with platform yaml."""
await setup.async_setup_component(
hass,
"switch",
{
"switch": {
"platform": "command_line",
"command": "echo 1",
"payload_on": "1",
"payload_off": "0",
}
},
)
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 0
async def test_state_integration_yaml(hass: HomeAssistant) -> None:
"""Test with none state."""
with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "switch_status")
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_on": f"echo 1 > {path}",
"command_off": f"echo 0 > {path}",
"name": "Test",
}
}
]
},
)
await hass.async_block_till_done()
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.test"},
blocking=True,
)
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_ON
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.test"},
blocking=True,
)
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_OFF
async def test_state_value(hass: HomeAssistant) -> None:
"""Test with state value."""
with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "switch_status")
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_state": f"cat {path}",
"command_on": f"echo 1 > {path}",
"command_off": f"echo 0 > {path}",
"value_template": '{{ value=="1" }}',
"icon": (
'{% if value=="1" %} mdi:on {% else %} mdi:off {% endif %}'
),
"name": "Test",
}
}
]
},
)
await hass.async_block_till_done()
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.test"},
blocking=True,
)
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_ON
assert entity_state.attributes.get("icon") == "mdi:on"
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.test"},
blocking=True,
)
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_OFF
assert entity_state.attributes.get("icon") == "mdi:off"
async def test_state_json_value(hass: HomeAssistant) -> None:
"""Test with state JSON value."""
with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "switch_status")
oncmd = json.dumps({"status": "ok"})
offcmd = json.dumps({"status": "nope"})
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_state": f"cat {path}",
"command_on": f"echo '{oncmd}' > {path}",
"command_off": f"echo '{offcmd}' > {path}",
"value_template": '{{ value_json.status=="ok" }}',
"icon": (
'{% if value_json.status=="ok" %} mdi:on'
"{% else %} mdi:off {% endif %}"
),
"name": "Test",
}
}
]
},
)
await hass.async_block_till_done()
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.test"},
blocking=True,
)
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_ON
assert entity_state.attributes.get("icon") == "mdi:on"
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.test"},
blocking=True,
)
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_OFF
assert entity_state.attributes.get("icon") == "mdi:off"
async def test_state_code(hass: HomeAssistant) -> None:
"""Test with state code."""
with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "switch_status")
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_state": f"cat {path}",
"command_on": f"echo 1 > {path}",
"command_off": f"echo 0 > {path}",
"name": "Test",
}
}
]
},
)
await hass.async_block_till_done()
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.test"},
blocking=True,
)
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_ON
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.test"},
blocking=True,
)
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_ON
async def test_assumed_state_should_be_true_if_command_state_is_none(
hass: HomeAssistant,
) -> None:
"""Test with state value."""
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_on": "echo 'on command'",
"command_off": "echo 'off command'",
"name": "Test",
}
}
]
},
)
await hass.async_block_till_done()
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.attributes["assumed_state"]
async def test_assumed_state_should_absent_if_command_state_present(
hass: HomeAssistant,
) -> None:
"""Test with state value."""
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_on": "echo 'on command'",
"command_off": "echo 'off command'",
"command_state": "cat {}",
"name": "Test",
}
}
]
},
)
await hass.async_block_till_done()
entity_state = hass.states.get("switch.test")
assert entity_state
assert "assumed_state" not in entity_state.attributes
async def test_name_is_set_correctly(hass: HomeAssistant) -> None:
"""Test that name is set correctly."""
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_on": "echo 'on command'",
"command_off": "echo 'off command'",
"name": "Test friendly name!",
}
}
]
},
)
await hass.async_block_till_done()
entity_state = hass.states.get("switch.test_friendly_name")
assert entity_state
assert entity_state.name == "Test friendly name!"
async def test_switch_command_state_fail(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant
) -> None:
"""Test that switch failures are handled correctly."""
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_on": "exit 0",
"command_off": "exit 0'",
"command_state": "echo 1",
"name": "Test",
}
}
]
},
)
await hass.async_block_till_done()
async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == "on"
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.test"},
blocking=True,
)
await hass.async_block_till_done()
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == "on"
assert "Command failed" in caplog.text
async def test_switch_command_state_code_exceptions(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant
) -> None:
"""Test that switch state code exceptions are handled correctly."""
with mock_asyncio_subprocess_run(exception=asyncio.TimeoutError) as run:
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_on": "exit 0",
"command_off": "exit 0'",
"command_state": "echo 1",
"name": "Test",
}
}
]
},
)
await hass.async_block_till_done()
async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL)
await hass.async_block_till_done()
assert run.called
assert "Timeout for command" in caplog.text
with mock_asyncio_subprocess_run(returncode=127) as run:
async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL * 2)
await hass.async_block_till_done()
assert run.called
assert "Error trying to exec command" in caplog.text
async def test_switch_command_state_value_exceptions(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant
) -> None:
"""Test that switch state value exceptions are handled correctly."""
with mock_asyncio_subprocess_run(exception=asyncio.TimeoutError) as run:
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_on": "exit 0",
"command_off": "exit 0'",
"command_state": "echo 1",
"value_template": '{{ value=="1" }}',
"name": "Test",
}
}
]
},
)
await hass.async_block_till_done()
async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL)
await hass.async_block_till_done()
assert run.call_count == 1
assert "Timeout for command" in caplog.text
with mock_asyncio_subprocess_run(returncode=127) as run:
async_fire_time_changed(hass, dt_util.utcnow() + SCAN_INTERVAL * 2)
await hass.async_block_till_done()
assert run.call_count == 1
assert "Command failed (with return code 127)" in caplog.text
async def test_unique_id(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test unique_id option and if it only creates one switch per id."""
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_on": "echo on",
"command_off": "echo off",
"unique_id": "unique",
"name": "Test",
}
},
{
"switch": {
"command_on": "echo on",
"command_off": "echo off",
"unique_id": "not-so-unique-anymore",
"name": "Test2",
}
},
{
"switch": {
"command_on": "echo on",
"command_off": "echo off",
"unique_id": "not-so-unique-anymore",
"name": "Test3",
},
},
]
},
)
await hass.async_block_till_done()
assert len(hass.states.async_all()) == 2
assert len(entity_registry.entities) == 2
assert entity_registry.async_get_entity_id("switch", "command_line", "unique")
assert entity_registry.async_get_entity_id(
"switch", "command_line", "not-so-unique-anymore"
)
async def test_command_failure(
caplog: pytest.LogCaptureFixture, hass: HomeAssistant
) -> None:
"""Test command failure."""
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_off": "exit 33",
"name": "Test",
}
}
]
},
)
await hass.async_block_till_done()
await hass.services.async_call(
SWITCH_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "switch.test"}, blocking=True
)
assert "return code 33" in caplog.text
async def test_templating(hass: HomeAssistant) -> None:
"""Test with templating."""
with tempfile.TemporaryDirectory() as tempdirname:
path = os.path.join(tempdirname, "switch_status")
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_state": f"cat {path}",
"command_on": f"echo 1 > {path}",
"command_off": f"echo 0 > {path}",
"value_template": '{{ value=="1" }}',
"icon": (
'{% if this.attributes.icon=="mdi:icon2" %} mdi:icon1 {% else %} mdi:icon2 {% endif %}'
),
"name": "Test",
}
},
{
"switch": {
"command_state": f"cat {path}",
"command_on": f"echo 1 > {path}",
"command_off": f"echo 0 > {path}",
"value_template": '{{ value=="1" }}',
"icon": (
'{% if states("switch.test")=="off" %} mdi:off {% else %} mdi:on {% endif %}'
),
"name": "Test2",
},
},
]
},
)
await hass.async_block_till_done()
entity_state = hass.states.get("switch.test")
entity_state2 = hass.states.get("switch.test2")
assert entity_state.state == STATE_OFF
assert entity_state2.state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.test"},
blocking=True,
)
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.test2"},
blocking=True,
)
entity_state = hass.states.get("switch.test")
entity_state2 = hass.states.get("switch.test2")
assert entity_state.state == STATE_ON
assert entity_state.attributes.get("icon") == "mdi:icon2"
assert entity_state2.state == STATE_ON
assert entity_state2.attributes.get("icon") == "mdi:on"
async def test_updating_to_often(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test handling updating when command already running."""
called = []
wait_till_event = asyncio.Event()
wait_till_event.set()
class MockCommandSwitch(CommandSwitch):
"""Mock entity that updates."""
async def _async_update(self) -> None:
"""Update entity."""
called.append(1)
# Wait till event is set
await wait_till_event.wait()
with patch(
"homeassistant.components.command_line.switch.CommandSwitch",
side_effect=MockCommandSwitch,
):
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_state": "echo 1",
"command_on": "echo 2",
"command_off": "echo 3",
"name": "Test",
"scan_interval": 10,
}
}
]
},
)
await hass.async_block_till_done()
assert not called
assert (
"Updating Command Line Switch Test took longer than the scheduled update interval"
not in caplog.text
)
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=11))
await hass.async_block_till_done()
assert called
called.clear()
assert (
"Updating Command Line Switch Test took longer than the scheduled update interval"
not in caplog.text
)
# Simulate update takes too long
wait_till_event.clear()
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=10))
await asyncio.sleep(0)
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=10))
wait_till_event.set()
# Finish processing update
await hass.async_block_till_done()
assert called
assert (
"Updating Command Line Switch Test took longer than the scheduled update interval"
in caplog.text
)
async def test_updating_manually(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test handling manual updating using homeassistant udate_entity service."""
await setup.async_setup_component(hass, HA_DOMAIN, {})
called = []
class MockCommandSwitch(CommandSwitch):
"""Mock entity that updates."""
async def _async_update(self) -> None:
"""Update slow."""
called.append(1)
with patch(
"homeassistant.components.command_line.switch.CommandSwitch",
side_effect=MockCommandSwitch,
):
await setup.async_setup_component(
hass,
DOMAIN,
{
"command_line": [
{
"switch": {
"command_state": "echo 1",
"command_on": "echo 2",
"command_off": "echo 3",
"name": "Test",
"scan_interval": 10,
}
}
]
},
)
await hass.async_block_till_done()
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=10))
await hass.async_block_till_done()
assert called
called.clear()
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: ["switch.test"]},
blocking=True,
)
await hass.async_block_till_done()
assert called
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"switch": {
"command_state": "echo 1",
"command_on": "echo 2",
"command_off": "echo 3",
"name": "Test",
"availability": '{{ states("sensor.input1")=="on" }}',
},
}
]
}
],
)
async def test_availability(
hass: HomeAssistant,
load_yaml_integration: None,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test availability."""
hass.states.async_set("sensor.input1", "on")
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_ON
hass.states.async_set("sensor.input1", "off")
await hass.async_block_till_done()
with mock_asyncio_subprocess_run(b"50\n"):
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("switch.test")
assert entity_state
assert entity_state.state == STATE_UNAVAILABLE