Replace mock_coro with AsyncMock (#99014)

* Replace mock_coro with AsyncMock

* Remove mock_coro test helper function

* Remove redundant AsyncMock
This commit is contained in:
Marc Mueller 2023-08-25 22:54:55 +02:00 committed by GitHub
parent 57144a6064
commit 544d6b05a5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 43 additions and 60 deletions

View file

@ -965,16 +965,6 @@ def patch_yaml_files(files_dict, endswith=True):
return patch.object(yaml_loader, "open", mock_open_f, create=True) return patch.object(yaml_loader, "open", mock_open_f, create=True)
def mock_coro(return_value=None, exception=None):
"""Return a coro that returns a value or raise an exception."""
fut = asyncio.Future()
if exception is not None:
fut.set_exception(exception)
else:
fut.set_result(return_value)
return fut
@contextmanager @contextmanager
def assert_setup_component(count, domain=None): def assert_setup_component(count, domain=None):
"""Collect valid configuration from setup_component. """Collect valid configuration from setup_component.

View file

@ -14,7 +14,7 @@ from homeassistant.components.ecobee.const import (
from homeassistant.const import CONF_API_KEY from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, mock_coro from tests.common import MockConfigEntry
async def test_abort_if_already_setup(hass: HomeAssistant) -> None: async def test_abort_if_already_setup(hass: HomeAssistant) -> None:
@ -175,9 +175,7 @@ async def test_import_flow_triggered_with_ecobee_conf_and_invalid_data(
with patch( with patch(
"homeassistant.components.ecobee.config_flow.load_json_object", "homeassistant.components.ecobee.config_flow.load_json_object",
return_value=MOCK_ECOBEE_CONF, return_value=MOCK_ECOBEE_CONF,
), patch.object( ), patch.object(flow, "async_step_user") as mock_async_step_user:
flow, "async_step_user", return_value=mock_coro()
) as mock_async_step_user:
await flow.async_step_import(import_data=None) await flow.async_step_import(import_data=None)
mock_async_step_user.assert_called_once_with( mock_async_step_user.assert_called_once_with(
@ -201,7 +199,7 @@ async def test_import_flow_triggered_with_ecobee_conf_and_valid_data_and_stale_t
), patch( ), patch(
"homeassistant.components.ecobee.config_flow.Ecobee" "homeassistant.components.ecobee.config_flow.Ecobee"
) as mock_ecobee, patch.object( ) as mock_ecobee, patch.object(
flow, "async_step_user", return_value=mock_coro() flow, "async_step_user"
) as mock_async_step_user: ) as mock_async_step_user:
mock_ecobee = mock_ecobee.return_value mock_ecobee = mock_ecobee.return_value
mock_ecobee.refresh_tokens.return_value = False mock_ecobee.refresh_tokens.return_value = False

View file

@ -7,7 +7,7 @@ from homeassistant.components import ios
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import mock_component, mock_coro from tests.common import mock_component
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
@ -28,7 +28,7 @@ async def test_creating_entry_sets_up_sensor(hass: HomeAssistant) -> None:
"""Test setting up iOS loads the sensor component.""" """Test setting up iOS loads the sensor component."""
with patch( with patch(
"homeassistant.components.ios.sensor.async_setup_entry", "homeassistant.components.ios.sensor.async_setup_entry",
return_value=mock_coro(True), return_value=True,
) as mock_setup: ) as mock_setup:
assert await async_setup_component(hass, ios.DOMAIN, {ios.DOMAIN: {}}) assert await async_setup_component(hass, ios.DOMAIN, {ios.DOMAIN: {}})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -39,7 +39,8 @@ async def test_creating_entry_sets_up_sensor(hass: HomeAssistant) -> None:
async def test_configuring_ios_creates_entry(hass: HomeAssistant) -> None: async def test_configuring_ios_creates_entry(hass: HomeAssistant) -> None:
"""Test that specifying config will create an entry.""" """Test that specifying config will create an entry."""
with patch( with patch(
"homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) "homeassistant.components.ios.async_setup_entry",
return_value=True,
) as mock_setup: ) as mock_setup:
await async_setup_component(hass, ios.DOMAIN, {"ios": {"push": {}}}) await async_setup_component(hass, ios.DOMAIN, {"ios": {"push": {}}})
await hass.async_block_till_done() await hass.async_block_till_done()
@ -50,7 +51,8 @@ async def test_configuring_ios_creates_entry(hass: HomeAssistant) -> None:
async def test_not_configuring_ios_not_creates_entry(hass: HomeAssistant) -> None: async def test_not_configuring_ios_not_creates_entry(hass: HomeAssistant) -> None:
"""Test that no config will not create an entry.""" """Test that no config will not create an entry."""
with patch( with patch(
"homeassistant.components.ios.async_setup_entry", return_value=mock_coro(True) "homeassistant.components.ios.async_setup_entry",
return_value=True,
) as mock_setup: ) as mock_setup:
await async_setup_component(hass, ios.DOMAIN, {"foo": "bar"}) await async_setup_component(hass, ios.DOMAIN, {"foo": "bar"})
await hass.async_block_till_done() await hass.async_block_till_done()

View file

@ -15,7 +15,7 @@ from homeassistant.components.logi_circle.config_flow import (
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, mock_coro from tests.common import MockConfigEntry
class MockRequest: class MockRequest:
@ -50,10 +50,12 @@ def mock_logi_circle():
with patch( with patch(
"homeassistant.components.logi_circle.config_flow.LogiCircle" "homeassistant.components.logi_circle.config_flow.LogiCircle"
) as logi_circle: ) as logi_circle:
future = asyncio.Future()
future.set_result({"accountId": "testId"})
LogiCircle = logi_circle() LogiCircle = logi_circle()
LogiCircle.authorize = AsyncMock(return_value=True) LogiCircle.authorize = AsyncMock(return_value=True)
LogiCircle.close = AsyncMock(return_value=True) LogiCircle.close = AsyncMock(return_value=True)
LogiCircle.account = mock_coro(return_value={"accountId": "testId"}) LogiCircle.account = future
LogiCircle.authorize_url = "http://authorize.url" LogiCircle.authorize_url = "http://authorize.url"
yield LogiCircle yield LogiCircle

View file

@ -6,7 +6,7 @@ from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, mock_coro from tests.common import MockConfigEntry
async def test_setup_with_cloud_config(hass: HomeAssistant) -> None: async def test_setup_with_cloud_config(hass: HomeAssistant) -> None:
@ -109,7 +109,9 @@ async def test_unload_entry(hass: HomeAssistant) -> None:
entry.add_to_hass(hass) entry.add_to_hass(hass)
with patch.object( with patch.object(
hass.config_entries, "async_forward_entry_unload", return_value=mock_coro(True) hass.config_entries,
"async_forward_entry_unload",
return_value=True,
) as unload_entry, patch( ) as unload_entry, patch(
"mill.Mill.fetch_heater_and_sensor_data", return_value={} "mill.Mill.fetch_heater_and_sensor_data", return_value={}
), patch( ), patch(

View file

@ -13,7 +13,7 @@ from homeassistant.setup import async_setup_component
from .const import REGISTER, REGISTER_CLEARTEXT, RENDER_TEMPLATE from .const import REGISTER, REGISTER_CLEARTEXT, RENDER_TEMPLATE
from tests.common import MockUser, mock_coro from tests.common import MockUser
from tests.typing import ClientSessionGenerator from tests.typing import ClientSessionGenerator
@ -28,7 +28,6 @@ async def test_registration(
with patch( with patch(
"homeassistant.components.person.async_add_user_device_tracker", "homeassistant.components.person.async_add_user_device_tracker",
spec=True, spec=True,
return_value=mock_coro(),
) as add_user_dev_track: ) as add_user_dev_track:
resp = await api_client.post( resp = await api_client.post(
"/api/mobile_app/registrations", json=REGISTER_CLEARTEXT "/api/mobile_app/registrations", json=REGISTER_CLEARTEXT

View file

@ -8,7 +8,7 @@ from homeassistant.setup import async_setup_component
from . import mock_storage from . import mock_storage
from tests.common import MockUser, mock_coro from tests.common import MockUser
# Temporarily: if auth not active, always set onboarded=True # Temporarily: if auth not active, always set onboarded=True
@ -31,7 +31,6 @@ async def test_setup_views_if_not_onboarded(hass: HomeAssistant) -> None:
"""Test if onboarding is not done, we setup views.""" """Test if onboarding is not done, we setup views."""
with patch( with patch(
"homeassistant.components.onboarding.views.async_setup", "homeassistant.components.onboarding.views.async_setup",
return_value=mock_coro(),
) as mock_setup: ) as mock_setup:
assert await async_setup_component(hass, "onboarding", {}) assert await async_setup_component(hass, "onboarding", {})

View file

@ -9,7 +9,7 @@ from homeassistant.const import STATE_NOT_HOME
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, async_fire_mqtt_message, mock_coro from tests.common import MockConfigEntry, async_fire_mqtt_message
from tests.typing import ClientSessionGenerator from tests.typing import ClientSessionGenerator
USER = "greg" USER = "greg"
@ -1303,7 +1303,7 @@ async def test_not_implemented_message(hass: HomeAssistant, context) -> None:
"""Handle not implemented message type.""" """Handle not implemented message type."""
patch_handler = patch( patch_handler = patch(
"homeassistant.components.owntracks.messages.async_handle_not_impl_msg", "homeassistant.components.owntracks.messages.async_handle_not_impl_msg",
return_value=mock_coro(False), return_value=False,
) )
patch_handler.start() patch_handler.start()
assert not await send_message(hass, LWT_TOPIC, LWT_MESSAGE) assert not await send_message(hass, LWT_TOPIC, LWT_MESSAGE)
@ -1314,7 +1314,7 @@ async def test_unsupported_message(hass: HomeAssistant, context) -> None:
"""Handle not implemented message type.""" """Handle not implemented message type."""
patch_handler = patch( patch_handler = patch(
"homeassistant.components.owntracks.messages.async_handle_unsupported_msg", "homeassistant.components.owntracks.messages.async_handle_unsupported_msg",
return_value=mock_coro(False), return_value=False,
) )
patch_handler.start() patch_handler.start()
assert not await send_message(hass, BAD_TOPIC, BAD_MESSAGE) assert not await send_message(hass, BAD_TOPIC, BAD_MESSAGE)
@ -1393,7 +1393,7 @@ def config_context(hass, setup_comp):
"""Set up the mocked context.""" """Set up the mocked context."""
patch_load = patch( patch_load = patch(
"homeassistant.components.device_tracker.async_load_config", "homeassistant.components.device_tracker.async_load_config",
return_value=mock_coro([]), return_value=[],
) )
patch_load.start() patch_load.start()

View file

@ -9,8 +9,6 @@ from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT, PERCENTAGE, UnitOfTemp
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import mock_coro
CONFIG = { CONFIG = {
DOMAIN: { DOMAIN: {
"space": "Home", "space": "Home",
@ -83,7 +81,7 @@ SENSOR_OUTPUT = {
@pytest.fixture @pytest.fixture
def mock_client(hass, hass_client): def mock_client(hass, hass_client):
"""Start the Home Assistant HTTP component.""" """Start the Home Assistant HTTP component."""
with patch("homeassistant.components.spaceapi", return_value=mock_coro(True)): with patch("homeassistant.components.spaceapi", return_value=True):
hass.loop.run_until_complete(async_setup_component(hass, "spaceapi", CONFIG)) hass.loop.run_until_complete(async_setup_component(hass, "spaceapi", CONFIG))
hass.states.async_set( hass.states.async_set(

View file

@ -6,8 +6,6 @@ from homeassistant.components.spc import DATA_API
from homeassistant.const import STATE_ALARM_ARMED_AWAY, STATE_ALARM_DISARMED from homeassistant.const import STATE_ALARM_ARMED_AWAY, STATE_ALARM_DISARMED
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from tests.common import mock_coro
async def test_valid_device_config(hass: HomeAssistant, monkeypatch) -> None: async def test_valid_device_config(hass: HomeAssistant, monkeypatch) -> None:
"""Test valid device config.""" """Test valid device config."""
@ -15,7 +13,7 @@ async def test_valid_device_config(hass: HomeAssistant, monkeypatch) -> None:
with patch( with patch(
"homeassistant.components.spc.SpcWebGateway.async_load_parameters", "homeassistant.components.spc.SpcWebGateway.async_load_parameters",
return_value=mock_coro(True), return_value=True,
): ):
assert await async_setup_component(hass, "spc", config) is True assert await async_setup_component(hass, "spc", config) is True
@ -26,7 +24,7 @@ async def test_invalid_device_config(hass: HomeAssistant, monkeypatch) -> None:
with patch( with patch(
"homeassistant.components.spc.SpcWebGateway.async_load_parameters", "homeassistant.components.spc.SpcWebGateway.async_load_parameters",
return_value=mock_coro(True), return_value=True,
): ):
assert await async_setup_component(hass, "spc", config) is False assert await async_setup_component(hass, "spc", config) is False
@ -53,7 +51,7 @@ async def test_update_alarm_device(hass: HomeAssistant) -> None:
mock_areas.return_value = {"1": area_mock} mock_areas.return_value = {"1": area_mock}
with patch( with patch(
"homeassistant.components.spc.SpcWebGateway.async_load_parameters", "homeassistant.components.spc.SpcWebGateway.async_load_parameters",
return_value=mock_coro(True), return_value=True,
): ):
assert await async_setup_component(hass, "spc", config) is True assert await async_setup_component(hass, "spc", config) is True

View file

@ -11,7 +11,7 @@ from homeassistant.components.syncthru.const import DOMAIN
from homeassistant.const import CONF_NAME, CONF_URL from homeassistant.const import CONF_NAME, CONF_URL
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, mock_coro from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker from tests.test_util.aiohttp import AiohttpClientMocker
FIXTURE_USER_INPUT = { FIXTURE_USER_INPUT = {
@ -90,7 +90,7 @@ async def test_syncthru_not_supported(hass: HomeAssistant) -> None:
async def test_unknown_state(hass: HomeAssistant) -> None: async def test_unknown_state(hass: HomeAssistant) -> None:
"""Test we show user form on unsupported device.""" """Test we show user form on unsupported device."""
with patch.object(SyncThru, "update", return_value=mock_coro()), patch.object( with patch.object(SyncThru, "update"), patch.object(
SyncThru, "is_unknown_state", return_value=True SyncThru, "is_unknown_state", return_value=True
): ):
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(

View file

@ -23,7 +23,6 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import mock_coro
from tests.typing import ClientSessionGenerator from tests.typing import ClientSessionGenerator
@ -72,7 +71,6 @@ async def test_auth_via_msg_incorrect_pass(no_auth_websocket_client) -> None:
"""Test authenticating.""" """Test authenticating."""
with patch( with patch(
"homeassistant.components.websocket_api.auth.process_wrong_login", "homeassistant.components.websocket_api.auth.process_wrong_login",
return_value=mock_coro(),
) as mock_process_wrong_login: ) as mock_process_wrong_login:
await no_auth_websocket_client.send_json( await no_auth_websocket_client.send_json(
{"type": TYPE_AUTH, "api_password": "wrong"} {"type": TYPE_AUTH, "api_password": "wrong"}

View file

@ -35,8 +35,6 @@ from homeassistant.helpers import entity_registry as er
from .common import find_entity_id from .common import find_entity_id
from .conftest import SIG_EP_INPUT, SIG_EP_OUTPUT, SIG_EP_TYPE from .conftest import SIG_EP_INPUT, SIG_EP_OUTPUT, SIG_EP_TYPE
from tests.common import mock_coro
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def button_platform_only(): def button_platform_only():
@ -151,7 +149,7 @@ async def test_button(hass: HomeAssistant, contact_sensor) -> None:
with patch( with patch(
"zigpy.zcl.Cluster.request", "zigpy.zcl.Cluster.request",
return_value=mock_coro([0x00, zcl_f.Status.SUCCESS]), return_value=[0x00, zcl_f.Status.SUCCESS],
): ):
await hass.services.async_call( await hass.services.async_call(
DOMAIN, DOMAIN,
@ -191,7 +189,7 @@ async def test_frost_unlock(hass: HomeAssistant, tuya_water_valve) -> None:
with patch( with patch(
"zigpy.zcl.Cluster.request", "zigpy.zcl.Cluster.request",
return_value=mock_coro([0x00, zcl_f.Status.SUCCESS]), return_value=[0x00, zcl_f.Status.SUCCESS],
): ):
await hass.services.async_call( await hass.services.async_call(
DOMAIN, DOMAIN,

View file

@ -19,7 +19,7 @@ from homeassistant.setup import async_setup_component
from .conftest import SIG_EP_INPUT, SIG_EP_OUTPUT, SIG_EP_TYPE from .conftest import SIG_EP_INPUT, SIG_EP_OUTPUT, SIG_EP_TYPE
from tests.common import async_get_device_automations, async_mock_service, mock_coro from tests.common import async_get_device_automations, async_mock_service
@pytest.fixture(autouse=True, name="stub_blueprint_populate") @pytest.fixture(autouse=True, name="stub_blueprint_populate")
@ -274,7 +274,7 @@ async def test_action(hass: HomeAssistant, device_ias, device_inovelli) -> None:
with patch( with patch(
"zigpy.zcl.Cluster.request", "zigpy.zcl.Cluster.request",
return_value=mock_coro([0x00, zcl_f.Status.SUCCESS]), return_value=[0x00, zcl_f.Status.SUCCESS],
): ):
assert await async_setup_component( assert await async_setup_component(
hass, hass,

View file

@ -23,8 +23,6 @@ from .common import (
) )
from .conftest import SIG_EP_INPUT, SIG_EP_OUTPUT, SIG_EP_PROFILE, SIG_EP_TYPE from .conftest import SIG_EP_INPUT, SIG_EP_OUTPUT, SIG_EP_PROFILE, SIG_EP_TYPE
from tests.common import mock_coro
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
def number_platform_only(): def number_platform_only():
@ -153,7 +151,7 @@ async def test_number(
# change value from HA # change value from HA
with patch( with patch(
"zigpy.zcl.Cluster.write_attributes", "zigpy.zcl.Cluster.write_attributes",
return_value=mock_coro([zcl_f.Status.SUCCESS, zcl_f.Status.SUCCESS]), return_value=[zcl_f.Status.SUCCESS, zcl_f.Status.SUCCESS],
): ):
# set value via UI # set value via UI
await hass.services.async_call( await hass.services.async_call(

View file

@ -27,7 +27,7 @@ import homeassistant.util.dt as dt_util
from .common import async_enable_traffic, find_entity_id from .common import async_enable_traffic, find_entity_id
from .conftest import SIG_EP_INPUT, SIG_EP_OUTPUT, SIG_EP_TYPE from .conftest import SIG_EP_INPUT, SIG_EP_OUTPUT, SIG_EP_TYPE
from tests.common import async_fire_time_changed, mock_coro from tests.common import async_fire_time_changed
@pytest.fixture(autouse=True) @pytest.fixture(autouse=True)
@ -87,7 +87,7 @@ async def test_siren(hass: HomeAssistant, siren) -> None:
# turn on from HA # turn on from HA
with patch( with patch(
"zigpy.device.Device.request", "zigpy.device.Device.request",
return_value=mock_coro([0x00, zcl_f.Status.SUCCESS]), return_value=[0x00, zcl_f.Status.SUCCESS],
), patch( ), patch(
"zigpy.zcl.Cluster.request", "zigpy.zcl.Cluster.request",
side_effect=zigpy.zcl.Cluster.request, side_effect=zigpy.zcl.Cluster.request,
@ -119,7 +119,7 @@ async def test_siren(hass: HomeAssistant, siren) -> None:
# turn off from HA # turn off from HA
with patch( with patch(
"zigpy.device.Device.request", "zigpy.device.Device.request",
return_value=mock_coro([0x01, zcl_f.Status.SUCCESS]), return_value=[0x01, zcl_f.Status.SUCCESS],
), patch( ), patch(
"zigpy.zcl.Cluster.request", "zigpy.zcl.Cluster.request",
side_effect=zigpy.zcl.Cluster.request, side_effect=zigpy.zcl.Cluster.request,
@ -151,7 +151,7 @@ async def test_siren(hass: HomeAssistant, siren) -> None:
# turn on from HA # turn on from HA
with patch( with patch(
"zigpy.device.Device.request", "zigpy.device.Device.request",
return_value=mock_coro([0x00, zcl_f.Status.SUCCESS]), return_value=[0x00, zcl_f.Status.SUCCESS],
), patch( ), patch(
"zigpy.zcl.Cluster.request", "zigpy.zcl.Cluster.request",
side_effect=zigpy.zcl.Cluster.request, side_effect=zigpy.zcl.Cluster.request,

View file

@ -23,7 +23,6 @@ from .common import (
MockModule, MockModule,
MockPlatform, MockPlatform,
get_test_config_dir, get_test_config_dir,
mock_coro,
mock_entity_platform, mock_entity_platform,
mock_integration, mock_integration,
) )
@ -110,7 +109,7 @@ async def test_core_failure_loads_safe_mode(
"""Test failing core setup aborts further setup.""" """Test failing core setup aborts further setup."""
with patch( with patch(
"homeassistant.components.homeassistant.async_setup", "homeassistant.components.homeassistant.async_setup",
return_value=mock_coro(False), return_value=False,
): ):
await bootstrap.async_from_config_dict({"group": {}}, hass) await bootstrap.async_from_config_dict({"group": {}}, hass)

View file

@ -40,7 +40,6 @@ from .common import (
MockPlatform, MockPlatform,
async_fire_time_changed, async_fire_time_changed,
mock_config_flow, mock_config_flow,
mock_coro,
mock_entity_platform, mock_entity_platform,
mock_integration, mock_integration,
) )
@ -605,7 +604,10 @@ async def test_domains_gets_domains_excludes_ignore_and_disabled(
async def test_saving_and_loading(hass: HomeAssistant) -> None: async def test_saving_and_loading(hass: HomeAssistant) -> None:
"""Test that we're saving and loading correctly.""" """Test that we're saving and loading correctly."""
mock_integration( mock_integration(
hass, MockModule("test", async_setup_entry=lambda *args: mock_coro(True)) hass,
MockModule(
"test", async_setup_entry=lambda *args: AsyncMock(return_value=True)
),
) )
mock_entity_platform(hass, "config_flow.test", None) mock_entity_platform(hass, "config_flow.test", None)