Merge multiple context managers in tests (#48146)

This commit is contained in:
Franck Nijhof 2021-03-27 09:17:15 +01:00 committed by GitHub
parent 79af18a8ab
commit ad13a9295e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
33 changed files with 590 additions and 627 deletions

View file

@ -501,9 +501,8 @@ async def test_refresh_token_provider_validation(mock_hass):
with patch( with patch(
"homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token", "homeassistant.auth.providers.insecure_example.ExampleAuthProvider.async_validate_refresh_token",
side_effect=InvalidAuthError("Invalid access"), side_effect=InvalidAuthError("Invalid access"),
) as call: ) as call, pytest.raises(InvalidAuthError):
with pytest.raises(InvalidAuthError): manager.async_create_access_token(refresh_token, ip)
manager.async_create_access_token(refresh_token, ip)
call.assert_called_with(refresh_token, ip) call.assert_called_with(refresh_token, ip)

View file

@ -933,12 +933,11 @@ async def test_update_lock_not_acquired(hass):
with patch( with patch(
"androidtv.androidtv.androidtv_async.AndroidTVAsync.update", "androidtv.androidtv.androidtv_async.AndroidTVAsync.update",
side_effect=LockNotAcquiredException, side_effect=LockNotAcquiredException,
): ), patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key]:
with patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key]: await hass.helpers.entity_component.async_update_entity(entity_id)
await hass.helpers.entity_component.async_update_entity(entity_id) state = hass.states.get(entity_id)
state = hass.states.get(entity_id) assert state is not None
assert state is not None assert state.state == STATE_OFF
assert state.state == STATE_OFF
with patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key]: with patchers.patch_shell(SHELL_RESPONSE_STANDBY)[patch_key]:
await hass.helpers.entity_component.async_update_entity(entity_id) await hass.helpers.entity_component.async_update_entity(entity_id)
@ -1206,19 +1205,18 @@ async def test_connection_closed_on_ha_stop(hass):
"""Test that the ADB socket connection is closed when HA stops.""" """Test that the ADB socket connection is closed when HA stops."""
patch_key, entity_id = _setup(CONFIG_ANDROIDTV_ADB_SERVER) patch_key, entity_id = _setup(CONFIG_ANDROIDTV_ADB_SERVER)
with patchers.PATCH_ADB_DEVICE_TCP, patchers.patch_connect(True)[patch_key]: with patchers.PATCH_ADB_DEVICE_TCP, patchers.patch_connect(True)[
with patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key]: patch_key
assert await async_setup_component( ], patchers.patch_shell(SHELL_RESPONSE_OFF)[patch_key]:
hass, DOMAIN, CONFIG_ANDROIDTV_ADB_SERVER assert await async_setup_component(hass, DOMAIN, CONFIG_ANDROIDTV_ADB_SERVER)
) await hass.async_block_till_done()
await hass.async_block_till_done()
with patch( with patch(
"androidtv.androidtv.androidtv_async.AndroidTVAsync.adb_close" "androidtv.androidtv.androidtv_async.AndroidTVAsync.adb_close"
) as adb_close: ) as adb_close:
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
await hass.async_block_till_done() await hass.async_block_till_done()
assert adb_close.called assert adb_close.called
async def test_exception(hass): async def test_exception(hass):

View file

@ -28,13 +28,14 @@ async def test_apprise_config_load_fail02(hass):
BASE_COMPONENT: {"name": "test", "platform": "apprise", "config": "/path/"} BASE_COMPONENT: {"name": "test", "platform": "apprise", "config": "/path/"}
} }
with patch("apprise.Apprise.add", return_value=False): with patch("apprise.Apprise.add", return_value=False), patch(
with patch("apprise.AppriseConfig.add", return_value=True): "apprise.AppriseConfig.add", return_value=True
assert await async_setup_component(hass, BASE_COMPONENT, config) ):
await hass.async_block_till_done() assert await async_setup_component(hass, BASE_COMPONENT, config)
await hass.async_block_till_done()
# Test that our service failed to load # Test that our service failed to load
assert not hass.services.has_service(BASE_COMPONENT, "test") assert not hass.services.has_service(BASE_COMPONENT, "test")
async def test_apprise_config_load_okay(hass, tmp_path): async def test_apprise_config_load_okay(hass, tmp_path):

View file

@ -72,20 +72,23 @@ async def setup_platform(
) )
mock_entry.add_to_hass(hass) mock_entry.add_to_hass(hass)
with patch("homeassistant.components.bond.PLATFORMS", [platform]): with patch(
with patch_bond_version(return_value=bond_version), patch_bond_bridge( "homeassistant.components.bond.PLATFORMS", [platform]
return_value=bridge ), patch_bond_version(return_value=bond_version), patch_bond_bridge(
), patch_bond_token(return_value=token), patch_bond_device_ids( return_value=bridge
return_value=[bond_device_id] ), patch_bond_token(
), patch_start_bpup(), patch_bond_device( return_value=token
return_value=discovered_device ), patch_bond_device_ids(
), patch_bond_device_properties( return_value=[bond_device_id]
return_value=props ), patch_start_bpup(), patch_bond_device(
), patch_bond_device_state( return_value=discovered_device
return_value=state ), patch_bond_device_properties(
): return_value=props
assert await async_setup_component(hass, BOND_DOMAIN, {}) ), patch_bond_device_state(
await hass.async_block_till_done() return_value=state
):
assert await async_setup_component(hass, BOND_DOMAIN, {})
await hass.async_block_till_done()
return mock_entry return mock_entry

View file

@ -237,19 +237,18 @@ async def test_update_stale(hass, mock_device_tracker_conf):
with patch( with patch(
"homeassistant.components.device_tracker.legacy.dt_util.utcnow", "homeassistant.components.device_tracker.legacy.dt_util.utcnow",
return_value=register_time, return_value=register_time,
): ), assert_setup_component(1, device_tracker.DOMAIN):
with assert_setup_component(1, device_tracker.DOMAIN): assert await async_setup_component(
assert await async_setup_component( hass,
hass, device_tracker.DOMAIN,
device_tracker.DOMAIN, {
{ device_tracker.DOMAIN: {
device_tracker.DOMAIN: { CONF_PLATFORM: "test",
CONF_PLATFORM: "test", device_tracker.CONF_CONSIDER_HOME: 59,
device_tracker.CONF_CONSIDER_HOME: 59, }
} },
}, )
) await hass.async_block_till_done()
await hass.async_block_till_done()
assert hass.states.get("device_tracker.dev1").state == STATE_HOME assert hass.states.get("device_tracker.dev1").state == STATE_HOME
@ -458,19 +457,18 @@ async def test_see_passive_zone_state(hass, mock_device_tracker_conf):
with patch( with patch(
"homeassistant.components.device_tracker.legacy.dt_util.utcnow", "homeassistant.components.device_tracker.legacy.dt_util.utcnow",
return_value=register_time, return_value=register_time,
): ), assert_setup_component(1, device_tracker.DOMAIN):
with assert_setup_component(1, device_tracker.DOMAIN): assert await async_setup_component(
assert await async_setup_component( hass,
hass, device_tracker.DOMAIN,
device_tracker.DOMAIN, {
{ device_tracker.DOMAIN: {
device_tracker.DOMAIN: { CONF_PLATFORM: "test",
CONF_PLATFORM: "test", device_tracker.CONF_CONSIDER_HOME: 59,
device_tracker.CONF_CONSIDER_HOME: 59, }
} },
}, )
) await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get("device_tracker.dev1") state = hass.states.get("device_tracker.dev1")
attrs = state.attributes attrs = state.attributes

View file

@ -93,17 +93,16 @@ async def test_light_unavailable(
with patch( with patch(
"homeassistant.components.elgato.light.Elgato.light", "homeassistant.components.elgato.light.Elgato.light",
side_effect=ElgatoError, side_effect=ElgatoError,
), patch(
"homeassistant.components.elgato.light.Elgato.state",
side_effect=ElgatoError,
): ):
with patch( await hass.services.async_call(
"homeassistant.components.elgato.light.Elgato.state", LIGHT_DOMAIN,
side_effect=ElgatoError, SERVICE_TURN_OFF,
): {ATTR_ENTITY_ID: "light.frenck"},
await hass.services.async_call( blocking=True,
LIGHT_DOMAIN, )
SERVICE_TURN_OFF, await hass.async_block_till_done()
{ATTR_ENTITY_ID: "light.frenck"}, state = hass.states.get("light.frenck")
blocking=True, assert state.state == STATE_UNAVAILABLE
)
await hass.async_block_till_done()
state = hass.states.get("light.frenck")
assert state.state == STATE_UNAVAILABLE

View file

@ -13,29 +13,30 @@ def test_config_google_home_entity_id_to_number():
with patch( with patch(
"homeassistant.components.emulated_hue.load_json", "homeassistant.components.emulated_hue.load_json",
return_value={"1": "light.test2"}, return_value={"1": "light.test2"},
) as json_loader: ) as json_loader, patch(
with patch("homeassistant.components.emulated_hue.save_json") as json_saver: "homeassistant.components.emulated_hue.save_json"
number = conf.entity_id_to_number("light.test") ) as json_saver:
assert number == "2" number = conf.entity_id_to_number("light.test")
assert number == "2"
assert json_saver.mock_calls[0][1][1] == { assert json_saver.mock_calls[0][1][1] == {
"1": "light.test2", "1": "light.test2",
"2": "light.test", "2": "light.test",
} }
assert json_saver.call_count == 1 assert json_saver.call_count == 1
assert json_loader.call_count == 1 assert json_loader.call_count == 1
number = conf.entity_id_to_number("light.test") number = conf.entity_id_to_number("light.test")
assert number == "2" assert number == "2"
assert json_saver.call_count == 1 assert json_saver.call_count == 1
number = conf.entity_id_to_number("light.test2") number = conf.entity_id_to_number("light.test2")
assert number == "1" assert number == "1"
assert json_saver.call_count == 1 assert json_saver.call_count == 1
entity_id = conf.number_to_entity_id("1") entity_id = conf.number_to_entity_id("1")
assert entity_id == "light.test2" assert entity_id == "light.test2"
def test_config_google_home_entity_id_to_number_altered(): def test_config_google_home_entity_id_to_number_altered():
@ -47,28 +48,29 @@ def test_config_google_home_entity_id_to_number_altered():
with patch( with patch(
"homeassistant.components.emulated_hue.load_json", "homeassistant.components.emulated_hue.load_json",
return_value={"21": "light.test2"}, return_value={"21": "light.test2"},
) as json_loader: ) as json_loader, patch(
with patch("homeassistant.components.emulated_hue.save_json") as json_saver: "homeassistant.components.emulated_hue.save_json"
number = conf.entity_id_to_number("light.test") ) as json_saver:
assert number == "22" number = conf.entity_id_to_number("light.test")
assert json_saver.call_count == 1 assert number == "22"
assert json_loader.call_count == 1 assert json_saver.call_count == 1
assert json_loader.call_count == 1
assert json_saver.mock_calls[0][1][1] == { assert json_saver.mock_calls[0][1][1] == {
"21": "light.test2", "21": "light.test2",
"22": "light.test", "22": "light.test",
} }
number = conf.entity_id_to_number("light.test") number = conf.entity_id_to_number("light.test")
assert number == "22" assert number == "22"
assert json_saver.call_count == 1 assert json_saver.call_count == 1
number = conf.entity_id_to_number("light.test2") number = conf.entity_id_to_number("light.test2")
assert number == "21" assert number == "21"
assert json_saver.call_count == 1 assert json_saver.call_count == 1
entity_id = conf.number_to_entity_id("21") entity_id = conf.number_to_entity_id("21")
assert entity_id == "light.test2" assert entity_id == "light.test2"
def test_config_google_home_entity_id_to_number_empty(): def test_config_google_home_entity_id_to_number_empty():
@ -79,25 +81,26 @@ def test_config_google_home_entity_id_to_number_empty():
with patch( with patch(
"homeassistant.components.emulated_hue.load_json", return_value={} "homeassistant.components.emulated_hue.load_json", return_value={}
) as json_loader: ) as json_loader, patch(
with patch("homeassistant.components.emulated_hue.save_json") as json_saver: "homeassistant.components.emulated_hue.save_json"
number = conf.entity_id_to_number("light.test") ) as json_saver:
assert number == "1" number = conf.entity_id_to_number("light.test")
assert json_saver.call_count == 1 assert number == "1"
assert json_loader.call_count == 1 assert json_saver.call_count == 1
assert json_loader.call_count == 1
assert json_saver.mock_calls[0][1][1] == {"1": "light.test"} assert json_saver.mock_calls[0][1][1] == {"1": "light.test"}
number = conf.entity_id_to_number("light.test") number = conf.entity_id_to_number("light.test")
assert number == "1" assert number == "1"
assert json_saver.call_count == 1 assert json_saver.call_count == 1
number = conf.entity_id_to_number("light.test2") number = conf.entity_id_to_number("light.test2")
assert number == "2" assert number == "2"
assert json_saver.call_count == 2 assert json_saver.call_count == 2
entity_id = conf.number_to_entity_id("2") entity_id = conf.number_to_entity_id("2")
assert entity_id == "light.test2" assert entity_id == "light.test2"
def test_config_alexa_entity_id_to_number(): def test_config_alexa_entity_id_to_number():

View file

@ -73,13 +73,14 @@ async def test_detection_flow_with_custom_path(hass):
USER_PROVIDED_PATH = EnOceanFlowHandler.MANUAL_PATH_VALUE USER_PROVIDED_PATH = EnOceanFlowHandler.MANUAL_PATH_VALUE
FAKE_DONGLE_PATH = "/fake/dongle" FAKE_DONGLE_PATH = "/fake/dongle"
with patch(DONGLE_VALIDATE_PATH_METHOD, Mock(return_value=True)): with patch(DONGLE_VALIDATE_PATH_METHOD, Mock(return_value=True)), patch(
with patch(DONGLE_DETECT_METHOD, Mock(return_value=[FAKE_DONGLE_PATH])): DONGLE_DETECT_METHOD, Mock(return_value=[FAKE_DONGLE_PATH])
result = await hass.config_entries.flow.async_init( ):
DOMAIN, result = await hass.config_entries.flow.async_init(
context={"source": "detect"}, DOMAIN,
data={CONF_DEVICE: USER_PROVIDED_PATH}, context={"source": "detect"},
) data={CONF_DEVICE: USER_PROVIDED_PATH},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "manual" assert result["step_id"] == "manual"
@ -90,13 +91,14 @@ async def test_detection_flow_with_invalid_path(hass):
USER_PROVIDED_PATH = "/invalid/path" USER_PROVIDED_PATH = "/invalid/path"
FAKE_DONGLE_PATH = "/fake/dongle" FAKE_DONGLE_PATH = "/fake/dongle"
with patch(DONGLE_VALIDATE_PATH_METHOD, Mock(return_value=False)): with patch(DONGLE_VALIDATE_PATH_METHOD, Mock(return_value=False)), patch(
with patch(DONGLE_DETECT_METHOD, Mock(return_value=[FAKE_DONGLE_PATH])): DONGLE_DETECT_METHOD, Mock(return_value=[FAKE_DONGLE_PATH])
result = await hass.config_entries.flow.async_init( ):
DOMAIN, result = await hass.config_entries.flow.async_init(
context={"source": "detect"}, DOMAIN,
data={CONF_DEVICE: USER_PROVIDED_PATH}, context={"source": "detect"},
) data={CONF_DEVICE: USER_PROVIDED_PATH},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "detect" assert result["step_id"] == "detect"

View file

@ -116,24 +116,23 @@ async def test_chain_history(hass, values, missing=False):
with patch( with patch(
"homeassistant.components.history.state_changes_during_period", "homeassistant.components.history.state_changes_during_period",
return_value=fake_states, return_value=fake_states,
), patch(
"homeassistant.components.history.get_last_state_changes",
return_value=fake_states,
): ):
with patch( with assert_setup_component(1, "sensor"):
"homeassistant.components.history.get_last_state_changes", assert await async_setup_component(hass, "sensor", config)
return_value=fake_states, await hass.async_block_till_done()
):
with assert_setup_component(1, "sensor"):
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
for value in values: for value in values:
hass.states.async_set(config["sensor"]["entity_id"], value.state) hass.states.async_set(config["sensor"]["entity_id"], value.state)
await hass.async_block_till_done() await hass.async_block_till_done()
state = hass.states.get("sensor.test") state = hass.states.get("sensor.test")
if missing: if missing:
assert state.state == "18.05" assert state.state == "18.05"
else: else:
assert state.state == "17.05" assert state.state == "17.05"
async def test_source_state_none(hass, values): async def test_source_state_none(hass, values):
@ -234,18 +233,17 @@ async def test_history_time(hass):
with patch( with patch(
"homeassistant.components.history.state_changes_during_period", "homeassistant.components.history.state_changes_during_period",
return_value=fake_states, return_value=fake_states,
), patch(
"homeassistant.components.history.get_last_state_changes",
return_value=fake_states,
): ):
with patch( with assert_setup_component(1, "sensor"):
"homeassistant.components.history.get_last_state_changes", assert await async_setup_component(hass, "sensor", config)
return_value=fake_states,
):
with assert_setup_component(1, "sensor"):
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
await hass.async_block_till_done() await hass.async_block_till_done()
state = hass.states.get("sensor.test")
assert state.state == "18.0" await hass.async_block_till_done()
state = hass.states.get("sensor.test")
assert state.state == "18.0"
async def test_setup(hass): async def test_setup(hass):

View file

@ -198,60 +198,59 @@ async def test_setup_race_condition(hass, legacy_patchable_time):
utcnow = dt_util.utcnow() utcnow = dt_util.utcnow()
with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch( with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch(
"geojson_client.generic_feed.GenericFeed" "geojson_client.generic_feed.GenericFeed"
) as mock_feed: ) as mock_feed, assert_setup_component(1, geo_location.DOMAIN):
with assert_setup_component(1, geo_location.DOMAIN): assert await async_setup_component(hass, geo_location.DOMAIN, CONFIG)
assert await async_setup_component(hass, geo_location.DOMAIN, CONFIG) await hass.async_block_till_done()
await hass.async_block_till_done()
mock_feed.return_value.update.return_value = "OK", [mock_entry_1] mock_feed.return_value.update.return_value = "OK", [mock_entry_1]
# Artificially trigger update. # Artificially trigger update.
hass.bus.async_fire(EVENT_HOMEASSISTANT_START) hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
# Collect events. # Collect events.
await hass.async_block_till_done() await hass.async_block_till_done()
all_states = hass.states.async_all() all_states = hass.states.async_all()
assert len(all_states) == 1 assert len(all_states) == 1
assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1 assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1
assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1 assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1
# Simulate an update - empty data, removes all entities # Simulate an update - empty data, removes all entities
mock_feed.return_value.update.return_value = "ERROR", None mock_feed.return_value.update.return_value = "ERROR", None
async_fire_time_changed(hass, utcnow + SCAN_INTERVAL) async_fire_time_changed(hass, utcnow + SCAN_INTERVAL)
await hass.async_block_till_done() await hass.async_block_till_done()
all_states = hass.states.async_all() all_states = hass.states.async_all()
assert len(all_states) == 0 assert len(all_states) == 0
assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 0 assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 0
assert len(hass.data[DATA_DISPATCHER][update_signal]) == 0 assert len(hass.data[DATA_DISPATCHER][update_signal]) == 0
# Simulate an update - 1 entry # Simulate an update - 1 entry
mock_feed.return_value.update.return_value = "OK", [mock_entry_1] mock_feed.return_value.update.return_value = "OK", [mock_entry_1]
async_fire_time_changed(hass, utcnow + 2 * SCAN_INTERVAL) async_fire_time_changed(hass, utcnow + 2 * SCAN_INTERVAL)
await hass.async_block_till_done() await hass.async_block_till_done()
all_states = hass.states.async_all() all_states = hass.states.async_all()
assert len(all_states) == 1 assert len(all_states) == 1
assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1 assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1
assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1 assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1
# Simulate an update - 1 entry # Simulate an update - 1 entry
mock_feed.return_value.update.return_value = "OK", [mock_entry_1] mock_feed.return_value.update.return_value = "OK", [mock_entry_1]
async_fire_time_changed(hass, utcnow + 3 * SCAN_INTERVAL) async_fire_time_changed(hass, utcnow + 3 * SCAN_INTERVAL)
await hass.async_block_till_done() await hass.async_block_till_done()
all_states = hass.states.async_all() all_states = hass.states.async_all()
assert len(all_states) == 1 assert len(all_states) == 1
assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1 assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 1
assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1 assert len(hass.data[DATA_DISPATCHER][update_signal]) == 1
# Simulate an update - empty data, removes all entities # Simulate an update - empty data, removes all entities
mock_feed.return_value.update.return_value = "ERROR", None mock_feed.return_value.update.return_value = "ERROR", None
async_fire_time_changed(hass, utcnow + 4 * SCAN_INTERVAL) async_fire_time_changed(hass, utcnow + 4 * SCAN_INTERVAL)
await hass.async_block_till_done() await hass.async_block_till_done()
all_states = hass.states.async_all() all_states = hass.states.async_all()
assert len(all_states) == 0 assert len(all_states) == 0
# Ensure that delete and update signal targets are now empty. # Ensure that delete and update signal targets are now empty.
assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 0 assert len(hass.data[DATA_DISPATCHER][delete_signal]) == 0
assert len(hass.data[DATA_DISPATCHER][update_signal]) == 0 assert len(hass.data[DATA_DISPATCHER][update_signal]) == 0

View file

@ -68,54 +68,55 @@ async def test_setup(hass, mock_feed):
utcnow = dt_util.utcnow() utcnow = dt_util.utcnow()
# Patching 'utcnow' to gain more control over the timed update. # Patching 'utcnow' to gain more control over the timed update.
with patch("homeassistant.util.dt.utcnow", return_value=utcnow): with patch(
with assert_setup_component(1, sensor.DOMAIN): "homeassistant.util.dt.utcnow", return_value=utcnow
assert await async_setup_component(hass, sensor.DOMAIN, VALID_CONFIG) ), assert_setup_component(1, sensor.DOMAIN):
# Artificially trigger update. assert await async_setup_component(hass, sensor.DOMAIN, VALID_CONFIG)
hass.bus.fire(EVENT_HOMEASSISTANT_START) # Artificially trigger update.
# Collect events. hass.bus.fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done() # Collect events.
await hass.async_block_till_done()
all_states = hass.states.async_all() all_states = hass.states.async_all()
assert len(all_states) == 1 assert len(all_states) == 1
state = hass.states.get("sensor.event_service_any") state = hass.states.get("sensor.event_service_any")
assert state is not None assert state is not None
assert state.name == "Event Service Any" assert state.name == "Event Service Any"
assert int(state.state) == 2 assert int(state.state) == 2
assert state.attributes == { assert state.attributes == {
ATTR_FRIENDLY_NAME: "Event Service Any", ATTR_FRIENDLY_NAME: "Event Service Any",
ATTR_UNIT_OF_MEASUREMENT: "Events", ATTR_UNIT_OF_MEASUREMENT: "Events",
ATTR_ICON: "mdi:alert", ATTR_ICON: "mdi:alert",
"Title 1": "16km", "Title 1": "16km",
"Title 2": "20km", "Title 2": "20km",
} }
# Simulate an update - empty data, but successful update, # Simulate an update - empty data, but successful update,
# so no changes to entities. # so no changes to entities.
mock_feed.return_value.update.return_value = "OK_NO_DATA", None mock_feed.return_value.update.return_value = "OK_NO_DATA", None
async_fire_time_changed(hass, utcnow + geo_rss_events.SCAN_INTERVAL) async_fire_time_changed(hass, utcnow + geo_rss_events.SCAN_INTERVAL)
await hass.async_block_till_done() await hass.async_block_till_done()
all_states = hass.states.async_all() all_states = hass.states.async_all()
assert len(all_states) == 1 assert len(all_states) == 1
state = hass.states.get("sensor.event_service_any") state = hass.states.get("sensor.event_service_any")
assert int(state.state) == 2 assert int(state.state) == 2
# Simulate an update - empty data, removes all entities # Simulate an update - empty data, removes all entities
mock_feed.return_value.update.return_value = "ERROR", None mock_feed.return_value.update.return_value = "ERROR", None
async_fire_time_changed(hass, utcnow + 2 * geo_rss_events.SCAN_INTERVAL) async_fire_time_changed(hass, utcnow + 2 * geo_rss_events.SCAN_INTERVAL)
await hass.async_block_till_done() await hass.async_block_till_done()
all_states = hass.states.async_all() all_states = hass.states.async_all()
assert len(all_states) == 1 assert len(all_states) == 1
state = hass.states.get("sensor.event_service_any") state = hass.states.get("sensor.event_service_any")
assert int(state.state) == 0 assert int(state.state) == 0
assert state.attributes == { assert state.attributes == {
ATTR_FRIENDLY_NAME: "Event Service Any", ATTR_FRIENDLY_NAME: "Event Service Any",
ATTR_UNIT_OF_MEASUREMENT: "Events", ATTR_UNIT_OF_MEASUREMENT: "Events",
ATTR_ICON: "mdi:alert", ATTR_ICON: "mdi:alert",
} }
async def test_setup_with_categories(hass, mock_feed): async def test_setup_with_categories(hass, mock_feed):

View file

@ -220,11 +220,12 @@ class TestGraphite(unittest.TestCase):
runs.append(1) runs.append(1)
return event return event
with mock.patch.object(self.gf, "_queue") as mock_queue: with mock.patch.object(self.gf, "_queue") as mock_queue, mock.patch.object(
with mock.patch.object(self.gf, "_report_attributes") as mock_r: self.gf, "_report_attributes"
mock_queue.get.side_effect = fake_get ) as mock_r:
self.gf.run() mock_queue.get.side_effect = fake_get
# Twice for two events, once for the stop self.gf.run()
assert mock_queue.task_done.call_count == 3 # Twice for two events, once for the stop
assert mock_r.call_count == 1 assert mock_queue.task_done.call_count == 3
assert mock_r.call_args == mock.call("entity", event.data["new_state"]) assert mock_r.call_count == 1
assert mock_r.call_args == mock.call("entity", event.data["new_state"])

View file

@ -13,24 +13,21 @@ async def test_creating_entry_sets_up_climate_discovery(hass):
with patch( with patch(
"homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.discovery", "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.discovery",
return_value=["1.2.3.4"], return_value=["1.2.3.4"],
): ), patch(
with patch( "homeassistant.components.hisense_aehw4a1.climate.async_setup_entry",
"homeassistant.components.hisense_aehw4a1.climate.async_setup_entry", return_value=True,
return_value=True, ) as mock_setup:
) as mock_setup: result = await hass.config_entries.flow.async_init(
result = await hass.config_entries.flow.async_init( hisense_aehw4a1.DOMAIN, context={"source": config_entries.SOURCE_USER}
hisense_aehw4a1.DOMAIN, context={"source": config_entries.SOURCE_USER} )
)
# Confirmation form # Confirmation form
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
result = await hass.config_entries.flow.async_configure( result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
result["flow_id"], {} assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
await hass.async_block_till_done() await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1 assert len(mock_setup.mock_calls) == 1
@ -40,17 +37,16 @@ async def test_configuring_hisense_w4a1_create_entry(hass):
with patch( with patch(
"homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.check", "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.check",
return_value=True, return_value=True,
): ), patch(
with patch( "homeassistant.components.hisense_aehw4a1.async_setup_entry",
"homeassistant.components.hisense_aehw4a1.async_setup_entry", return_value=True,
return_value=True, ) as mock_setup:
) as mock_setup: await async_setup_component(
await async_setup_component( hass,
hass, hisense_aehw4a1.DOMAIN,
hisense_aehw4a1.DOMAIN, {"hisense_aehw4a1": {"ip_address": ["1.2.3.4"]}},
{"hisense_aehw4a1": {"ip_address": ["1.2.3.4"]}}, )
) await hass.async_block_till_done()
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1 assert len(mock_setup.mock_calls) == 1
@ -60,17 +56,16 @@ async def test_configuring_hisense_w4a1_not_creates_entry_for_device_not_found(h
with patch( with patch(
"homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.check", "homeassistant.components.hisense_aehw4a1.config_flow.AehW4a1.check",
side_effect=exceptions.ConnectionError, side_effect=exceptions.ConnectionError,
): ), patch(
with patch( "homeassistant.components.hisense_aehw4a1.async_setup_entry",
"homeassistant.components.hisense_aehw4a1.async_setup_entry", return_value=True,
return_value=True, ) as mock_setup:
) as mock_setup: await async_setup_component(
await async_setup_component( hass,
hass, hisense_aehw4a1.DOMAIN,
hisense_aehw4a1.DOMAIN, {"hisense_aehw4a1": {"ip_address": ["1.2.3.4"]}},
{"hisense_aehw4a1": {"ip_address": ["1.2.3.4"]}}, )
) await hass.async_block_till_done()
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 0 assert len(mock_setup.mock_calls) == 0

View file

@ -162,12 +162,11 @@ class TestHistoryStatsSensor(unittest.TestCase):
with patch( with patch(
"homeassistant.components.history.state_changes_during_period", "homeassistant.components.history.state_changes_during_period",
return_value=fake_states, return_value=fake_states,
): ), patch("homeassistant.components.history.get_state", return_value=None):
with patch("homeassistant.components.history.get_state", return_value=None): sensor1.update()
sensor1.update() sensor2.update()
sensor2.update() sensor3.update()
sensor3.update() sensor4.update()
sensor4.update()
assert sensor1.state == 0.5 assert sensor1.state == 0.5
assert sensor2.state is None assert sensor2.state is None
@ -246,12 +245,11 @@ class TestHistoryStatsSensor(unittest.TestCase):
with patch( with patch(
"homeassistant.components.history.state_changes_during_period", "homeassistant.components.history.state_changes_during_period",
return_value=fake_states, return_value=fake_states,
): ), patch("homeassistant.components.history.get_state", return_value=None):
with patch("homeassistant.components.history.get_state", return_value=None): sensor1.update()
sensor1.update() sensor2.update()
sensor2.update() sensor3.update()
sensor3.update() sensor4.update()
sensor4.update()
assert sensor1.state == 0.5 assert sensor1.state == 0.5
assert sensor2.state is None assert sensor2.state is None

View file

@ -254,14 +254,15 @@ async def test_setup_config_ssl(
config = {"influxdb": config_base.copy()} config = {"influxdb": config_base.copy()}
config["influxdb"].update(config_ext) config["influxdb"].update(config_ext)
with patch("os.access", return_value=True): with patch("os.access", return_value=True), patch(
with patch("os.path.isfile", return_value=True): "os.path.isfile", return_value=True
assert await async_setup_component(hass, influxdb.DOMAIN, config) ):
await hass.async_block_till_done() assert await async_setup_component(hass, influxdb.DOMAIN, config)
await hass.async_block_till_done()
assert hass.bus.listen.called assert hass.bus.listen.called
assert hass.bus.listen.call_args_list[0][0][0] == EVENT_STATE_CHANGED assert hass.bus.listen.call_args_list[0][0][0] == EVENT_STATE_CHANGED
assert expected_client_args.items() <= mock_client.call_args.kwargs.items() assert expected_client_args.items() <= mock_client.call_args.kwargs.items()
@pytest.mark.parametrize( @pytest.mark.parametrize(

View file

@ -90,11 +90,10 @@ async def test_full_flow(
}, },
) )
with patch("homeassistant.components.lyric.api.ConfigEntryLyricClient"): with patch("homeassistant.components.lyric.api.ConfigEntryLyricClient"), patch(
with patch( "homeassistant.components.lyric.async_setup_entry", return_value=True
"homeassistant.components.lyric.async_setup_entry", return_value=True ) as mock_setup:
) as mock_setup: result = await hass.config_entries.flow.async_configure(result["flow_id"])
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["data"]["auth_implementation"] == DOMAIN assert result["data"]["auth_implementation"] == DOMAIN

View file

@ -288,19 +288,18 @@ async def test_update(hass):
"""Test update.""" """Test update."""
with patch( with patch(
"homeassistant.components.melissa.climate._LOGGER.warning" "homeassistant.components.melissa.climate._LOGGER.warning"
) as mocked_warning: ) as mocked_warning, patch("homeassistant.components.melissa"):
with patch("homeassistant.components.melissa"): api = melissa_mock()
api = melissa_mock() device = (await api.async_fetch_devices())[_SERIAL]
device = (await api.async_fetch_devices())[_SERIAL] thermostat = MelissaClimate(api, _SERIAL, device)
thermostat = MelissaClimate(api, _SERIAL, device) await thermostat.async_update()
await thermostat.async_update() assert thermostat.fan_mode == SPEED_LOW
assert thermostat.fan_mode == SPEED_LOW assert thermostat.state == HVAC_MODE_HEAT
assert thermostat.state == HVAC_MODE_HEAT api.async_status = AsyncMock(side_effect=KeyError("boom"))
api.async_status = AsyncMock(side_effect=KeyError("boom")) await thermostat.async_update()
await thermostat.async_update() mocked_warning.assert_called_once_with(
mocked_warning.assert_called_once_with( "Unable to update entity %s", thermostat.entity_id
"Unable to update entity %s", thermostat.entity_id )
)
async def test_melissa_op_to_hass(hass): async def test_melissa_op_to_hass(hass):
@ -333,35 +332,33 @@ async def test_hass_mode_to_melissa(hass):
"""Test for hass operations to melssa.""" """Test for hass operations to melssa."""
with patch( with patch(
"homeassistant.components.melissa.climate._LOGGER.warning" "homeassistant.components.melissa.climate._LOGGER.warning"
) as mocked_warning: ) as mocked_warning, patch("homeassistant.components.melissa"):
with patch("homeassistant.components.melissa"): api = melissa_mock()
api = melissa_mock() device = (await api.async_fetch_devices())[_SERIAL]
device = (await api.async_fetch_devices())[_SERIAL] thermostat = MelissaClimate(api, _SERIAL, device)
thermostat = MelissaClimate(api, _SERIAL, device) assert thermostat.hass_mode_to_melissa(HVAC_MODE_FAN_ONLY) == 1
assert thermostat.hass_mode_to_melissa(HVAC_MODE_FAN_ONLY) == 1 assert thermostat.hass_mode_to_melissa(HVAC_MODE_HEAT) == 2
assert thermostat.hass_mode_to_melissa(HVAC_MODE_HEAT) == 2 assert thermostat.hass_mode_to_melissa(HVAC_MODE_COOL) == 3
assert thermostat.hass_mode_to_melissa(HVAC_MODE_COOL) == 3 assert thermostat.hass_mode_to_melissa(HVAC_MODE_DRY) == 4
assert thermostat.hass_mode_to_melissa(HVAC_MODE_DRY) == 4 thermostat.hass_mode_to_melissa("test")
thermostat.hass_mode_to_melissa("test") mocked_warning.assert_called_once_with(
mocked_warning.assert_called_once_with( "Melissa have no setting for %s mode", "test"
"Melissa have no setting for %s mode", "test" )
)
async def test_hass_fan_to_melissa(hass): async def test_hass_fan_to_melissa(hass):
"""Test for translate melissa states to hass.""" """Test for translate melissa states to hass."""
with patch( with patch(
"homeassistant.components.melissa.climate._LOGGER.warning" "homeassistant.components.melissa.climate._LOGGER.warning"
) as mocked_warning: ) as mocked_warning, patch("homeassistant.components.melissa"):
with patch("homeassistant.components.melissa"): api = melissa_mock()
api = melissa_mock() device = (await api.async_fetch_devices())[_SERIAL]
device = (await api.async_fetch_devices())[_SERIAL] thermostat = MelissaClimate(api, _SERIAL, device)
thermostat = MelissaClimate(api, _SERIAL, device) assert thermostat.hass_fan_to_melissa("auto") == 0
assert thermostat.hass_fan_to_melissa("auto") == 0 assert thermostat.hass_fan_to_melissa(SPEED_LOW) == 1
assert thermostat.hass_fan_to_melissa(SPEED_LOW) == 1 assert thermostat.hass_fan_to_melissa(SPEED_MEDIUM) == 2
assert thermostat.hass_fan_to_melissa(SPEED_MEDIUM) == 2 assert thermostat.hass_fan_to_melissa(SPEED_HIGH) == 3
assert thermostat.hass_fan_to_melissa(SPEED_HIGH) == 3 thermostat.hass_fan_to_melissa("test")
thermostat.hass_fan_to_melissa("test") mocked_warning.assert_called_once_with(
mocked_warning.assert_called_once_with( "Melissa have no setting for %s fan mode", "test"
"Melissa have no setting for %s fan mode", "test" )
)

View file

@ -103,31 +103,27 @@ async def test_invalid_ip(hass: HomeAssistantType) -> None:
async def test_same_host(hass: HomeAssistantType) -> None: async def test_same_host(hass: HomeAssistantType) -> None:
"""Test abort in case of same host name.""" """Test abort in case of same host name."""
with patch( with patch("aiodns.DNSResolver.query", side_effect=aiodns.error.DNSError,), patch(
"aiodns.DNSResolver.query", "mcstatus.server.MinecraftServer.status",
side_effect=aiodns.error.DNSError, return_value=PingResponse(STATUS_RESPONSE_RAW),
): ):
with patch( unique_id = "mc.dummyserver.com-25565"
"mcstatus.server.MinecraftServer.status", config_data = {
return_value=PingResponse(STATUS_RESPONSE_RAW), CONF_NAME: DEFAULT_NAME,
): CONF_HOST: "mc.dummyserver.com",
unique_id = "mc.dummyserver.com-25565" CONF_PORT: DEFAULT_PORT,
config_data = { }
CONF_NAME: DEFAULT_NAME, mock_config_entry = MockConfigEntry(
CONF_HOST: "mc.dummyserver.com", domain=DOMAIN, unique_id=unique_id, data=config_data
CONF_PORT: DEFAULT_PORT, )
} mock_config_entry.add_to_hass(hass)
mock_config_entry = MockConfigEntry(
domain=DOMAIN, unique_id=unique_id, data=config_data
)
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT
) )
assert result["type"] == RESULT_TYPE_ABORT assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured" assert result["reason"] == "already_configured"
async def test_port_too_small(hass: HomeAssistantType) -> None: async def test_port_too_small(hass: HomeAssistantType) -> None:
@ -163,93 +159,80 @@ async def test_connection_failed(hass: HomeAssistantType) -> None:
with patch( with patch(
"aiodns.DNSResolver.query", "aiodns.DNSResolver.query",
side_effect=aiodns.error.DNSError, side_effect=aiodns.error.DNSError,
): ), patch("mcstatus.server.MinecraftServer.status", side_effect=OSError):
with patch("mcstatus.server.MinecraftServer.status", side_effect=OSError): result = await hass.config_entries.flow.async_init(
result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT )
)
assert result["type"] == RESULT_TYPE_FORM assert result["type"] == RESULT_TYPE_FORM
assert result["errors"] == {"base": "cannot_connect"} assert result["errors"] == {"base": "cannot_connect"}
async def test_connection_succeeded_with_srv_record(hass: HomeAssistantType) -> None: async def test_connection_succeeded_with_srv_record(hass: HomeAssistantType) -> None:
"""Test config entry in case of a successful connection with a SRV record.""" """Test config entry in case of a successful connection with a SRV record."""
with patch( with patch("aiodns.DNSResolver.query", return_value=SRV_RECORDS,), patch(
"aiodns.DNSResolver.query", "mcstatus.server.MinecraftServer.status",
return_value=SRV_RECORDS, return_value=PingResponse(STATUS_RESPONSE_RAW),
): ):
with patch( result = await hass.config_entries.flow.async_init(
"mcstatus.server.MinecraftServer.status", DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_SRV
return_value=PingResponse(STATUS_RESPONSE_RAW), )
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_SRV
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == USER_INPUT_SRV[CONF_HOST] assert result["title"] == USER_INPUT_SRV[CONF_HOST]
assert result["data"][CONF_NAME] == USER_INPUT_SRV[CONF_NAME] assert result["data"][CONF_NAME] == USER_INPUT_SRV[CONF_NAME]
assert result["data"][CONF_HOST] == USER_INPUT_SRV[CONF_HOST] assert result["data"][CONF_HOST] == USER_INPUT_SRV[CONF_HOST]
async def test_connection_succeeded_with_host(hass: HomeAssistantType) -> None: async def test_connection_succeeded_with_host(hass: HomeAssistantType) -> None:
"""Test config entry in case of a successful connection with a host name.""" """Test config entry in case of a successful connection with a host name."""
with patch( with patch("aiodns.DNSResolver.query", side_effect=aiodns.error.DNSError,), patch(
"aiodns.DNSResolver.query", "mcstatus.server.MinecraftServer.status",
side_effect=aiodns.error.DNSError, return_value=PingResponse(STATUS_RESPONSE_RAW),
): ):
with patch( result = await hass.config_entries.flow.async_init(
"mcstatus.server.MinecraftServer.status", DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT
return_value=PingResponse(STATUS_RESPONSE_RAW), )
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == USER_INPUT[CONF_HOST] assert result["title"] == USER_INPUT[CONF_HOST]
assert result["data"][CONF_NAME] == USER_INPUT[CONF_NAME] assert result["data"][CONF_NAME] == USER_INPUT[CONF_NAME]
assert result["data"][CONF_HOST] == "mc.dummyserver.com" assert result["data"][CONF_HOST] == "mc.dummyserver.com"
async def test_connection_succeeded_with_ip4(hass: HomeAssistantType) -> None: async def test_connection_succeeded_with_ip4(hass: HomeAssistantType) -> None:
"""Test config entry in case of a successful connection with an IPv4 address.""" """Test config entry in case of a successful connection with an IPv4 address."""
with patch("getmac.get_mac_address", return_value="01:23:45:67:89:ab"): with patch("getmac.get_mac_address", return_value="01:23:45:67:89:ab"), patch(
with patch( "aiodns.DNSResolver.query",
"aiodns.DNSResolver.query", side_effect=aiodns.error.DNSError,
side_effect=aiodns.error.DNSError, ), patch(
): "mcstatus.server.MinecraftServer.status",
with patch( return_value=PingResponse(STATUS_RESPONSE_RAW),
"mcstatus.server.MinecraftServer.status", ):
return_value=PingResponse(STATUS_RESPONSE_RAW), result = await hass.config_entries.flow.async_init(
): DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_IPV4
result = await hass.config_entries.flow.async_init( )
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_IPV4
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == USER_INPUT_IPV4[CONF_HOST] assert result["title"] == USER_INPUT_IPV4[CONF_HOST]
assert result["data"][CONF_NAME] == USER_INPUT_IPV4[CONF_NAME] assert result["data"][CONF_NAME] == USER_INPUT_IPV4[CONF_NAME]
assert result["data"][CONF_HOST] == "1.1.1.1" assert result["data"][CONF_HOST] == "1.1.1.1"
async def test_connection_succeeded_with_ip6(hass: HomeAssistantType) -> None: async def test_connection_succeeded_with_ip6(hass: HomeAssistantType) -> None:
"""Test config entry in case of a successful connection with an IPv6 address.""" """Test config entry in case of a successful connection with an IPv6 address."""
with patch("getmac.get_mac_address", return_value="01:23:45:67:89:ab"): with patch("getmac.get_mac_address", return_value="01:23:45:67:89:ab"), patch(
with patch( "aiodns.DNSResolver.query",
"aiodns.DNSResolver.query", side_effect=aiodns.error.DNSError,
side_effect=aiodns.error.DNSError, ), patch(
): "mcstatus.server.MinecraftServer.status",
with patch( return_value=PingResponse(STATUS_RESPONSE_RAW),
"mcstatus.server.MinecraftServer.status", ):
return_value=PingResponse(STATUS_RESPONSE_RAW), result = await hass.config_entries.flow.async_init(
): DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_IPV6
result = await hass.config_entries.flow.async_init( )
DOMAIN, context={"source": SOURCE_USER}, data=USER_INPUT_IPV6
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == USER_INPUT_IPV6[CONF_HOST] assert result["title"] == USER_INPUT_IPV6[CONF_HOST]
assert result["data"][CONF_NAME] == USER_INPUT_IPV6[CONF_NAME] assert result["data"][CONF_NAME] == USER_INPUT_IPV6[CONF_NAME]
assert result["data"][CONF_HOST] == "::ffff:0101:0101" assert result["data"][CONF_HOST] == "::ffff:0101:0101"

View file

@ -743,10 +743,9 @@ async def test_sending_mqtt_commands_and_optimistic(hass, mqtt_mock):
with patch( with patch(
"homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state",
return_value=fake_state, return_value=fake_state,
): ), assert_setup_component(1, light.DOMAIN):
with assert_setup_component(1, light.DOMAIN): assert await async_setup_component(hass, light.DOMAIN, config)
assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get("light.test") state = hass.states.get("light.test")
assert state.state == STATE_ON assert state.state == STATE_ON

View file

@ -298,39 +298,38 @@ async def test_sending_mqtt_commands_and_optimistic(hass, mqtt_mock):
with patch( with patch(
"homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state",
return_value=fake_state, return_value=fake_state,
): ), assert_setup_component(1, light.DOMAIN):
with assert_setup_component(1, light.DOMAIN): assert await async_setup_component(
assert await async_setup_component( hass,
hass, light.DOMAIN,
light.DOMAIN, {
{ light.DOMAIN: {
light.DOMAIN: { "platform": "mqtt",
"platform": "mqtt", "schema": "template",
"schema": "template", "name": "test",
"name": "test", "command_topic": "test_light_rgb/set",
"command_topic": "test_light_rgb/set", "command_on_template": "on,"
"command_on_template": "on," "{{ brightness|d }},"
"{{ brightness|d }}," "{{ color_temp|d }},"
"{{ color_temp|d }}," "{{ white_value|d }},"
"{{ white_value|d }}," "{{ red|d }}-"
"{{ red|d }}-" "{{ green|d }}-"
"{{ green|d }}-" "{{ blue|d }}",
"{{ blue|d }}", "command_off_template": "off",
"command_off_template": "off", "effect_list": ["colorloop", "random"],
"effect_list": ["colorloop", "random"], "optimistic": True,
"optimistic": True, "state_template": '{{ value.split(",")[0] }}',
"state_template": '{{ value.split(",")[0] }}', "color_temp_template": '{{ value.split(",")[2] }}',
"color_temp_template": '{{ value.split(",")[2] }}', "white_value_template": '{{ value.split(",")[3] }}',
"white_value_template": '{{ value.split(",")[3] }}', "red_template": '{{ value.split(",")[4].' 'split("-")[0] }}',
"red_template": '{{ value.split(",")[4].' 'split("-")[0] }}', "green_template": '{{ value.split(",")[4].' 'split("-")[1] }}',
"green_template": '{{ value.split(",")[4].' 'split("-")[1] }}', "blue_template": '{{ value.split(",")[4].' 'split("-")[2] }}',
"blue_template": '{{ value.split(",")[4].' 'split("-")[2] }}', "effect_template": '{{ value.split(",")[5] }}',
"effect_template": '{{ value.split(",")[5] }}', "qos": 2,
"qos": 2, }
} },
}, )
) await hass.async_block_till_done()
await hass.async_block_till_done()
state = hass.states.get("light.test") state = hass.states.get("light.test")
assert state.state == STATE_ON assert state.state == STATE_ON

View file

@ -64,29 +64,31 @@ class PilightDaemonSim:
@patch("homeassistant.components.pilight._LOGGER.error") @patch("homeassistant.components.pilight._LOGGER.error")
async def test_connection_failed_error(mock_error, hass): async def test_connection_failed_error(mock_error, hass):
"""Try to connect at 127.0.0.1:5001 with socket error.""" """Try to connect at 127.0.0.1:5001 with socket error."""
with assert_setup_component(4): with assert_setup_component(4), patch(
with patch("pilight.pilight.Client", side_effect=socket.error) as mock_client: "pilight.pilight.Client", side_effect=socket.error
assert not await async_setup_component( ) as mock_client:
hass, pilight.DOMAIN, {pilight.DOMAIN: {}} assert not await async_setup_component(
) hass, pilight.DOMAIN, {pilight.DOMAIN: {}}
mock_client.assert_called_once_with( )
host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT mock_client.assert_called_once_with(
) host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT
assert mock_error.call_count == 1 )
assert mock_error.call_count == 1
@patch("homeassistant.components.pilight._LOGGER.error") @patch("homeassistant.components.pilight._LOGGER.error")
async def test_connection_timeout_error(mock_error, hass): async def test_connection_timeout_error(mock_error, hass):
"""Try to connect at 127.0.0.1:5001 with socket timeout.""" """Try to connect at 127.0.0.1:5001 with socket timeout."""
with assert_setup_component(4): with assert_setup_component(4), patch(
with patch("pilight.pilight.Client", side_effect=socket.timeout) as mock_client: "pilight.pilight.Client", side_effect=socket.timeout
assert not await async_setup_component( ) as mock_client:
hass, pilight.DOMAIN, {pilight.DOMAIN: {}} assert not await async_setup_component(
) hass, pilight.DOMAIN, {pilight.DOMAIN: {}}
mock_client.assert_called_once_with( )
host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT mock_client.assert_called_once_with(
) host=pilight.DEFAULT_HOST, port=pilight.DEFAULT_PORT
assert mock_error.call_count == 1 )
assert mock_error.call_count == 1
@patch("pilight.pilight.Client", PilightDaemonSim) @patch("pilight.pilight.Client", PilightDaemonSim)
@ -134,23 +136,22 @@ async def test_send_code(mock_pilight_error, hass):
@patch("homeassistant.components.pilight._LOGGER.error") @patch("homeassistant.components.pilight._LOGGER.error")
async def test_send_code_fail(mock_pilight_error, hass): async def test_send_code_fail(mock_pilight_error, hass):
"""Check IOError exception error message.""" """Check IOError exception error message."""
with assert_setup_component(4): with assert_setup_component(4), patch(
with patch("pilight.pilight.Client.send_code", side_effect=IOError): "pilight.pilight.Client.send_code", side_effect=IOError
assert await async_setup_component( ):
hass, pilight.DOMAIN, {pilight.DOMAIN: {}} assert await async_setup_component(hass, pilight.DOMAIN, {pilight.DOMAIN: {}})
)
# Call with protocol info, should not give error # Call with protocol info, should not give error
service_data = {"protocol": "test", "value": 42} service_data = {"protocol": "test", "value": 42}
await hass.services.async_call( await hass.services.async_call(
pilight.DOMAIN, pilight.DOMAIN,
pilight.SERVICE_NAME, pilight.SERVICE_NAME,
service_data=service_data, service_data=service_data,
blocking=True, blocking=True,
) )
await hass.async_block_till_done() await hass.async_block_till_done()
error_log_call = mock_pilight_error.call_args_list[-1] error_log_call = mock_pilight_error.call_args_list[-1]
assert "Pilight send failed" in str(error_log_call) assert "Pilight send failed" in str(error_log_call)
@patch("homeassistant.components.pilight._LOGGER.error") @patch("homeassistant.components.pilight._LOGGER.error")

View file

@ -87,12 +87,11 @@ class TestSignalMesssenger(unittest.TestCase):
) )
with self.assertLogs( with self.assertLogs(
"homeassistant.components.signal_messenger.notify", level="WARNING" "homeassistant.components.signal_messenger.notify", level="WARNING"
) as context: ) as context, tempfile.NamedTemporaryFile(
with tempfile.NamedTemporaryFile( suffix=".png", prefix=os.path.basename(__file__)
suffix=".png", prefix=os.path.basename(__file__) ) as tf:
) as tf: data = {"data": {"attachment": tf.name}}
data = {"data": {"attachment": tf.name}} self._signalmessenger.send_message(message, **data)
self._signalmessenger.send_message(message, **data)
self.assertIn( self.assertIn(
"The 'attachment' option is deprecated, please replace it with 'attachments'. This option will become invalid in version 0.108", "The 'attachment' option is deprecated, please replace it with 'attachments'. This option will become invalid in version 0.108",
context.output[0], context.output[0],
@ -117,12 +116,11 @@ class TestSignalMesssenger(unittest.TestCase):
) )
with self.assertLogs( with self.assertLogs(
"homeassistant.components.signal_messenger.notify", level="DEBUG" "homeassistant.components.signal_messenger.notify", level="DEBUG"
) as context: ) as context, tempfile.NamedTemporaryFile(
with tempfile.NamedTemporaryFile( suffix=".png", prefix=os.path.basename(__file__)
suffix=".png", prefix=os.path.basename(__file__) ) as tf:
) as tf: data = {"data": {"attachments": [tf.name]}}
data = {"data": {"attachments": [tf.name]}} self._signalmessenger.send_message(message, **data)
self._signalmessenger.send_message(message, **data)
self.assertIn("Sending signal message", context.output[0]) self.assertIn("Sending signal message", context.output[0])
self.assertTrue(mock.called) self.assertTrue(mock.called)
self.assertEqual(mock.call_count, 2) self.assertEqual(mock.call_count, 2)

View file

@ -291,20 +291,19 @@ async def async_log_error_from_test_path(hass, path, sq):
call_path = "internal_path.py" call_path = "internal_path.py"
with patch.object( with patch.object(
_LOGGER, "findCaller", MagicMock(return_value=(call_path, 0, None, None)) _LOGGER, "findCaller", MagicMock(return_value=(call_path, 0, None, None))
), patch(
"traceback.extract_stack",
MagicMock(
return_value=[
get_frame("main_path/main.py"),
get_frame(path),
get_frame(call_path),
get_frame("venv_path/logging/log.py"),
]
),
): ):
with patch( _LOGGER.error("error message")
"traceback.extract_stack", await _async_block_until_queue_empty(hass, sq)
MagicMock(
return_value=[
get_frame("main_path/main.py"),
get_frame(path),
get_frame(call_path),
get_frame("venv_path/logging/log.py"),
]
),
):
_LOGGER.error("error message")
await _async_block_until_queue_empty(hass, sq)
async def test_homeassistant_path(hass, simple_queue, hass_client): async def test_homeassistant_path(hass, simple_queue, hass_client):

View file

@ -415,10 +415,11 @@ async def test_ep_channels_configure(channel):
claimed = {ch_1.id: ch_1, ch_2.id: ch_2, ch_3.id: ch_3} claimed = {ch_1.id: ch_1, ch_2.id: ch_2, ch_3.id: ch_3}
client_chans = {ch_4.id: ch_4, ch_5.id: ch_5} client_chans = {ch_4.id: ch_4, ch_5.id: ch_5}
with mock.patch.dict(ep_channels.claimed_channels, claimed, clear=True): with mock.patch.dict(
with mock.patch.dict(ep_channels.client_channels, client_chans, clear=True): ep_channels.claimed_channels, claimed, clear=True
await ep_channels.async_configure() ), mock.patch.dict(ep_channels.client_channels, client_chans, clear=True):
await ep_channels.async_initialize(mock.sentinel.from_cache) await ep_channels.async_configure()
await ep_channels.async_initialize(mock.sentinel.from_cache)
for ch in [*claimed.values(), *client_chans.values()]: for ch in [*claimed.values(), *client_chans.values()]:
assert ch.async_initialize.call_count == 1 assert ch.async_initialize.call_count == 1

View file

@ -212,17 +212,14 @@ def test_discover_by_device_type_override():
with mock.patch( with mock.patch(
"homeassistant.components.zha.core.registries.ZHA_ENTITIES.get_entity", "homeassistant.components.zha.core.registries.ZHA_ENTITIES.get_entity",
get_entity_mock, get_entity_mock,
): ), mock.patch.dict(disc.PROBE._device_configs, overrides, clear=True):
with mock.patch.dict(disc.PROBE._device_configs, overrides, clear=True): disc.PROBE.discover_by_device_type(ep_channels)
disc.PROBE.discover_by_device_type(ep_channels) assert get_entity_mock.call_count == 1
assert get_entity_mock.call_count == 1 assert ep_channels.claim_channels.call_count == 1
assert ep_channels.claim_channels.call_count == 1 assert ep_channels.claim_channels.call_args[0][0] is mock.sentinel.claimed
assert ep_channels.claim_channels.call_args[0][0] is mock.sentinel.claimed assert ep_channels.async_new_entity.call_count == 1
assert ep_channels.async_new_entity.call_count == 1 assert ep_channels.async_new_entity.call_args[0][0] == zha_const.SWITCH
assert ep_channels.async_new_entity.call_args[0][0] == zha_const.SWITCH assert ep_channels.async_new_entity.call_args[0][1] == mock.sentinel.entity_cls
assert (
ep_channels.async_new_entity.call_args[0][1] == mock.sentinel.entity_cls
)
def test_discover_probe_single_cluster(): def test_discover_probe_single_cluster():

View file

@ -202,20 +202,17 @@ async def test_zwave_ready_wait(hass, mock_openzwave, zwave_setup):
sleeps.append(duration) sleeps.append(duration)
await asyncio_sleep(0) await asyncio_sleep(0)
with patch("homeassistant.components.zwave.dt_util.utcnow", new=utcnow): with patch("homeassistant.components.zwave.dt_util.utcnow", new=utcnow), patch(
with patch("asyncio.sleep", new=sleep): "asyncio.sleep", new=sleep
with patch.object(zwave, "_LOGGER") as mock_logger: ), patch.object(zwave, "_LOGGER") as mock_logger:
hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED
await hass.async_start() await hass.async_start()
assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert len(sleeps) == const.NETWORK_READY_WAIT_SECS
assert mock_logger.warning.called assert mock_logger.warning.called
assert len(mock_logger.warning.mock_calls) == 1 assert len(mock_logger.warning.mock_calls) == 1
assert ( assert mock_logger.warning.mock_calls[0][1][1] == const.NETWORK_READY_WAIT_SECS
mock_logger.warning.mock_calls[0][1][1]
== const.NETWORK_READY_WAIT_SECS
)
async def test_device_entity(hass, mock_openzwave): async def test_device_entity(hass, mock_openzwave):
@ -341,19 +338,19 @@ async def test_unparsed_node_discovery(hass, mock_openzwave):
sleeps.append(duration) sleeps.append(duration)
await asyncio_sleep(0) await asyncio_sleep(0)
with patch("homeassistant.components.zwave.dt_util.utcnow", new=utcnow): with patch("homeassistant.components.zwave.dt_util.utcnow", new=utcnow), patch(
with patch("asyncio.sleep", new=sleep): "asyncio.sleep", new=sleep
with patch.object(zwave, "_LOGGER") as mock_logger: ), patch.object(zwave, "_LOGGER") as mock_logger:
await hass.async_add_executor_job(mock_receivers[0], node) await hass.async_add_executor_job(mock_receivers[0], node)
await hass.async_block_till_done() await hass.async_block_till_done()
assert len(sleeps) == const.NODE_READY_WAIT_SECS assert len(sleeps) == const.NODE_READY_WAIT_SECS
assert mock_logger.warning.called assert mock_logger.warning.called
assert len(mock_logger.warning.mock_calls) == 1 assert len(mock_logger.warning.mock_calls) == 1
assert mock_logger.warning.mock_calls[0][1][1:] == ( assert mock_logger.warning.mock_calls[0][1][1:] == (
14, 14,
const.NODE_READY_WAIT_SECS, const.NODE_READY_WAIT_SECS,
) )
assert hass.states.get("zwave.unknown_node_14").state == "unknown" assert hass.states.get("zwave.unknown_node_14").state == "unknown"

View file

@ -99,9 +99,10 @@ def test_inherit_enforces_domain_set():
"""Return logger.""" """Return logger."""
return logging.getLogger(__name__) return logging.getLogger(__name__)
with patch.dict(config_entries.HANDLERS, {TEST_DOMAIN: TestFlowHandler}): with patch.dict(
with pytest.raises(TypeError): config_entries.HANDLERS, {TEST_DOMAIN: TestFlowHandler}
TestFlowHandler() ), pytest.raises(TypeError):
TestFlowHandler()
async def test_abort_if_no_implementation(hass, flow_handler): async def test_abort_if_no_implementation(hass, flow_handler):

View file

@ -377,9 +377,8 @@ async def test_get_cloud_url(hass: HomeAssistant):
hass.components.cloud, hass.components.cloud,
"async_remote_ui_url", "async_remote_ui_url",
side_effect=cloud.CloudNotAvailable, side_effect=cloud.CloudNotAvailable,
): ), pytest.raises(NoURLAvailableError):
with pytest.raises(NoURLAvailableError): _get_cloud_url(hass)
_get_cloud_url(hass)
async def test_get_external_url_cloud_fallback(hass: HomeAssistant): async def test_get_external_url_cloud_fallback(hass: HomeAssistant):

View file

@ -561,22 +561,21 @@ async def test_call_context_target_specific_no_auth(
hass, mock_handle_entity_call, mock_entities hass, mock_handle_entity_call, mock_entities
): ):
"""Check targeting specific entities without auth.""" """Check targeting specific entities without auth."""
with pytest.raises(exceptions.Unauthorized) as err: with pytest.raises(exceptions.Unauthorized) as err, patch(
with patch( "homeassistant.auth.AuthManager.async_get_user",
"homeassistant.auth.AuthManager.async_get_user", return_value=Mock(permissions=PolicyPermissions({}, None)),
return_value=Mock(permissions=PolicyPermissions({}, None)), ):
): await service.entity_service_call(
await service.entity_service_call( hass,
hass, [Mock(entities=mock_entities)],
[Mock(entities=mock_entities)], Mock(),
Mock(), ha.ServiceCall(
ha.ServiceCall( "test_domain",
"test_domain", "test_service",
"test_service", {"entity_id": "light.kitchen"},
{"entity_id": "light.kitchen"}, context=ha.Context(user_id="mock-id"),
context=ha.Context(user_id="mock-id"), ),
), )
)
assert err.value.context.user_id == "mock-id" assert err.value.context.user_id == "mock-id"
assert err.value.entity_id == "light.kitchen" assert err.value.entity_id == "light.kitchen"

View file

@ -1221,12 +1221,11 @@ async def test_init_custom_integration(hass):
None, None,
{"name": "Hue", "dependencies": [], "requirements": [], "domain": "hue"}, {"name": "Hue", "dependencies": [], "requirements": [], "domain": "hue"},
) )
with pytest.raises(data_entry_flow.UnknownHandler): with pytest.raises(data_entry_flow.UnknownHandler), patch(
with patch( "homeassistant.loader.async_get_integration",
"homeassistant.loader.async_get_integration", return_value=integration,
return_value=integration, ):
): await hass.config_entries.flow.async_init("bla")
await hass.config_entries.flow.async_init("bla")
async def test_support_entry_unload(hass): async def test_support_entry_unload(hass):

View file

@ -84,9 +84,8 @@ async def test_install_missing_package(hass):
"""Test an install attempt on an existing package.""" """Test an install attempt on an existing package."""
with patch( with patch(
"homeassistant.util.package.install_package", return_value=False "homeassistant.util.package.install_package", return_value=False
) as mock_inst: ) as mock_inst, pytest.raises(RequirementsNotFound):
with pytest.raises(RequirementsNotFound): await async_process_requirements(hass, "test_component", ["hello==1.0.0"])
await async_process_requirements(hass, "test_component", ["hello==1.0.0"])
assert len(mock_inst.mock_calls) == 1 assert len(mock_inst.mock_calls) == 1

View file

@ -206,8 +206,9 @@ async def test_callback_is_always_scheduled(hass):
callback = MagicMock() callback = MagicMock()
hasync.shutdown_run_callback_threadsafe(hass.loop) hasync.shutdown_run_callback_threadsafe(hass.loop)
with patch.object(hass.loop, "call_soon_threadsafe") as mock_call_soon_threadsafe: with patch.object(
with pytest.raises(RuntimeError): hass.loop, "call_soon_threadsafe"
hasync.run_callback_threadsafe(hass.loop, callback) ) as mock_call_soon_threadsafe, pytest.raises(RuntimeError):
hasync.run_callback_threadsafe(hass.loop, callback)
mock_call_soon_threadsafe.assert_called_once() mock_call_soon_threadsafe.assert_called_once()

View file

@ -65,9 +65,8 @@ def test_environment_variable_default():
def test_invalid_environment_variable(): def test_invalid_environment_variable():
"""Test config file with no environment variable sat.""" """Test config file with no environment variable sat."""
conf = "password: !env_var PASSWORD" conf = "password: !env_var PASSWORD"
with pytest.raises(HomeAssistantError): with pytest.raises(HomeAssistantError), io.StringIO(conf) as file:
with io.StringIO(conf) as file: yaml_loader.yaml.load(file, Loader=yaml_loader.SafeLineLoader)
yaml_loader.yaml.load(file, Loader=yaml_loader.SafeLineLoader)
def test_include_yaml(): def test_include_yaml():