response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Home Assistant fixture with history.
def hass_history(hass_recorder): """Home Assistant fixture with history.""" hass = hass_recorder() config = history.CONFIG_SCHEMA( { history.DOMAIN: { CONF_INCLUDE: { CONF_DOMAINS: ["media_player"], CONF_ENTITIES: ["thermostat.test"], }, CONF_EXCLUDE: { CONF_DOMAINS: ["thermostat"], CONF_ENTITIES: ["media_player.test"], }, } } ) assert setup_component(hass, history.DOMAIN, config) return hass
Return listeners without final write listeners since we are not testing for these.
def listeners_without_writes(listeners: dict[str, int]) -> dict[str, int]: """Return listeners without final write listeners since we are not testing for these.""" return { key: value for key, value in listeners.items() if key != EVENT_HOMEASSISTANT_FINAL_WRITE }
Test setup method of history.
def test_setup() -> None: """Test setup method of history."""
Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned).
def test_get_significant_states(hass_history) -> None: """Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned). """ hass = hass_history zero, four, states = record_states(hass) hist = get_significant_states(hass, zero, four, entity_ids=list(states)) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Test that only significant states are returned. When minimal responses is set only the first and last states return a complete state. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned).
def test_get_significant_states_minimal_response(hass_history) -> None: """Test that only significant states are returned. When minimal responses is set only the first and last states return a complete state. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned). """ hass = hass_history zero, four, states = record_states(hass) hist = get_significant_states( hass, zero, four, minimal_response=True, entity_ids=list(states) ) entites_with_reducable_states = [ "media_player.test", "media_player.test3", ] # All states for media_player.test state are reduced # down to last_changed and state when minimal_response # is set except for the first state. # is set. We use JSONEncoder to make sure that are # pre-encoded last_changed is always the same as what # will happen with encoding a native state for entity_id in entites_with_reducable_states: entity_states = states[entity_id] for state_idx in range(1, len(entity_states)): input_state = entity_states[state_idx] orig_last_changed = json.dumps( process_timestamp(input_state.last_changed), cls=JSONEncoder, ).replace('"', "") orig_state = input_state.state entity_states[state_idx] = { "last_changed": orig_last_changed, "state": orig_state, } assert len(hist) == len(states) assert_states_equal_without_context( states["media_player.test"][0], hist["media_player.test"][0] ) assert states["media_player.test"][1] == hist["media_player.test"][1] assert states["media_player.test"][2] == hist["media_player.test"][2] assert_multiple_states_equal_without_context( states["media_player.test2"], hist["media_player.test2"] ) assert_states_equal_without_context( states["media_player.test3"][0], hist["media_player.test3"][0] ) assert states["media_player.test3"][1] == hist["media_player.test3"][1] assert_multiple_states_equal_without_context( states["script.can_cancel_this_one"], hist["script.can_cancel_this_one"] ) assert_multiple_states_equal_without_context_and_last_changed( states["thermostat.test"], hist["thermostat.test"] ) assert_multiple_states_equal_without_context_and_last_changed( states["thermostat.test2"], hist["thermostat.test2"] )
Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned).
def test_get_significant_states_with_initial(hass_history) -> None: """Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned). """ hass = hass_history zero, four, states = record_states(hass) one_and_half = zero + timedelta(seconds=1.5) for entity_id in states: if entity_id == "media_player.test": states[entity_id] = states[entity_id][1:] for state in states[entity_id]: # If the state is recorded before the start time # start it will have its last_updated and last_changed # set to the start time. if state.last_updated < one_and_half: state.last_updated = one_and_half state.last_changed = one_and_half hist = get_significant_states( hass, one_and_half, four, include_start_time_state=True, entity_ids=list(states) ) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned).
def test_get_significant_states_without_initial(hass_history) -> None: """Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned). """ hass = hass_history zero, four, states = record_states(hass) one = zero + timedelta(seconds=1) one_with_microsecond = zero + timedelta(seconds=1, microseconds=1) one_and_half = zero + timedelta(seconds=1.5) for entity_id in states: states[entity_id] = [ s for s in states[entity_id] if s.last_changed not in (one, one_with_microsecond) ] del states["media_player.test2"] hist = get_significant_states( hass, one_and_half, four, include_start_time_state=False, entity_ids=list(states), ) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Test that only significant states are returned for one entity.
def test_get_significant_states_entity_id(hass_history) -> None: """Test that only significant states are returned for one entity.""" hass = hass_history zero, four, states = record_states(hass) del states["media_player.test2"] del states["media_player.test3"] del states["thermostat.test"] del states["thermostat.test2"] del states["script.can_cancel_this_one"] hist = get_significant_states(hass, zero, four, ["media_player.test"]) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Test that only significant states are returned for one entity.
def test_get_significant_states_multiple_entity_ids(hass_history) -> None: """Test that only significant states are returned for one entity.""" hass = hass_history zero, four, states = record_states(hass) del states["media_player.test2"] del states["media_player.test3"] del states["thermostat.test2"] del states["script.can_cancel_this_one"] hist = get_significant_states( hass, zero, four, ["media_player.test", "thermostat.test"], ) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Test order of results from get_significant_states. When entity ids are given, the results should be returned with the data in the same order.
def test_get_significant_states_are_ordered(hass_history) -> None: """Test order of results from get_significant_states. When entity ids are given, the results should be returned with the data in the same order. """ hass = hass_history zero, four, _states = record_states(hass) entity_ids = ["media_player.test", "media_player.test2"] hist = get_significant_states(hass, zero, four, entity_ids) assert list(hist.keys()) == entity_ids entity_ids = ["media_player.test2", "media_player.test"] hist = get_significant_states(hass, zero, four, entity_ids) assert list(hist.keys()) == entity_ids
Test significant states when significant_states_only is set.
def test_get_significant_states_only(hass_history) -> None: """Test significant states when significant_states_only is set.""" hass = hass_history entity_id = "sensor.test" def set_state(state, **kwargs): """Set the state.""" hass.states.set(entity_id, state, **kwargs) wait_recording_done(hass) return hass.states.get(entity_id) start = dt_util.utcnow() - timedelta(minutes=4) points = [start + timedelta(minutes=i) for i in range(1, 4)] states = [] with freeze_time(start) as freezer: set_state("123", attributes={"attribute": 10.64}) freezer.move_to(points[0]) # Attributes are different, state not states.append(set_state("123", attributes={"attribute": 21.42})) freezer.move_to(points[1]) # state is different, attributes not states.append(set_state("32", attributes={"attribute": 21.42})) freezer.move_to(points[2]) # everything is different states.append(set_state("412", attributes={"attribute": 54.23})) hist = get_significant_states( hass, start, significant_changes_only=True, entity_ids=list({state.entity_id for state in states}), ) assert len(hist[entity_id]) == 2 assert not any( state.last_updated == states[0].last_updated for state in hist[entity_id] ) assert any( state.last_updated == states[1].last_updated for state in hist[entity_id] ) assert any( state.last_updated == states[2].last_updated for state in hist[entity_id] ) hist = get_significant_states( hass, start, significant_changes_only=False, entity_ids=list({state.entity_id for state in states}), ) assert len(hist[entity_id]) == 3 assert_multiple_states_equal_without_context_and_last_changed( states, hist[entity_id] )
Check if significant states are retrieved.
def check_significant_states(hass, zero, four, states, config): """Check if significant states are retrieved.""" hist = get_significant_states(hass, zero, four) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Record some test states. We inject a bunch of state updates from media player, zone and thermostat.
def record_states(hass): """Record some test states. We inject a bunch of state updates from media player, zone and thermostat. """ mp = "media_player.test" mp2 = "media_player.test2" mp3 = "media_player.test3" therm = "thermostat.test" therm2 = "thermostat.test2" zone = "zone.home" script_c = "script.can_cancel_this_one" def set_state(entity_id, state, **kwargs): """Set the state.""" hass.states.set(entity_id, state, **kwargs) wait_recording_done(hass) return hass.states.get(entity_id) zero = dt_util.utcnow() one = zero + timedelta(seconds=1) two = one + timedelta(seconds=1) three = two + timedelta(seconds=1) four = three + timedelta(seconds=1) states = {therm: [], therm2: [], mp: [], mp2: [], mp3: [], script_c: []} with freeze_time(one) as freezer: states[mp].append( set_state(mp, "idle", attributes={"media_title": str(sentinel.mt1)}) ) states[mp2].append( set_state(mp2, "YouTube", attributes={"media_title": str(sentinel.mt2)}) ) states[mp3].append( set_state(mp3, "idle", attributes={"media_title": str(sentinel.mt1)}) ) states[therm].append( set_state(therm, 20, attributes={"current_temperature": 19.5}) ) freezer.move_to(one + timedelta(microseconds=1)) states[mp].append( set_state(mp, "YouTube", attributes={"media_title": str(sentinel.mt2)}) ) freezer.move_to(two) # This state will be skipped only different in time set_state(mp, "YouTube", attributes={"media_title": str(sentinel.mt3)}) # This state will be skipped because domain is excluded set_state(zone, "zoning") states[script_c].append( set_state(script_c, "off", attributes={"can_cancel": True}) ) states[therm].append( set_state(therm, 21, attributes={"current_temperature": 19.8}) ) states[therm2].append( set_state(therm2, 20, attributes={"current_temperature": 19}) ) freezer.move_to(three) states[mp].append( set_state(mp, "Netflix", attributes={"media_title": str(sentinel.mt4)}) ) states[mp3].append( set_state(mp3, "Netflix", attributes={"media_title": str(sentinel.mt3)}) ) # Attributes changed even though state is the same states[therm].append( set_state(therm, 21, attributes={"current_temperature": 20}) ) return zero, four, states
Fixture to initialize the db with the old schema 30.
def db_schema_30(): """Fixture to initialize the db with the old schema 30.""" with old_db_schema("30"): yield
Home Assistant fixture to use legacy history recording.
def legacy_hass_history(hass_history): """Home Assistant fixture to use legacy history recording.""" instance = recorder.get_instance(hass_history) with patch.object(instance.states_meta_manager, "active", False): yield hass_history
Test setup method of history.
def test_setup() -> None: """Test setup method of history."""
Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned).
def test_get_significant_states(legacy_hass_history) -> None: """Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned). """ hass = legacy_hass_history zero, four, states = record_states(hass) hist = get_significant_states(hass, zero, four, entity_ids=list(states)) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Test that only significant states are returned. When minimal responses is set only the first and last states return a complete state. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned).
def test_get_significant_states_minimal_response(legacy_hass_history) -> None: """Test that only significant states are returned. When minimal responses is set only the first and last states return a complete state. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned). """ hass = legacy_hass_history zero, four, states = record_states(hass) hist = get_significant_states( hass, zero, four, minimal_response=True, entity_ids=list(states) ) entites_with_reducable_states = [ "media_player.test", "media_player.test3", ] # All states for media_player.test state are reduced # down to last_changed and state when minimal_response # is set except for the first state. # is set. We use JSONEncoder to make sure that are # pre-encoded last_changed is always the same as what # will happen with encoding a native state for entity_id in entites_with_reducable_states: entity_states = states[entity_id] for state_idx in range(1, len(entity_states)): input_state = entity_states[state_idx] orig_last_changed = json.dumps( process_timestamp(input_state.last_changed), cls=JSONEncoder, ).replace('"', "") orig_state = input_state.state entity_states[state_idx] = { "last_changed": orig_last_changed, "state": orig_state, } assert len(hist) == len(states) assert_states_equal_without_context( states["media_player.test"][0], hist["media_player.test"][0] ) assert states["media_player.test"][1] == hist["media_player.test"][1] assert states["media_player.test"][2] == hist["media_player.test"][2] assert_multiple_states_equal_without_context( states["media_player.test2"], hist["media_player.test2"] ) assert_states_equal_without_context( states["media_player.test3"][0], hist["media_player.test3"][0] ) assert states["media_player.test3"][1] == hist["media_player.test3"][1] assert_multiple_states_equal_without_context( states["script.can_cancel_this_one"], hist["script.can_cancel_this_one"] ) assert_multiple_states_equal_without_context_and_last_changed( states["thermostat.test"], hist["thermostat.test"] ) assert_multiple_states_equal_without_context_and_last_changed( states["thermostat.test2"], hist["thermostat.test2"] )
Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned).
def test_get_significant_states_with_initial(legacy_hass_history) -> None: """Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned). """ hass = legacy_hass_history zero, four, states = record_states(hass) one = zero + timedelta(seconds=1) one_with_microsecond = zero + timedelta(seconds=1, microseconds=1) one_and_half = zero + timedelta(seconds=1.5) for entity_id in states: if entity_id == "media_player.test": states[entity_id] = states[entity_id][1:] for state in states[entity_id]: if state.last_changed in (one, one_with_microsecond): state.last_changed = one_and_half state.last_updated = one_and_half hist = get_significant_states( hass, one_and_half, four, include_start_time_state=True, entity_ids=list(states), ) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned).
def test_get_significant_states_without_initial(legacy_hass_history) -> None: """Test that only significant states are returned. We should get back every thermostat change that includes an attribute change, but only the state updates for media player (attribute changes are not significant and not returned). """ hass = legacy_hass_history zero, four, states = record_states(hass) one = zero + timedelta(seconds=1) one_with_microsecond = zero + timedelta(seconds=1, microseconds=1) one_and_half = zero + timedelta(seconds=1.5) for entity_id in states: states[entity_id] = list( filter( lambda s: s.last_changed not in (one, one_with_microsecond), states[entity_id], ) ) del states["media_player.test2"] hist = get_significant_states( hass, one_and_half, four, include_start_time_state=False, entity_ids=list(states), ) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Test that only significant states are returned for one entity.
def test_get_significant_states_entity_id(hass_history) -> None: """Test that only significant states are returned for one entity.""" hass = hass_history instance = recorder.get_instance(hass) with patch.object(instance.states_meta_manager, "active", False): zero, four, states = record_states(hass) del states["media_player.test2"] del states["media_player.test3"] del states["thermostat.test"] del states["thermostat.test2"] del states["script.can_cancel_this_one"] hist = get_significant_states(hass, zero, four, ["media_player.test"]) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Test that only significant states are returned for one entity.
def test_get_significant_states_multiple_entity_ids(legacy_hass_history) -> None: """Test that only significant states are returned for one entity.""" hass = legacy_hass_history zero, four, states = record_states(hass) del states["media_player.test2"] del states["media_player.test3"] del states["thermostat.test2"] del states["script.can_cancel_this_one"] hist = get_significant_states( hass, zero, four, ["media_player.test", "thermostat.test"], ) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Test order of results from get_significant_states. When entity ids are given, the results should be returned with the data in the same order.
def test_get_significant_states_are_ordered(legacy_hass_history) -> None: """Test order of results from get_significant_states. When entity ids are given, the results should be returned with the data in the same order. """ hass = legacy_hass_history zero, four, _states = record_states(hass) entity_ids = ["media_player.test", "media_player.test2"] hist = get_significant_states(hass, zero, four, entity_ids) assert list(hist.keys()) == entity_ids entity_ids = ["media_player.test2", "media_player.test"] hist = get_significant_states(hass, zero, four, entity_ids) assert list(hist.keys()) == entity_ids
Test significant states when significant_states_only is set.
def test_get_significant_states_only(legacy_hass_history) -> None: """Test significant states when significant_states_only is set.""" hass = legacy_hass_history entity_id = "sensor.test" def set_state(state, **kwargs): """Set the state.""" hass.states.set(entity_id, state, **kwargs) wait_recording_done(hass) return hass.states.get(entity_id) start = dt_util.utcnow() - timedelta(minutes=4) points = [start + timedelta(minutes=i) for i in range(1, 4)] states = [] with freeze_time(start) as freezer: set_state("123", attributes={"attribute": 10.64}) freezer.move_to(points[0]) # Attributes are different, state not states.append(set_state("123", attributes={"attribute": 21.42})) freezer.move_to(points[1]) # state is different, attributes not states.append(set_state("32", attributes={"attribute": 21.42})) freezer.move_to(points[2]) # everything is different states.append(set_state("412", attributes={"attribute": 54.23})) hist = get_significant_states( hass, start, significant_changes_only=True, entity_ids=list({state.entity_id for state in states}), ) assert len(hist[entity_id]) == 2 assert not any( state.last_updated == states[0].last_updated for state in hist[entity_id] ) assert any( state.last_updated == states[1].last_updated for state in hist[entity_id] ) assert any( state.last_updated == states[2].last_updated for state in hist[entity_id] ) hist = get_significant_states( hass, start, significant_changes_only=False, entity_ids=list({state.entity_id for state in states}), ) assert len(hist[entity_id]) == 3 assert_multiple_states_equal_without_context_and_last_changed( states, hist[entity_id] )
Check if significant states are retrieved.
def check_significant_states(hass, zero, four, states, config): """Check if significant states are retrieved.""" hist = get_significant_states(hass, zero, four) assert_dict_of_states_equal_without_context_and_last_changed(states, hist)
Record some test states. We inject a bunch of state updates from media player, zone and thermostat.
def record_states(hass): """Record some test states. We inject a bunch of state updates from media player, zone and thermostat. """ mp = "media_player.test" mp2 = "media_player.test2" mp3 = "media_player.test3" therm = "thermostat.test" therm2 = "thermostat.test2" zone = "zone.home" script_c = "script.can_cancel_this_one" def set_state(entity_id, state, **kwargs): """Set the state.""" hass.states.set(entity_id, state, **kwargs) wait_recording_done(hass) return hass.states.get(entity_id) zero = dt_util.utcnow() one = zero + timedelta(seconds=1) two = one + timedelta(seconds=1) three = two + timedelta(seconds=1) four = three + timedelta(seconds=1) states = {therm: [], therm2: [], mp: [], mp2: [], mp3: [], script_c: []} with freeze_time(one) as freezer: states[mp].append( set_state(mp, "idle", attributes={"media_title": str(sentinel.mt1)}) ) states[mp2].append( set_state(mp2, "YouTube", attributes={"media_title": str(sentinel.mt2)}) ) states[mp3].append( set_state(mp3, "idle", attributes={"media_title": str(sentinel.mt1)}) ) states[therm].append( set_state(therm, 20, attributes={"current_temperature": 19.5}) ) freezer.move_to(one + timedelta(microseconds=1)) states[mp].append( set_state(mp, "YouTube", attributes={"media_title": str(sentinel.mt2)}) ) freezer.move_to(two) # This state will be skipped only different in time set_state(mp, "YouTube", attributes={"media_title": str(sentinel.mt3)}) # This state will be skipped because domain is excluded set_state(zone, "zoning") states[script_c].append( set_state(script_c, "off", attributes={"can_cancel": True}) ) states[therm].append( set_state(therm, 21, attributes={"current_temperature": 19.8}) ) states[therm2].append( set_state(therm2, 20, attributes={"current_temperature": 19}) ) freezer.move_to(three) states[mp].append( set_state(mp, "Netflix", attributes={"media_title": str(sentinel.mt4)}) ) states[mp3].append( set_state(mp3, "Netflix", attributes={"media_title": str(sentinel.mt3)}) ) # Attributes changed even though state is the same states[therm].append( set_state(therm, 21, attributes={"current_temperature": 20}) ) return zero, four, states
Return listeners without final write listeners since we are not testing for these.
def listeners_without_writes(listeners: dict[str, int]) -> dict[str, int]: """Return listeners without final write listeners since we are not testing for these.""" return { key: value for key, value in listeners.items() if key != EVENT_HOMEASSISTANT_FINAL_WRITE }
Test setup method of history.
def test_setup() -> None: """Test setup method of history."""
Fixture to initialize the db with the old schema 32.
def db_schema_32(): """Fixture to initialize the db with the old schema 32.""" with old_db_schema("32"): yield
Test the history statistics sensor setup with invalid config.
def test_setup_invalid_config(config) -> None: """Test the history statistics sensor setup with invalid config.""" with pytest.raises(vol.Invalid): SENSOR_SCHEMA(config)
Mock valid config flow setup.
def hko_config_flow_connect(): """Mock valid config flow setup.""" with patch( "homeassistant.components.hko.config_flow.HKO.weather", return_value=json.loads(load_fixture("hko/rhrread.json")), ): yield
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.holiday.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Set up the test environment.
def entities_fixture( hass: HomeAssistant, entity_registry: er.EntityRegistry, request: pytest.FixtureRequest, ) -> dict[str, str]: """Set up the test environment.""" if request.param == "entities_unique_id": return entities_unique_id(entity_registry) if request.param == "entities_no_unique_id": return entities_no_unique_id(hass) raise RuntimeError("Invalid setup fixture")
Create some entities in the entity registry.
def entities_unique_id(entity_registry: er.EntityRegistry) -> dict[str, str]: """Create some entities in the entity registry.""" entry_blocked = entity_registry.async_get_or_create( "group", "test", "unique", suggested_object_id="all_locks" ) assert entry_blocked.entity_id == CLOUD_NEVER_EXPOSED_ENTITIES[0] entry_lock = entity_registry.async_get_or_create("lock", "test", "unique1") entry_binary_sensor = entity_registry.async_get_or_create( "binary_sensor", "test", "unique1" ) entry_binary_sensor_door = entity_registry.async_get_or_create( "binary_sensor", "test", "unique2", original_device_class="door", ) entry_sensor = entity_registry.async_get_or_create("sensor", "test", "unique1") entry_sensor_temperature = entity_registry.async_get_or_create( "sensor", "test", "unique2", original_device_class="temperature", ) return { "blocked": entry_blocked.entity_id, "lock": entry_lock.entity_id, "binary_sensor": entry_binary_sensor.entity_id, "door_sensor": entry_binary_sensor_door.entity_id, "sensor": entry_sensor.entity_id, "temperature_sensor": entry_sensor_temperature.entity_id, }
Create some entities not in the entity registry.
def entities_no_unique_id(hass: HomeAssistant) -> dict[str, str]: """Create some entities not in the entity registry.""" blocked = CLOUD_NEVER_EXPOSED_ENTITIES[0] lock = "lock.test" binary_sensor = "binary_sensor.test" door_sensor = "binary_sensor.door" sensor = "sensor.test" sensor_temperature = "sensor.temperature" hass.states.async_set(binary_sensor, "on", {}) hass.states.async_set(door_sensor, "on", {"device_class": "door"}) hass.states.async_set(sensor, "on", {}) hass.states.async_set(sensor_temperature, "on", {"device_class": "temperature"}) return { "blocked": blocked, "lock": lock, "binary_sensor": binary_sensor, "door_sensor": door_sensor, "sensor": sensor, "temperature_sensor": sensor_temperature, }
Turn specified entity on if possible. This is a legacy helper method. Do not use it for new tests.
def turn_on(hass, entity_id=None, **service_data): """Turn specified entity on if possible. This is a legacy helper method. Do not use it for new tests. """ if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id hass.services.call(ha.DOMAIN, SERVICE_TURN_ON, service_data)
Turn specified entity off. This is a legacy helper method. Do not use it for new tests.
def turn_off(hass, entity_id=None, **service_data): """Turn specified entity off. This is a legacy helper method. Do not use it for new tests. """ if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id hass.services.call(ha.DOMAIN, SERVICE_TURN_OFF, service_data)
Toggle specified entity. This is a legacy helper method. Do not use it for new tests.
def toggle(hass, entity_id=None, **service_data): """Toggle specified entity. This is a legacy helper method. Do not use it for new tests. """ if entity_id is not None: service_data[ATTR_ENTITY_ID] = entity_id hass.services.call(ha.DOMAIN, SERVICE_TOGGLE, service_data)
Stop Home Assistant. This is a legacy helper method. Do not use it for new tests.
def stop(hass): """Stop Home Assistant. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_HOMEASSISTANT_STOP)
Stop Home Assistant. This is a legacy helper method. Do not use it for new tests.
def restart(hass): """Stop Home Assistant. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_HOMEASSISTANT_RESTART)
Check the config files. This is a legacy helper method. Do not use it for new tests.
def check_config(hass): """Check the config files. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_CHECK_CONFIG)
Reload the core config. This is a legacy helper method. Do not use it for new tests.
def reload_core_config(hass): """Reload the core config. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(ha.DOMAIN, SERVICE_RELOAD_CORE_CONFIG)
Test validators.
def test_validator() -> None: """Test validators.""" parsed = ha_scene.STATES_SCHEMA({"light.Test": {"state": "on"}}) assert len(parsed) == 1 assert "light.test" in parsed assert parsed["light.test"].entity_id == "light.test" assert parsed["light.test"].state == "on"
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Create a context with default user_id.
def context_with_user(): """Create a context with default user_id.""" return Context(user_id="test_user_id")
Initialize components.
def setup_comp(hass): """Initialize components.""" mock_component(hass, "group")
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Track calls to a mock service.
def calls(hass: HomeAssistant) -> list[ServiceCall]: """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Initialize components.
def setup_comp(hass): """Initialize components.""" mock_component(hass, "group") hass.states.async_set("test.entity", "hello")
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Initialize components.
def setup_comp(hass): """Initialize components.""" mock_component(hass, "group")
Make sure we don't accept number for 'at' value.
def test_schema_valid(conf) -> None: """Make sure we don't accept number for 'at' value.""" time.TRIGGER_SCHEMA(conf)
Make sure we don't accept number for 'at' value.
def test_schema_invalid(conf) -> None: """Make sure we don't accept number for 'at' value.""" with pytest.raises(vol.Invalid): time.TRIGGER_SCHEMA(conf)
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Initialize components.
def setup_comp(hass): """Initialize components.""" mock_component(hass, "group")
Stub an alert.
def stub_alert(aioclient_mock, alert_id): """Stub an alert.""" aioclient_mock.get( f"https://alerts.home-assistant.io/alerts/{alert_id}.json", json={"title": f"Title for {alert_id}", "content": f"Content for {alert_id}"}, )
Mock getting green settings.
def mock_get_green_settings(): """Mock getting green settings.""" with patch( "homeassistant.components.homeassistant_green.config_flow.async_get_green_settings", return_value={ "activity_led": True, "power_led": True, "system_health_led": True, }, ) as get_green_settings: yield get_green_settings
Mock setting green settings.
def mock_set_green_settings(): """Mock setting green settings.""" with patch( "homeassistant.components.homeassistant_green.config_flow.async_set_green_settings", ) as set_green_settings: yield set_green_settings
Mock the radio connection and probing of the ZHA config flow.
def mock_zha_config_flow_setup() -> Generator[None, None, None]: """Mock the radio connection and probing of the ZHA config flow.""" def mock_probe(config: dict[str, Any]) -> None: # The radio probing will return the correct baudrate return {**config, "baudrate": 115200} mock_connect_app = MagicMock() mock_connect_app.__aenter__.return_value.backups.backups = [MagicMock()] mock_connect_app.__aenter__.return_value.backups.create_backup.return_value = ( MagicMock() ) with ( patch( "bellows.zigbee.application.ControllerApplication.probe", side_effect=mock_probe, ), patch( "homeassistant.components.zha.radio_manager.ZhaRadioManager.connect_zigpy_app", return_value=mock_connect_app, ), patch( "homeassistant.components.zha.async_setup_entry", return_value=True, ), ): yield
Mock zha.api.async_get_last_network_settings.
def mock_zha_get_last_network_settings() -> Generator[None, None, None]: """Mock zha.api.async_get_last_network_settings.""" with patch( "homeassistant.components.zha.api.async_get_last_network_settings", AsyncMock(return_value=None), ): yield
Mock add-on already running.
def mock_addon_running(addon_store_info, addon_info): """Mock add-on already running.""" addon_store_info.return_value = { "installed": "1.0.0", "state": "started", "version": "1.0.0", } addon_info.return_value["hostname"] = "core-silabs-multiprotocol" addon_info.return_value["state"] = "started" addon_info.return_value["version"] = "1.0.0" return addon_info
Mock add-on already installed but not running.
def mock_addon_installed(addon_store_info, addon_info): """Mock add-on already installed but not running.""" addon_store_info.return_value = { "installed": "1.0.0", "state": "stopped", "version": "1.0.0", } addon_info.return_value["hostname"] = "core-silabs-multiprotocol" addon_info.return_value["state"] = "stopped" addon_info.return_value["version"] = "1.0.0" return addon_info
Mock Supervisor add-on store info.
def addon_store_info_fixture(): """Mock Supervisor add-on store info.""" with patch( "homeassistant.components.hassio.addon_manager.async_get_addon_store_info" ) as addon_store_info: addon_store_info.return_value = { "available": True, "installed": None, "state": None, "version": "1.0.0", } yield addon_store_info
Mock Supervisor add-on info.
def addon_info_fixture(): """Mock Supervisor add-on info.""" with patch( "homeassistant.components.hassio.addon_manager.async_get_addon_info", ) as addon_info: addon_info.return_value = { "available": True, "hostname": None, "options": {}, "state": None, "update_available": False, "version": None, } yield addon_info
Mock set add-on options.
def set_addon_options_fixture(): """Mock set add-on options.""" with patch( "homeassistant.components.hassio.addon_manager.async_set_addon_options" ) as set_options: yield set_options
Return the install add-on side effect.
def install_addon_side_effect_fixture(addon_store_info, addon_info): """Return the install add-on side effect.""" async def install_addon(hass, slug): """Mock install add-on.""" addon_store_info.return_value = { "installed": "1.0.0", "state": "stopped", "version": "1.0.0", } addon_info.return_value["hostname"] = "core-silabs-multiprotocol" addon_info.return_value["state"] = "stopped" addon_info.return_value["version"] = "1.0.0" return install_addon
Mock install add-on.
def mock_install_addon(install_addon_side_effect): """Mock install add-on.""" with patch( "homeassistant.components.hassio.addon_manager.async_install_addon", side_effect=install_addon_side_effect, ) as install_addon: yield install_addon
Mock start add-on.
def start_addon_fixture(): """Mock start add-on.""" with patch( "homeassistant.components.hassio.addon_manager.async_start_addon" ) as start_addon: yield start_addon
Mock stop add-on.
def stop_addon_fixture(): """Mock stop add-on.""" with patch( "homeassistant.components.hassio.addon_manager.async_stop_addon" ) as stop_addon: yield stop_addon
Mock uninstall add-on.
def uninstall_addon_fixture(): """Mock uninstall add-on.""" with patch( "homeassistant.components.hassio.addon_manager.async_uninstall_addon" ) as uninstall_addon: yield uninstall_addon
Fixture for a test config flow.
def config_flow_handler( hass: HomeAssistant, current_request_with_host: Any ) -> Generator[FakeConfigFlow, None, None]: """Fixture for a test config flow.""" mock_platform(hass, f"{TEST_DOMAIN}.config_flow") with mock_config_flow(TEST_DOMAIN, FakeConfigFlow): yield
Fixture for patching options flow addon state polling.
def options_flow_poll_addon_state() -> Generator[None, None, None]: """Fixture for patching options flow addon state polling.""" with patch( "homeassistant.components.homeassistant_hardware.silabs_multiprotocol_addon.WaitingAddonManager.async_wait_until_addon_state" ): yield
Fixture to mock the `hassio` integration.
def hassio_integration(hass: HomeAssistant) -> Generator[None, None, None]: """Fixture to mock the `hassio` integration.""" mock_component(hass, "hassio") hass.data["hassio"] = Mock(spec_set=HassIO)
Fixture for a test silabs multiprotocol platform.
def mock_multiprotocol_platform( hass: HomeAssistant, ) -> Generator[FakeConfigFlow, None, None]: """Fixture for a test silabs multiprotocol platform.""" hass.config.components.add(TEST_DOMAIN) platform = MockMultiprotocolPlatform() mock_platform(hass, f"{TEST_DOMAIN}.silabs_multiprotocol", platform) return platform
Get suggested value for key in voluptuous schema.
def get_suggested(schema, key): """Get suggested value for key in voluptuous schema.""" for k in schema: if k == key: if k.description is None or "suggested_value" not in k.description: return None return k.description["suggested_value"] # Wanted key absent from schema raise Exception
Test is_multiprotocol_url.
def test_is_multiprotocol_url() -> None: """Test is_multiprotocol_url.""" assert silabs_multiprotocol_addon.is_multiprotocol_url( "socket://core-silabs-multiprotocol:9999" ) assert silabs_multiprotocol_addon.is_multiprotocol_url( "http://core-silabs-multiprotocol:8081" ) assert not silabs_multiprotocol_addon.is_multiprotocol_url("/dev/ttyAMA1")
Mock usb serial by id.
def mock_usb_serial_by_id_fixture() -> Generator[MagicMock, None, None]: """Mock usb serial by id.""" with patch( "homeassistant.components.zha.config_flow.usb.get_serial_by_id" ) as mock_usb_serial_by_id: mock_usb_serial_by_id.side_effect = lambda x: x yield mock_usb_serial_by_id
Mock the zha integration.
def mock_zha(): """Mock the zha integration.""" mock_connect_app = MagicMock() mock_connect_app.__aenter__.return_value.backups.backups = [MagicMock()] mock_connect_app.__aenter__.return_value.backups.create_backup.return_value = ( MagicMock() ) with ( patch( "homeassistant.components.zha.radio_manager.ZhaRadioManager.connect_zigpy_app", return_value=mock_connect_app, ), patch( "homeassistant.components.zha.async_setup_entry", return_value=True, ), ): yield
Mock zha.api.async_get_last_network_settings.
def mock_zha_get_last_network_settings() -> Generator[None, None, None]: """Mock zha.api.async_get_last_network_settings.""" with patch( "homeassistant.components.zha.api.async_get_last_network_settings", AsyncMock(return_value=None), ): yield
Mock add-on already running.
def mock_addon_running(addon_store_info, addon_info): """Mock add-on already running.""" addon_store_info.return_value = { "installed": "1.0.0", "state": "started", "version": "1.0.0", } addon_info.return_value["hostname"] = "core-silabs-multiprotocol" addon_info.return_value["state"] = "started" addon_info.return_value["version"] = "1.0.0" return addon_info
Mock add-on already installed but not running.
def mock_addon_installed(addon_store_info, addon_info): """Mock add-on already installed but not running.""" addon_store_info.return_value = { "installed": "1.0.0", "state": "stopped", "version": "1.0.0", } addon_info.return_value["hostname"] = "core-silabs-multiprotocol" addon_info.return_value["state"] = "stopped" addon_info.return_value["version"] = "1.0.0" return addon_info
Mock Supervisor add-on store info.
def addon_store_info_fixture(): """Mock Supervisor add-on store info.""" with patch( "homeassistant.components.hassio.addon_manager.async_get_addon_store_info" ) as addon_store_info: addon_store_info.return_value = { "available": True, "installed": None, "state": None, "version": "1.0.0", } yield addon_store_info
Mock Supervisor add-on info.
def addon_info_fixture(): """Mock Supervisor add-on info.""" with patch( "homeassistant.components.hassio.addon_manager.async_get_addon_info", ) as addon_info: addon_info.return_value = { "available": True, "hostname": None, "options": {}, "state": None, "update_available": False, "version": None, } yield addon_info
Mock set add-on options.
def set_addon_options_fixture(): """Mock set add-on options.""" with patch( "homeassistant.components.hassio.addon_manager.async_set_addon_options" ) as set_options: yield set_options
Return the install add-on side effect.
def install_addon_side_effect_fixture(addon_store_info, addon_info): """Return the install add-on side effect.""" async def install_addon(hass, slug): """Mock install add-on.""" addon_store_info.return_value = { "installed": "1.0.0", "state": "stopped", "version": "1.0.0", } addon_info.return_value["hostname"] = "core-silabs-multiprotocol" addon_info.return_value["state"] = "stopped" addon_info.return_value["version"] = "1.0.0" return install_addon
Mock install add-on.
def mock_install_addon(install_addon_side_effect): """Mock install add-on.""" with patch( "homeassistant.components.hassio.addon_manager.async_install_addon", side_effect=install_addon_side_effect, ) as install_addon: yield install_addon
Mock start add-on.
def start_addon_fixture(): """Mock start add-on.""" with patch( "homeassistant.components.hassio.addon_manager.async_start_addon" ) as start_addon: yield start_addon
Mock stop add-on.
def stop_addon_fixture(): """Mock stop add-on.""" with patch( "homeassistant.components.hassio.addon_manager.async_stop_addon" ) as stop_addon: yield stop_addon
Mock uninstall add-on.
def uninstall_addon_fixture(): """Mock uninstall add-on.""" with patch( "homeassistant.components.hassio.addon_manager.async_uninstall_addon" ) as uninstall_addon: yield uninstall_addon
Slows down eager tasks by delaying for an event loop tick.
def delayed_side_effect() -> Callable[..., Awaitable[None]]: """Slows down eager tasks by delaying for an event loop tick.""" async def side_effect(*args: Any, **kwargs: Any) -> None: await asyncio.sleep(0) return side_effect
Test hardware variant parsing.
def test_hardware_variant( usb_product_name: str, expected_variant: HardwareVariant ) -> None: """Test hardware variant parsing.""" assert HardwareVariant.from_usb_product_name(usb_product_name) == expected_variant
Test hardware variant parsing with an invalid product.
def test_hardware_variant_invalid(): """Test hardware variant parsing with an invalid product.""" with pytest.raises( ValueError, match=r"^Unknown SkyConnect product name: Some other product$" ): HardwareVariant.from_usb_product_name("Some other product")
Test `get_usb_service_info` conversion.
def test_get_usb_service_info() -> None: """Test `get_usb_service_info` conversion.""" assert get_usb_service_info(SKYCONNECT_CONFIG_ENTRY) == UsbServiceInfo( device=SKYCONNECT_CONFIG_ENTRY.data["device"], vid=SKYCONNECT_CONFIG_ENTRY.data["vid"], pid=SKYCONNECT_CONFIG_ENTRY.data["pid"], serial_number=SKYCONNECT_CONFIG_ENTRY.data["serial_number"], manufacturer=SKYCONNECT_CONFIG_ENTRY.data["manufacturer"], description=SKYCONNECT_CONFIG_ENTRY.data["product"], )
Test `get_hardware_variant` extraction.
def test_get_hardware_variant() -> None: """Test `get_hardware_variant` extraction.""" assert get_hardware_variant(SKYCONNECT_CONFIG_ENTRY) == HardwareVariant.SKYCONNECT assert ( get_hardware_variant(CONNECT_ZBT1_CONFIG_ENTRY) == HardwareVariant.CONNECT_ZBT1 )
Test extracting the ZHA device path from its config entry.
def test_get_zha_device_path() -> None: """Test extracting the ZHA device path from its config entry.""" assert ( get_zha_device_path(ZHA_CONFIG_ENTRY) == ZHA_CONFIG_ENTRY.data["device"]["path"] )
Mock the radio connection and probing of the ZHA config flow.
def mock_zha_config_flow_setup() -> Generator[None, None, None]: """Mock the radio connection and probing of the ZHA config flow.""" def mock_probe(config: dict[str, Any]) -> None: # The radio probing will return the correct baudrate return {**config, "baudrate": 115200} mock_connect_app = MagicMock() mock_connect_app.__aenter__.return_value.backups.backups = [MagicMock()] mock_connect_app.__aenter__.return_value.backups.create_backup.return_value = ( MagicMock() ) with ( patch( "bellows.zigbee.application.ControllerApplication.probe", side_effect=mock_probe, ), patch( "homeassistant.components.zha.radio_manager.ZhaRadioManager.connect_zigpy_app", return_value=mock_connect_app, ), patch( "homeassistant.components.zha.async_setup_entry", return_value=True, ), ): yield
Mock zha.api.async_get_last_network_settings.
def mock_zha_get_last_network_settings() -> Generator[None, None, None]: """Mock zha.api.async_get_last_network_settings.""" with patch( "homeassistant.components.zha.api.async_get_last_network_settings", AsyncMock(return_value=None), ): yield
Mock add-on already running.
def mock_addon_running(addon_store_info, addon_info): """Mock add-on already running.""" addon_store_info.return_value = { "installed": "1.0.0", "state": "started", "version": "1.0.0", } addon_info.return_value["hostname"] = "core-silabs-multiprotocol" addon_info.return_value["state"] = "started" addon_info.return_value["version"] = "1.0.0" return addon_info
Mock add-on already installed but not running.
def mock_addon_installed(addon_store_info, addon_info): """Mock add-on already installed but not running.""" addon_store_info.return_value = { "installed": "1.0.0", "state": "stopped", "version": "1.0.0", } addon_info.return_value["hostname"] = "core-silabs-multiprotocol" addon_info.return_value["state"] = "stopped" addon_info.return_value["version"] = "1.0.0" return addon_info