response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Test passing the job type to HassJob when we already know it. | def test_hassjob_passing_job_type():
"""Test passing the job type to HassJob when we already know it."""
@ha.callback
def callback_func():
pass
def not_callback_func():
pass
assert (
HassJob(callback_func, job_type=ha.HassJobType.Callback).job_type
== ha.HassJobType.Callback
)
# We should trust the job_type passed in
assert (
HassJob(not_callback_func, job_type=ha.HassJobType.Callback).job_type
== ha.HassJobType.Callback
) |
Test module.__all__ is correctly set. | def test_all() -> None:
"""Test module.__all__ is correctly set."""
help_test_all(ha) |
Test deprecated constants. | def test_deprecated_constants(
caplog: pytest.LogCaptureFixture,
enum: ha.ConfigSource,
) -> None:
"""Test deprecated constants."""
import_and_test_deprecated_constant_enum(caplog, ha, enum, "SOURCE_", "2025.1") |
Test one time listener repr. | def test_one_time_listener_repr(hass: HomeAssistant) -> None:
"""Test one time listener repr."""
def _listener(event: ha.Event):
"""Test listener."""
one_time_listener = ha._OneTimeListener(hass, HassJob(_listener))
repr_str = repr(one_time_listener)
assert "OneTimeListener" in repr_str
assert "test_core" in repr_str
assert "_listener" in repr_str |
Return a flow manager. | def manager():
"""Return a flow manager."""
handlers = Registry()
entries = []
class FlowManager(data_entry_flow.FlowManager):
"""Test flow manager."""
async def async_create_flow(self, handler_key, *, context, data):
"""Test create flow."""
handler = handlers.get(handler_key)
if handler is None:
raise data_entry_flow.UnknownHandler
flow = handler()
flow.init_step = context.get("init_step", "init")
return flow
async def async_finish_flow(self, flow, result):
"""Test finish flow."""
if result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY:
result["source"] = flow.context.get("source")
entries.append(result)
return result
mgr = FlowManager(None)
mgr.mock_created_entries = entries
mgr.mock_reg_handler = handlers.register
return mgr |
Test module.__all__ is correctly set. | def test_all() -> None:
"""Test module.__all__ is correctly set."""
help_test_all(data_entry_flow) |
Test deprecated constants. | def test_deprecated_constants(
caplog: pytest.LogCaptureFixture,
enum: data_entry_flow.FlowResultType,
) -> None:
"""Test deprecated constants."""
import_and_test_deprecated_constant_enum(
caplog, data_entry_flow, enum, "RESULT_TYPE_", "2025.1"
) |
Test ConditionError stringifiers. | def test_conditionerror_format() -> None:
"""Test ConditionError stringifiers."""
error1 = ConditionErrorMessage("test", "A test error")
assert str(error1) == "In 'test' condition: A test error"
error2 = ConditionErrorMessage("test", "Another error")
assert str(error2) == "In 'test' condition: Another error"
error_pos1 = ConditionErrorIndex("box", index=0, total=2, error=error1)
assert (
str(error_pos1)
== """In 'box' (item 1 of 2):
In 'test' condition: A test error"""
)
error_pos2 = ConditionErrorIndex("box", index=1, total=2, error=error2)
assert (
str(error_pos2)
== """In 'box' (item 2 of 2):
In 'test' condition: Another error"""
)
error_container1 = ConditionErrorContainer("box", errors=[error_pos1, error_pos2])
assert (
str(error_container1)
== """In 'box' (item 1 of 2):
In 'test' condition: A test error
In 'box' (item 2 of 2):
In 'test' condition: Another error"""
)
error_pos3 = ConditionErrorIndex("box", index=0, total=1, error=error1)
assert (
str(error_pos3)
== """In 'box':
In 'test' condition: A test error"""
) |
Ensure we can create TemplateError. | def test_template_message(arg: str | Exception, expected: str) -> None:
"""Ensure we can create TemplateError."""
template_error = TemplateError(arg)
assert str(template_error) == expected |
Test loading components. | def test_component_loader(hass: HomeAssistant) -> None:
"""Test loading components."""
components = loader.Components(hass)
assert components.http.CONFIG_SCHEMA is http.CONFIG_SCHEMA
assert hass.components.http.CONFIG_SCHEMA is http.CONFIG_SCHEMA |
Test loading components. | def test_component_loader_non_existing(hass: HomeAssistant) -> None:
"""Test loading components."""
components = loader.Components(hass)
with pytest.raises(ImportError):
_ = components.non_existing |
Test integration properties. | def test_integration_properties(hass: HomeAssistant) -> None:
"""Test integration properties."""
integration = loader.Integration(
hass,
"homeassistant.components.hue",
None,
{
"name": "Philips Hue",
"domain": "hue",
"dependencies": ["test-dep"],
"requirements": ["test-req==1.0.0"],
"zeroconf": ["_hue._tcp.local."],
"homekit": {"models": ["BSB002"]},
"dhcp": [
{"hostname": "tesla_*", "macaddress": "4CFCAA*"},
{"hostname": "tesla_*", "macaddress": "044EAF*"},
{"hostname": "tesla_*", "macaddress": "98ED5C*"},
{"registered_devices": True},
],
"bluetooth": [{"manufacturer_id": 76, "manufacturer_data_start": [0x06]}],
"usb": [
{"vid": "10C4", "pid": "EA60"},
{"vid": "1CF1", "pid": "0030"},
{"vid": "1A86", "pid": "7523"},
{"vid": "10C4", "pid": "8A2A"},
],
"ssdp": [
{
"manufacturer": "Royal Philips Electronics",
"modelName": "Philips hue bridge 2012",
},
{
"manufacturer": "Royal Philips Electronics",
"modelName": "Philips hue bridge 2015",
},
{"manufacturer": "Signify", "modelName": "Philips hue bridge 2015"},
],
"mqtt": ["hue/discovery"],
"version": "1.0.0",
},
)
assert integration.name == "Philips Hue"
assert integration.domain == "hue"
assert integration.homekit == {"models": ["BSB002"]}
assert integration.zeroconf == ["_hue._tcp.local."]
assert integration.dhcp == [
{"hostname": "tesla_*", "macaddress": "4CFCAA*"},
{"hostname": "tesla_*", "macaddress": "044EAF*"},
{"hostname": "tesla_*", "macaddress": "98ED5C*"},
{"registered_devices": True},
]
assert integration.usb == [
{"vid": "10C4", "pid": "EA60"},
{"vid": "1CF1", "pid": "0030"},
{"vid": "1A86", "pid": "7523"},
{"vid": "10C4", "pid": "8A2A"},
]
assert integration.bluetooth == [
{"manufacturer_id": 76, "manufacturer_data_start": [0x06]}
]
assert integration.ssdp == [
{
"manufacturer": "Royal Philips Electronics",
"modelName": "Philips hue bridge 2012",
},
{
"manufacturer": "Royal Philips Electronics",
"modelName": "Philips hue bridge 2015",
},
{"manufacturer": "Signify", "modelName": "Philips hue bridge 2015"},
]
assert integration.mqtt == ["hue/discovery"]
assert integration.dependencies == ["test-dep"]
assert integration.requirements == ["test-req==1.0.0"]
assert integration.is_built_in is True
assert integration.version == "1.0.0"
integration = loader.Integration(
hass,
"custom_components.hue",
None,
{
"name": "Philips Hue",
"domain": "hue",
"dependencies": ["test-dep"],
"requirements": ["test-req==1.0.0"],
},
)
assert integration.is_built_in is False
assert integration.homekit is None
assert integration.zeroconf is None
assert integration.dhcp is None
assert integration.bluetooth is None
assert integration.usb is None
assert integration.ssdp is None
assert integration.mqtt is None
assert integration.version is None
integration = loader.Integration(
hass,
"custom_components.hue",
None,
{
"name": "Philips Hue",
"domain": "hue",
"dependencies": ["test-dep"],
"zeroconf": [{"type": "_hue._tcp.local.", "name": "hue*"}],
"requirements": ["test-req==1.0.0"],
},
)
assert integration.is_built_in is False
assert integration.homekit is None
assert integration.zeroconf == [{"type": "_hue._tcp.local.", "name": "hue*"}]
assert integration.dhcp is None
assert integration.usb is None
assert integration.bluetooth is None
assert integration.ssdp is None |
Return a generated test integration. | def _get_test_integration(
hass: HomeAssistant, name: str, config_flow: bool, import_executor: bool = False
) -> loader.Integration:
"""Return a generated test integration."""
return loader.Integration(
hass,
f"homeassistant.components.{name}",
None,
{
"name": name,
"domain": name,
"config_flow": config_flow,
"dependencies": [],
"requirements": [],
"zeroconf": [f"_{name}._tcp.local."],
"homekit": {"models": [name]},
"ssdp": [{"manufacturer": name, "modelName": name}],
"mqtt": [f"{name}/discovery"],
"import_executor": import_executor,
},
) |
Return a generated test integration with application_credentials support. | def _get_test_integration_with_application_credentials(hass, name):
"""Return a generated test integration with application_credentials support."""
return loader.Integration(
hass,
f"homeassistant.components.{name}",
None,
{
"name": name,
"domain": name,
"config_flow": True,
"dependencies": ["application_credentials"],
"requirements": [],
"zeroconf": [f"_{name}._tcp.local."],
"homekit": {"models": [name]},
"ssdp": [{"manufacturer": name, "modelName": name}],
"mqtt": [f"{name}/discovery"],
},
) |
Return a generated test integration with a zeroconf matcher. | def _get_test_integration_with_zeroconf_matcher(hass, name, config_flow):
"""Return a generated test integration with a zeroconf matcher."""
return loader.Integration(
hass,
f"homeassistant.components.{name}",
None,
{
"name": name,
"domain": name,
"config_flow": config_flow,
"dependencies": [],
"requirements": [],
"zeroconf": [{"type": f"_{name}._tcp.local.", "name": f"{name}*"}],
"homekit": {"models": [name]},
"ssdp": [{"manufacturer": name, "modelName": name}],
},
) |
Return a generated test integration with a legacy zeroconf matcher. | def _get_test_integration_with_legacy_zeroconf_matcher(hass, name, config_flow):
"""Return a generated test integration with a legacy zeroconf matcher."""
return loader.Integration(
hass,
f"homeassistant.components.{name}",
None,
{
"name": name,
"domain": name,
"config_flow": config_flow,
"dependencies": [],
"requirements": [],
"zeroconf": [
{
"type": f"_{name}._tcp.local.",
"macaddress": "AABBCC*",
"manufacturer": "legacy*",
"model": "legacy*",
"name": f"{name}*",
}
],
"homekit": {"models": [name]},
"ssdp": [{"manufacturer": name, "modelName": name}],
},
) |
Return a generated test integration with a dhcp matcher. | def _get_test_integration_with_dhcp_matcher(hass, name, config_flow):
"""Return a generated test integration with a dhcp matcher."""
return loader.Integration(
hass,
f"homeassistant.components.{name}",
None,
{
"name": name,
"domain": name,
"config_flow": config_flow,
"dependencies": [],
"requirements": [],
"zeroconf": [],
"dhcp": [
{"hostname": "tesla_*", "macaddress": "4CFCAA*"},
{"hostname": "tesla_*", "macaddress": "044EAF*"},
{"hostname": "tesla_*", "macaddress": "98ED5C*"},
],
"homekit": {"models": [name]},
"ssdp": [{"manufacturer": name, "modelName": name}],
},
) |
Return a generated test integration with a bluetooth matcher. | def _get_test_integration_with_bluetooth_matcher(hass, name, config_flow):
"""Return a generated test integration with a bluetooth matcher."""
return loader.Integration(
hass,
f"homeassistant.components.{name}",
None,
{
"name": name,
"domain": name,
"config_flow": config_flow,
"bluetooth": [
{
"local_name": "Prodigio_*",
},
],
},
) |
Return a generated test integration with a usb matcher. | def _get_test_integration_with_usb_matcher(hass, name, config_flow):
"""Return a generated test integration with a usb matcher."""
return loader.Integration(
hass,
f"homeassistant.components.{name}",
None,
{
"name": name,
"domain": name,
"config_flow": config_flow,
"dependencies": [],
"requirements": [],
"usb": [
{
"vid": "10C4",
"pid": "EA60",
"known_devices": ["slae.sh cc2652rb stick"],
},
{"vid": "1CF1", "pid": "0030", "known_devices": ["Conbee II"]},
{
"vid": "1A86",
"pid": "7523",
"known_devices": ["Electrolama zig-a-zig-ah"],
},
{"vid": "10C4", "pid": "8A2A", "known_devices": ["Nortek HUSBZB-1"]},
],
},
) |
Test that import_executor defaults. | def test_import_executor_default(hass: HomeAssistant) -> None:
"""Test that import_executor defaults."""
custom_comp = mock_integration(hass, MockModule("any_random"), built_in=False)
assert custom_comp.import_executor is True
built_in_comp = mock_integration(hass, MockModule("other_random"), built_in=True)
assert built_in_comp.import_executor is True |
Test validate Python version method. | def test_validate_python(mock_exit) -> None:
"""Test validate Python version method."""
with patch("sys.version_info", new_callable=PropertyMock(return_value=(2, 7, 8))):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch("sys.version_info", new_callable=PropertyMock(return_value=(3, 2, 0))):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch("sys.version_info", new_callable=PropertyMock(return_value=(3, 4, 2))):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch("sys.version_info", new_callable=PropertyMock(return_value=(3, 5, 2))):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch(
"sys.version_info",
new_callable=PropertyMock(
return_value=(REQUIRED_PYTHON_VER[0] - 1,) + REQUIRED_PYTHON_VER[1:]
),
):
main.validate_python()
assert mock_exit.called is True
mock_exit.reset_mock()
with patch(
"sys.version_info", new_callable=PropertyMock(return_value=REQUIRED_PYTHON_VER)
):
main.validate_python()
assert mock_exit.called is False
mock_exit.reset_mock()
with patch(
"sys.version_info",
new_callable=PropertyMock(
return_value=(REQUIRED_PYTHON_VER[:2]) + (REQUIRED_PYTHON_VER[2] + 1,)
),
):
main.validate_python()
assert mock_exit.called is False
mock_exit.reset_mock() |
Test --skip-pip and --skip-pip-package are mutually exclusive. | def test_skip_pip_mutually_exclusive(mock_exit) -> None:
"""Test --skip-pip and --skip-pip-package are mutually exclusive."""
def parse_args(*args):
with patch("sys.argv", ["python", *args]):
return main.get_arguments()
args = parse_args("--skip-pip")
assert args.skip_pip is True
args = parse_args("--skip-pip-packages", "foo")
assert args.skip_pip is False
assert args.skip_pip_packages == ["foo"]
args = parse_args("--skip-pip-packages", "foo-asd,bar-xyz")
assert args.skip_pip is False
assert args.skip_pip_packages == ["foo-asd", "bar-xyz"]
assert mock_exit.called is False
args = parse_args("--skip-pip", "--skip-pip-packages", "foo")
assert mock_exit.called is True |
Return env without wheel links. | def env_without_wheel_links():
"""Return env without wheel links."""
env = dict(os.environ)
env.pop("WHEEL_LINKS", None)
return env |
Test we can run. | def test_run(hass: HomeAssistant, tmpdir: py.path.local) -> None:
"""Test we can run."""
test_dir = tmpdir.mkdir("config")
default_config = runner.RuntimeConfig(test_dir)
with (
patch.object(runner, "TASK_CANCELATION_TIMEOUT", 1),
patch("homeassistant.bootstrap.async_setup_hass", return_value=hass),
patch("threading._shutdown"),
patch("homeassistant.core.HomeAssistant.async_run") as mock_run,
):
runner.run(default_config)
assert mock_run.called |
Test we can run and we still shutdown if the executor shutdown throws. | def test_run_executor_shutdown_throws(
hass: HomeAssistant, tmpdir: py.path.local
) -> None:
"""Test we can run and we still shutdown if the executor shutdown throws."""
test_dir = tmpdir.mkdir("config")
default_config = runner.RuntimeConfig(test_dir)
with (
patch.object(runner, "TASK_CANCELATION_TIMEOUT", 1),
pytest.raises(RuntimeError),
patch("homeassistant.bootstrap.async_setup_hass", return_value=hass),
patch("threading._shutdown"),
patch(
"homeassistant.runner.InterruptibleThreadPoolExecutor.shutdown",
side_effect=RuntimeError,
) as mock_shutdown,
patch(
"homeassistant.core.HomeAssistant.async_run",
) as mock_run,
):
runner.run(default_config)
assert mock_shutdown.called
assert mock_run.called |
Test we can shutdown and not block forever. | def test_run_does_not_block_forever_with_shielded_task(
hass: HomeAssistant, tmpdir: py.path.local, caplog: pytest.LogCaptureFixture
) -> None:
"""Test we can shutdown and not block forever."""
test_dir = tmpdir.mkdir("config")
default_config = runner.RuntimeConfig(test_dir)
tasks = []
async def _async_create_tasks(*_):
async def async_raise(*_):
try:
await asyncio.sleep(2)
except asyncio.CancelledError:
raise Exception
async def async_shielded(*_):
try:
await asyncio.sleep(2)
except asyncio.CancelledError:
await asyncio.sleep(2)
tasks.append(asyncio.ensure_future(asyncio.shield(async_shielded())))
tasks.append(asyncio.ensure_future(asyncio.sleep(2)))
tasks.append(asyncio.ensure_future(async_raise()))
await asyncio.sleep(0.1)
return 0
with (
patch.object(runner, "TASK_CANCELATION_TIMEOUT", 1),
patch("homeassistant.bootstrap.async_setup_hass", return_value=hass),
patch("threading._shutdown"),
patch("homeassistant.core.HomeAssistant.async_run", _async_create_tasks),
):
runner.run(default_config)
assert len(tasks) == 3
assert (
"Task could not be canceled and was still running after shutdown" in caplog.text
) |
Test that we can enable posix_spawn on musllinux. | def test__enable_posix_spawn() -> None:
"""Test that we can enable posix_spawn on musllinux."""
def _mock_sys_tags_any() -> Iterator[packaging.tags.Tag]:
yield from packaging.tags.parse_tag("py3-none-any")
def _mock_sys_tags_musl() -> Iterator[packaging.tags.Tag]:
yield from packaging.tags.parse_tag("cp311-cp311-musllinux_1_1_x86_64")
with (
patch.object(runner.subprocess, "_USE_POSIX_SPAWN", False),
patch(
"homeassistant.runner.packaging.tags.sys_tags",
side_effect=_mock_sys_tags_musl,
),
):
runner._enable_posix_spawn()
assert runner.subprocess._USE_POSIX_SPAWN is True
with (
patch.object(runner.subprocess, "_USE_POSIX_SPAWN", False),
patch(
"homeassistant.runner.packaging.tags.sys_tags",
side_effect=_mock_sys_tags_any,
),
):
runner._enable_posix_spawn()
assert runner.subprocess._USE_POSIX_SPAWN is False |
Mock config flows. | def mock_handlers():
"""Mock config flows."""
class MockFlowHandler(config_entries.ConfigFlow):
"""Define a mock flow handler."""
VERSION = 1
with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}):
yield |
Test we can't open sockets. | def test_sockets_disabled() -> None:
"""Test we can't open sockets."""
with pytest.raises(pytest_socket.SocketBlockedError):
socket.socket() |
Test we can't connect to an address different from 127.0.0.1. | def test_sockets_enabled(socket_enabled) -> None:
"""Test we can't connect to an address different from 127.0.0.1."""
mysocket = socket.socket()
with pytest.raises(pytest_socket.SocketConnectBlockedError):
mysocket.connect(("127.0.0.2", 1234)) |
Register a view. | def register_view(hass: HomeAssistant) -> None:
"""Register a view."""
class TestView(HomeAssistantView):
"""Test view to serve the test."""
requires_auth = False
url = "/api/test"
name = "api:test"
async def get(self, request: web.Request) -> web.Response:
"""Return a test result."""
return self.json({"test": True})
hass.http.register_view(TestView()) |
Home Assistant mock with minimum amount of data set to make it work with auth. | def mock_hass(hass: HomeAssistant) -> HomeAssistant:
"""Home Assistant mock with minimum amount of data set to make it work with auth."""
return hass |
Test we fetch the owner permissions for an owner user. | def test_owner_fetching_owner_permissions() -> None:
"""Test we fetch the owner permissions for an owner user."""
group = models.Group(name="Test Group", policy={})
owner = models.User(
name="Test User", perm_lookup=None, groups=[group], is_owner=True
)
assert owner.permissions is permissions.OwnerPermissions |
Test we merge the groups permissions. | def test_permissions_merged() -> None:
"""Test we merge the groups permissions."""
group = models.Group(
name="Test Group", policy={"entities": {"domains": {"switch": True}}}
)
group2 = models.Group(
name="Test Group", policy={"entities": {"entity_ids": {"light.kitchen": True}}}
)
user = models.User(name="Test User", perm_lookup=None, groups=[group, group2])
# Make sure we cache instance
assert user.permissions is user.permissions
assert user.permissions.check_entity("switch.bla", "read") is True
assert user.permissions.check_entity("light.kitchen", "read") is True
assert user.permissions.check_entity("light.not_kitchen", "read") is False |
Test we clear the cache when a group changes. | def test_cache_cleared_on_group_change() -> None:
"""Test we clear the cache when a group changes."""
group = models.Group(
name="Test Group", policy={"entities": {"domains": {"switch": True}}}
)
admin_group = models.Group(
name="Admin group", id=models.GROUP_ID_ADMIN, policy={"entities": {}}
)
user = models.User(
name="Test User", perm_lookup=None, groups=[group], is_active=True
)
# Make sure we cache instance
assert user.permissions is user.permissions
# Make sure we cache is_admin
assert user.is_admin is user.is_admin
assert user.is_active is True
user.groups = []
assert user.groups == []
assert user.is_admin is False
user.is_owner = True
assert user.is_admin is True
user.is_owner = False
assert user.is_admin is False
user.groups = [admin_group]
assert user.is_admin is True
user.is_active = False
assert user.is_admin is False |
Test entity ID policy. | def test_entities_none() -> None:
"""Test entity ID policy."""
policy = None
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is False |
Test entity ID policy. | def test_entities_empty() -> None:
"""Test entity ID policy."""
policy = {}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is False |
Test entity ID policy. | def test_entities_false() -> None:
"""Test entity ID policy."""
policy = False
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy) |
Test entity ID policy. | def test_entities_true() -> None:
"""Test entity ID policy."""
policy = True
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True |
Test entity ID policy. | def test_entities_domains_true() -> None:
"""Test entity ID policy."""
policy = {"domains": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True |
Test entity ID policy. | def test_entities_domains_domain_true() -> None:
"""Test entity ID policy."""
policy = {"domains": {"light": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("switch.kitchen", "read") is False |
Test entity ID policy. | def test_entities_domains_domain_false() -> None:
"""Test entity ID policy."""
policy = {"domains": {"light": False}}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy) |
Test entity ID policy. | def test_entities_entity_ids_true() -> None:
"""Test entity ID policy."""
policy = {"entity_ids": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True |
Test entity ID policy. | def test_entities_entity_ids_false() -> None:
"""Test entity ID policy."""
policy = {"entity_ids": False}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy) |
Test entity ID policy. | def test_entities_entity_ids_entity_id_true() -> None:
"""Test entity ID policy."""
policy = {"entity_ids": {"light.kitchen": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("switch.kitchen", "read") is False |
Test entity ID policy. | def test_entities_entity_ids_entity_id_false() -> None:
"""Test entity ID policy."""
policy = {"entity_ids": {"light.kitchen": False}}
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy) |
Test policy granting control only. | def test_entities_control_only() -> None:
"""Test policy granting control only."""
policy = {"entity_ids": {"light.kitchen": {"read": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("light.kitchen", "control") is False
assert compiled("light.kitchen", "edit") is False |
Test policy granting control only. | def test_entities_read_control() -> None:
"""Test policy granting control only."""
policy = {"domains": {"light": {"read": True, "control": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("light.kitchen", "control") is True
assert compiled("light.kitchen", "edit") is False |
Test policy allowing all entities. | def test_entities_all_allow() -> None:
"""Test policy allowing all entities."""
policy = {"all": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("light.kitchen", "control") is True
assert compiled("switch.kitchen", "read") is True |
Test policy applying read to all entities. | def test_entities_all_read() -> None:
"""Test policy applying read to all entities."""
policy = {"all": {"read": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True
assert compiled("light.kitchen", "control") is False
assert compiled("switch.kitchen", "read") is True |
Test entity ID policy applying control to all. | def test_entities_all_control() -> None:
"""Test entity ID policy applying control to all."""
policy = {"all": {"control": True}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is False
assert compiled("light.kitchen", "control") is True
assert compiled("switch.kitchen", "read") is False
assert compiled("switch.kitchen", "control") is True |
Test entity ID policy applying control on device id. | def test_entities_device_id_boolean(hass: HomeAssistant) -> None:
"""Test entity ID policy applying control on device id."""
entity_registry = mock_registry(
hass,
{
"test_domain.allowed": RegistryEntry(
entity_id="test_domain.allowed",
unique_id="1234",
platform="test_platform",
device_id="mock-allowed-dev-id",
),
"test_domain.not_allowed": RegistryEntry(
entity_id="test_domain.not_allowed",
unique_id="5678",
platform="test_platform",
device_id="mock-not-allowed-dev-id",
),
},
)
device_registry = mock_device_registry(hass)
policy = {"device_ids": {"mock-allowed-dev-id": {"read": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(
policy, PermissionLookup(entity_registry, device_registry)
)
assert compiled("test_domain.allowed", "read") is True
assert compiled("test_domain.allowed", "control") is False
assert compiled("test_domain.not_allowed", "read") is False
assert compiled("test_domain.not_allowed", "control") is False |
Test entity ID policy for areas. | def test_entities_areas_true() -> None:
"""Test entity ID policy for areas."""
policy = {"area_ids": True}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(policy, None)
assert compiled("light.kitchen", "read") is True |
Test entity ID policy for areas with specific area. | def test_entities_areas_area_true(hass: HomeAssistant) -> None:
"""Test entity ID policy for areas with specific area."""
entity_registry = mock_registry(
hass,
{
"light.kitchen": RegistryEntry(
entity_id="light.kitchen",
unique_id="1234",
platform="test_platform",
device_id="mock-dev-id",
)
},
)
device_registry = mock_device_registry(
hass, {"mock-dev-id": DeviceEntry(id="mock-dev-id", area_id="mock-area-id")}
)
policy = {"area_ids": {"mock-area-id": {"read": True, "control": True}}}
ENTITY_POLICY_SCHEMA(policy)
compiled = compile_entities(
policy, PermissionLookup(entity_registry, device_registry)
)
assert compiled("light.kitchen", "read") is True
assert compiled("light.kitchen", "control") is True
assert compiled("light.kitchen", "edit") is False
assert compiled("switch.kitchen", "read") is False |
Test merging policy with two entities. | def test_merging_permissions_true_rules_dict() -> None:
"""Test merging policy with two entities."""
policy1 = {
"something_else": True,
"entities": {"entity_ids": {"light.kitchen": True}},
}
policy2 = {"entities": {"entity_ids": True}}
assert merge_policies([policy1, policy2]) == {
"something_else": True,
"entities": {"entity_ids": True},
} |
Test merging policy with two entities. | def test_merging_permissions_multiple_subcategories() -> None:
"""Test merging policy with two entities."""
policy1 = {"entities": None}
policy2 = {"entities": {"entity_ids": True}}
policy3 = {"entities": True}
assert merge_policies([policy1, policy2]) == policy2
assert merge_policies([policy1, policy3]) == policy3
assert merge_policies([policy2, policy3]) == policy3 |
Test admin policy works. | def test_admin_policy() -> None:
"""Test admin policy works."""
# Make sure it's valid
POLICY_SCHEMA(system_policies.ADMIN_POLICY)
perms = PolicyPermissions(system_policies.ADMIN_POLICY, None)
assert perms.check_entity("light.kitchen", "read")
assert perms.check_entity("light.kitchen", "control")
assert perms.check_entity("light.kitchen", "edit") |
Test user policy works. | def test_user_policy() -> None:
"""Test user policy works."""
# Make sure it's valid
POLICY_SCHEMA(system_policies.USER_POLICY)
perms = PolicyPermissions(system_policies.USER_POLICY, None)
assert perms.check_entity("light.kitchen", "read")
assert perms.check_entity("light.kitchen", "control")
assert perms.check_entity("light.kitchen", "edit") |
Test read only policy works. | def test_read_only_policy() -> None:
"""Test read only policy works."""
# Make sure it's valid
POLICY_SCHEMA(system_policies.READ_ONLY_POLICY)
perms = PolicyPermissions(system_policies.READ_ONLY_POLICY, None)
assert perms.check_entity("light.kitchen", "read")
assert not perms.check_entity("light.kitchen", "control")
assert not perms.check_entity("light.kitchen", "edit") |
Test if we can test the all group. | def test_test_all() -> None:
"""Test if we can test the all group."""
for val in (None, {}, {"all": None}, {"all": {}}):
assert util.test_all(val, "read") is False
for val in (True, {"all": True}, {"all": {"read": True}}):
assert util.test_all(val, "read") is True |
Mock provider. | def provider(hass, store):
"""Mock provider."""
return command_line.CommandLineAuthProvider(
hass,
store,
{
CONF_TYPE: "command_line",
command_line.CONF_COMMAND: os.path.join(
os.path.dirname(__file__), "test_command_line_cmd.sh"
),
command_line.CONF_ARGS: [],
command_line.CONF_META: False,
},
) |
Mock manager. | def manager(hass, store, provider):
"""Mock manager."""
return AuthManager(hass, store, {(provider.type, provider.id): provider}, {}) |
Create a loaded data class. | def data(hass):
"""Create a loaded data class."""
data = hass_auth.Data(hass)
hass.loop.run_until_complete(data.async_load())
return data |
Create a loaded legacy data class. | def legacy_data(hass):
"""Create a loaded legacy data class."""
data = hass_auth.Data(hass)
hass.loop.run_until_complete(data.async_load())
data.is_legacy = True
return data |
Mock provider. | def provider(hass, store):
"""Mock provider."""
return insecure_example.ExampleAuthProvider(
hass,
store,
{
"type": "insecure_example",
"users": [
{
"name": "Test Name",
"username": "user-test",
"password": "password-test",
},
{"username": "🎉", "password": "😎"},
],
},
) |
Mock manager. | def manager(hass, store, provider):
"""Mock manager."""
return AuthManager(hass, store, {(provider.type, provider.id): provider}, {}) |
Mock provider. | def provider(hass, store):
"""Mock provider."""
return legacy_api_password.LegacyApiPasswordAuthProvider(hass, store, CONFIG) |
Mock manager. | def manager(hass, store, provider):
"""Mock manager."""
return auth.AuthManager(hass, store, {(provider.type, provider.id): provider}, {}) |
Mock provider. | def provider(hass, store):
"""Mock provider."""
return tn_auth.TrustedNetworksAuthProvider(
hass,
store,
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": [
"192.168.0.1",
"192.168.128.0/24",
"::1",
"fd00::/8",
],
}
),
) |
Mock provider with trusted users config. | def provider_with_user(hass, store):
"""Mock provider with trusted users config."""
return tn_auth.TrustedNetworksAuthProvider(
hass,
store,
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": [
"192.168.0.1",
"192.168.128.0/24",
"::1",
"fd00::/8",
],
# user_id will be injected in test
"trusted_users": {
"192.168.0.1": [],
"192.168.128.0/24": [],
"fd00::/8": [],
},
}
),
) |
Mock provider with allow_bypass_login config. | def provider_bypass_login(hass, store):
"""Mock provider with allow_bypass_login config."""
return tn_auth.TrustedNetworksAuthProvider(
hass,
store,
tn_auth.CONFIG_SCHEMA(
{
"type": "trusted_networks",
"trusted_networks": [
"192.168.0.1",
"192.168.128.0/24",
"::1",
"fd00::/8",
],
"allow_bypass_login": True,
}
),
) |
Mock manager. | def manager(hass, store, provider):
"""Mock manager."""
return auth.AuthManager(hass, store, {(provider.type, provider.id): provider}, {}) |
Mock manager with trusted user. | def manager_with_user(hass, store, provider_with_user):
"""Mock manager with trusted user."""
return auth.AuthManager(
hass,
store,
{(provider_with_user.type, provider_with_user.id): provider_with_user},
{},
) |
Mock manager with allow bypass login. | def manager_bypass_login(hass, store, provider_bypass_login):
"""Mock manager with allow bypass login."""
return auth.AuthManager(
hass,
store,
{(provider_bypass_login.type, provider_bypass_login.id): provider_bypass_login},
{},
) |
Patch zeroconf wrapper that detects if multiple instances are used. | def patch_zeroconf_multiple_catcher() -> Generator[None, None, None]:
"""Patch zeroconf wrapper that detects if multiple instances are used."""
with patch(
"homeassistant.components.zeroconf.install_multiple_zeroconf_catcher",
side_effect=lambda zc: None,
):
yield |
Fixture to prevent certain I/O from happening. | def prevent_io() -> Generator[None, None, None]:
"""Fixture to prevent certain I/O from happening."""
with patch(
"homeassistant.components.http.ban.load_yaml_config_file",
):
yield |
Test fixture that ensures all entities are enabled in the registry. | def entity_registry_enabled_by_default() -> Generator[None, None, None]:
"""Test fixture that ensures all entities are enabled in the registry."""
with patch(
"homeassistant.helpers.entity.Entity.entity_registry_enabled_default",
return_value=True,
):
yield |
Stub copying the blueprints to the config folder. | def stub_blueprint_populate_fixture() -> Generator[None, Any, None]:
"""Stub copying the blueprints to the config folder."""
from tests.components.blueprint.common import stub_blueprint_populate_fixture_helper
yield from stub_blueprint_populate_fixture_helper() |
Mock the list TTS cache function. | def mock_tts_get_cache_files_fixture():
"""Mock the list TTS cache function."""
from tests.components.tts.common import mock_tts_get_cache_files_fixture_helper
yield from mock_tts_get_cache_files_fixture_helper() |
Mock the TTS cache dir in memory. | def mock_tts_init_cache_dir_fixture(
init_tts_cache_dir_side_effect: Any,
) -> Generator[MagicMock, None, None]:
"""Mock the TTS cache dir in memory."""
from tests.components.tts.common import mock_tts_init_cache_dir_fixture_helper
yield from mock_tts_init_cache_dir_fixture_helper(init_tts_cache_dir_side_effect) |
Return the cache dir. | def init_tts_cache_dir_side_effect_fixture() -> Any:
"""Return the cache dir."""
from tests.components.tts.common import (
init_tts_cache_dir_side_effect_fixture_helper,
)
return init_tts_cache_dir_side_effect_fixture_helper() |
Mock the TTS cache dir with empty dir. | def mock_tts_cache_dir_fixture(
tmp_path, mock_tts_init_cache_dir, mock_tts_get_cache_files, request
):
"""Mock the TTS cache dir with empty dir."""
from tests.components.tts.common import mock_tts_cache_dir_fixture_helper
yield from mock_tts_cache_dir_fixture_helper(
tmp_path, mock_tts_init_cache_dir, mock_tts_get_cache_files, request
) |
Mock writing tags. | def tts_mutagen_mock_fixture():
"""Mock writing tags."""
from tests.components.tts.common import tts_mutagen_mock_fixture_helper
yield from tts_mutagen_mock_fixture_helper() |
Mock a conversation agent. | def mock_conversation_agent_fixture(hass: HomeAssistant) -> MockAgent:
"""Mock a conversation agent."""
from tests.components.conversation.common import (
mock_conversation_agent_fixture_helper,
)
return mock_conversation_agent_fixture_helper(hass) |
Prevent ffmpeg from creating a subprocess. | def prevent_ffmpeg_subprocess() -> Generator[None, None, None]:
"""Prevent ffmpeg from creating a subprocess."""
with patch(
"homeassistant.components.ffmpeg.FFVersion.get_version", return_value="6.0"
):
yield |
Return mocked light entities. | def mock_light_entities() -> list["MockLight"]:
"""Return mocked light entities."""
from tests.components.light.common import MockLight
return [
MockLight("Ceiling", STATE_ON),
MockLight("Ceiling", STATE_OFF),
MockLight(None, STATE_OFF),
] |
Return mocked sensor entities. | def mock_sensor_entities() -> dict[str, "MockSensor"]:
"""Return mocked sensor entities."""
from tests.components.sensor.common import get_mock_sensor_entities
return get_mock_sensor_entities() |
Return mocked toggle entities. | def mock_switch_entities() -> list["MockSwitch"]:
"""Return mocked toggle entities."""
from tests.components.switch.common import get_mock_switch_entities
return get_mock_switch_entities() |
Return mocked legacy device scanner entity. | def mock_legacy_device_scanner() -> "MockScanner":
"""Return mocked legacy device scanner entity."""
from tests.components.device_tracker.common import MockScanner
return MockScanner() |
Return setup callable for legacy device tracker setup. | def mock_legacy_device_tracker_setup() -> (
Callable[[HomeAssistant, "MockScanner"], None]
):
"""Return setup callable for legacy device tracker setup."""
from tests.components.device_tracker.common import mock_legacy_device_tracker_setup
return mock_legacy_device_tracker_setup |
Override async_setup_entry. | def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.abode.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry |
Fixture to provide a requests mocker. | def requests_mock_fixture(requests_mock) -> None:
"""Fixture to provide a requests mocker."""
# Mocks the login response for abodepy.
requests_mock.post(URL.LOGIN, text=load_fixture("login.json", "abode"))
# Mocks the logout response for abodepy.
requests_mock.post(URL.LOGOUT, text=load_fixture("logout.json", "abode"))
# Mocks the oauth claims response for abodepy.
requests_mock.get(URL.OAUTH_TOKEN, text=load_fixture("oauth_claims.json", "abode"))
# Mocks the panel response for abodepy.
requests_mock.get(URL.PANEL, text=load_fixture("panel.json", "abode"))
# Mocks the automations response for abodepy.
requests_mock.get(URL.AUTOMATION, text=load_fixture("automation.json", "abode"))
# Mocks the devices response for abodepy.
requests_mock.get(URL.DEVICES, text=load_fixture("devices.json", "abode")) |
Mock the hub discover method. | def mock_hub_discover():
"""Mock the hub discover method."""
with patch("aiopulse.Hub.discover") as mock_discover:
yield mock_discover |
Mock the hub run method. | def mock_hub_run():
"""Mock the hub run method."""
with patch("aiopulse.Hub.run") as mock_run:
yield mock_run |
Fixture to patch the Advantage Air async_get method. | def mock_get():
"""Fixture to patch the Advantage Air async_get method."""
with patch_get() as mock_get:
yield mock_get |
Fixture to patch the Advantage Air async_get method. | def mock_update():
"""Fixture to patch the Advantage Air async_get method."""
with patch_update() as mock_get:
yield mock_get |
Patch the Advantage Air async_get method. | def patch_get(return_value=TEST_SYSTEM_DATA, side_effect=None):
"""Patch the Advantage Air async_get method."""
return patch(
"homeassistant.components.advantage_air.advantage_air.async_get",
new=AsyncMock(return_value=return_value, side_effect=side_effect),
) |
Patch the Advantage Air async_set method. | def patch_update(return_value=True, side_effect=None):
"""Patch the Advantage Air async_set method."""
return patch(
"homeassistant.components.advantage_air.advantage_air._endpoint.async_update",
new=AsyncMock(return_value=return_value, side_effect=side_effect),
) |
Override async_setup_entry. | def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.aemet.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry |
Mock AEMET OpenData API calls. | def mock_api_call(cmd: str, fetch_data: bool = False) -> dict[str, Any]:
"""Mock AEMET OpenData API calls."""
if cmd == "maestro/municipio/id28065":
return TOWN_DATA_MOCK
if cmd == "maestro/municipios":
return TOWNS_DATA_MOCK
if cmd == "observacion/convencional/datos/estacion/3195":
return STATION_DATA_MOCK
if cmd == "observacion/convencional/todas":
return STATIONS_DATA_MOCK
if cmd == "prediccion/especifica/municipio/diaria/28065":
return FORECAST_DAILY_DATA_MOCK
if cmd == "prediccion/especifica/municipio/horaria/28065":
return FORECAST_HOURLY_DATA_MOCK
return {} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.