diff --git a/homeassistant/components/hassio/addon_panel.py b/homeassistant/components/hassio/addon_panel.py index d8616a82578..9e44b961a1c 100644 --- a/homeassistant/components/hassio/addon_panel.py +++ b/homeassistant/components/hassio/addon_panel.py @@ -75,12 +75,9 @@ class HassIOAddonPanel(HomeAssistantView): return {} -def _register_panel(hass, addon, data): - """Init coroutine to register the panel. - - Return coroutine. - """ - return hass.components.panel_custom.async_register_panel( +async def _register_panel(hass, addon, data): + """Init coroutine to register the panel.""" + await hass.components.panel_custom.async_register_panel( frontend_url_path=addon, webcomponent_name="hassio-main", sidebar_title=data[ATTR_TITLE], diff --git a/homeassistant/components/homekit/__init__.py b/homeassistant/components/homekit/__init__.py index 35620e9e11d..479e1e4dab9 100644 --- a/homeassistant/components/homekit/__init__.py +++ b/homeassistant/components/homekit/__init__.py @@ -484,7 +484,7 @@ class HomeKit: ) _LOGGER.debug("Driver start") - self.hass.async_add_executor_job(self.driver.start) + self.hass.add_job(self.driver.start) self.status = STATUS_RUNNING async def async_stop(self, *args): diff --git a/homeassistant/components/homekit/accessories.py b/homeassistant/components/homekit/accessories.py index 4f0a840770c..ab3d1ae8507 100644 --- a/homeassistant/components/homekit/accessories.py +++ b/homeassistant/components/homekit/accessories.py @@ -165,7 +165,7 @@ class HomeAccessory(Accessory): Run inside the Home Assistant event loop. """ state = self.hass.states.get(self.entity_id) - self.hass.async_add_executor_job(self.update_state_callback, None, None, state) + self.hass.async_add_job(self.update_state_callback, None, None, state) async_track_state_change(self.hass, self.entity_id, self.update_state_callback) battery_charging_state = None diff --git a/homeassistant/components/smhi/weather.py b/homeassistant/components/smhi/weather.py index 0c5450b5ddd..f09491bf611 100644 --- a/homeassistant/components/smhi/weather.py +++ b/homeassistant/components/smhi/weather.py @@ -99,15 +99,6 @@ class SmhiWeather(WeatherEntity): @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self) -> None: """Refresh the forecast data from SMHI weather API.""" - - def fail(): - """Postpone updates.""" - self._fail_count += 1 - if self._fail_count < 3: - self.hass.helpers.event.async_call_later( - RETRY_TIMEOUT, self.retry_update() - ) - try: with async_timeout.timeout(10): self._forecasts = await self.get_weather_forecast() @@ -115,11 +106,15 @@ class SmhiWeather(WeatherEntity): except (asyncio.TimeoutError, SmhiForecastException): _LOGGER.error("Failed to connect to SMHI API, retry in 5 minutes") - fail() + self._fail_count += 1 + if self._fail_count < 3: + self.hass.helpers.event.async_call_later( + RETRY_TIMEOUT, self.retry_update + ) - async def retry_update(self): + async def retry_update(self, _): """Retry refresh weather forecast.""" - self.async_update() + await self.async_update() async def get_weather_forecast(self) -> []: """Return the current forecasts from SMHI API.""" diff --git a/homeassistant/components/vera/__init__.py b/homeassistant/components/vera/__init__.py index c98833a7daa..9b2d44fd94b 100644 --- a/homeassistant/components/vera/__init__.py +++ b/homeassistant/components/vera/__init__.py @@ -90,8 +90,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b controller.start() hass.bus.async_listen_once( - EVENT_HOMEASSISTANT_STOP, - lambda event: hass.async_add_executor_job(controller.stop), + EVENT_HOMEASSISTANT_STOP, lambda event: controller.stop() ) try: diff --git a/script/scaffold/templates/config_flow/tests/test_config_flow.py b/script/scaffold/templates/config_flow/tests/test_config_flow.py index 3d829b5cc32..d6dee8d0bd0 100644 --- a/script/scaffold/templates/config_flow/tests/test_config_flow.py +++ b/script/scaffold/templates/config_flow/tests/test_config_flow.py @@ -1,10 +1,10 @@ """Test the NEW_NAME config flow.""" -from asynctest import patch - from homeassistant import config_entries, setup from homeassistant.components.NEW_DOMAIN.config_flow import CannotConnect, InvalidAuth from homeassistant.components.NEW_DOMAIN.const import DOMAIN +from tests.async_mock import patch + async def test_form(hass): """Test we get the form.""" diff --git a/script/scaffold/templates/config_flow_oauth2/tests/test_config_flow.py b/script/scaffold/templates/config_flow_oauth2/tests/test_config_flow.py index 8a543a04af3..7dda6564507 100644 --- a/script/scaffold/templates/config_flow_oauth2/tests/test_config_flow.py +++ b/script/scaffold/templates/config_flow_oauth2/tests/test_config_flow.py @@ -1,6 +1,4 @@ """Test the NEW_NAME config flow.""" -from asynctest import patch - from homeassistant import config_entries, setup from homeassistant.components.NEW_DOMAIN.const import ( DOMAIN, @@ -9,6 +7,8 @@ from homeassistant.components.NEW_DOMAIN.const import ( ) from homeassistant.helpers import config_entry_oauth2_flow +from tests.async_mock import patch + CLIENT_ID = "1234" CLIENT_SECRET = "5678" diff --git a/tests/async_mock.py b/tests/async_mock.py new file mode 100644 index 00000000000..1942b2ca284 --- /dev/null +++ b/tests/async_mock.py @@ -0,0 +1,8 @@ +"""Mock utilities that are async aware.""" +import sys + +if sys.version_info[:2] < (3, 8): + from asynctest.mock import * # noqa + from asynctest.mock import CoroutineMock as AsyncMock # noqa +else: + from unittest.mock import * # noqa diff --git a/tests/auth/providers/test_command_line.py b/tests/auth/providers/test_command_line.py index abcf124b9c4..3915950cedb 100644 --- a/tests/auth/providers/test_command_line.py +++ b/tests/auth/providers/test_command_line.py @@ -1,7 +1,6 @@ """Tests for the command_line auth provider.""" import os -from unittest.mock import Mock import uuid import pytest @@ -11,7 +10,7 @@ from homeassistant.auth import AuthManager, auth_store, models as auth_models from homeassistant.auth.providers import command_line from homeassistant.const import CONF_TYPE -from tests.common import mock_coro +from tests.async_mock import AsyncMock @pytest.fixture @@ -63,7 +62,7 @@ async def test_match_existing_credentials(store, provider): data={"username": "good-user"}, is_new=False, ) - provider.async_credentials = Mock(return_value=mock_coro([existing])) + provider.async_credentials = AsyncMock(return_value=[existing]) credentials = await provider.async_get_or_create_credentials( {"username": "good-user", "password": "irrelevant"} ) diff --git a/tests/auth/providers/test_homeassistant.py b/tests/auth/providers/test_homeassistant.py index 9cfdfc30aa5..f9ac8fbb92a 100644 --- a/tests/auth/providers/test_homeassistant.py +++ b/tests/auth/providers/test_homeassistant.py @@ -1,7 +1,6 @@ """Test the Home Assistant local auth provider.""" import asyncio -from asynctest import Mock, patch import pytest import voluptuous as vol @@ -12,6 +11,8 @@ from homeassistant.auth.providers import ( homeassistant as hass_auth, ) +from tests.async_mock import Mock, patch + @pytest.fixture def data(hass): diff --git a/tests/auth/providers/test_insecure_example.py b/tests/auth/providers/test_insecure_example.py index c5b3a8db038..c2b16cbafab 100644 --- a/tests/auth/providers/test_insecure_example.py +++ b/tests/auth/providers/test_insecure_example.py @@ -1,5 +1,4 @@ """Tests for the insecure example auth provider.""" -from unittest.mock import Mock import uuid import pytest @@ -7,7 +6,7 @@ import pytest from homeassistant.auth import AuthManager, auth_store, models as auth_models from homeassistant.auth.providers import insecure_example -from tests.common import mock_coro +from tests.async_mock import AsyncMock @pytest.fixture @@ -63,7 +62,7 @@ async def test_match_existing_credentials(store, provider): data={"username": "user-test"}, is_new=False, ) - provider.async_credentials = Mock(return_value=mock_coro([existing])) + provider.async_credentials = AsyncMock(return_value=[existing]) credentials = await provider.async_get_or_create_credentials( {"username": "user-test", "password": "password-test"} ) diff --git a/tests/auth/test_auth_store.py b/tests/auth/test_auth_store.py index 109eb20fb6c..78ab9829ab6 100644 --- a/tests/auth/test_auth_store.py +++ b/tests/auth/test_auth_store.py @@ -1,10 +1,10 @@ """Tests for the auth store.""" import asyncio -import asynctest - from homeassistant.auth import auth_store +from tests.async_mock import patch + async def test_loading_no_group_data_format(hass, hass_storage): """Test we correctly load old data without any groups.""" @@ -229,12 +229,12 @@ async def test_system_groups_store_id_and_name(hass, hass_storage): async def test_loading_race_condition(hass): """Test only one storage load called when concurrent loading occurred .""" store = auth_store.AuthStore(hass) - with asynctest.patch( + with patch( "homeassistant.helpers.entity_registry.async_get_registry" - ) as mock_ent_registry, asynctest.patch( + ) as mock_ent_registry, patch( "homeassistant.helpers.device_registry.async_get_registry" - ) as mock_dev_registry, asynctest.patch( - "homeassistant.helpers.storage.Store.async_load" + ) as mock_dev_registry, patch( + "homeassistant.helpers.storage.Store.async_load", return_value=None ) as mock_load: results = await asyncio.gather(store.async_get_users(), store.async_get_users()) diff --git a/tests/common.py b/tests/common.py index 5a8250e5686..b76fa23bbf2 100644 --- a/tests/common.py +++ b/tests/common.py @@ -14,7 +14,6 @@ import threading import uuid from aiohttp.test_utils import unused_port as get_test_instance_port # noqa -from asynctest import MagicMock, Mock, patch from homeassistant import auth, config_entries, core as ha, loader from homeassistant.auth import ( @@ -60,6 +59,8 @@ import homeassistant.util.dt as date_util from homeassistant.util.unit_system import METRIC_SYSTEM import homeassistant.util.yaml.loader as yaml_loader +from tests.async_mock import AsyncMock, MagicMock, Mock, patch + _LOGGER = logging.getLogger(__name__) INSTANCES = [] CLIENT_ID = "https://example.com/app" @@ -159,20 +160,37 @@ async def async_test_home_assistant(loop): def async_add_job(target, *args): """Add job.""" - if isinstance(target, Mock): - return mock_coro(target(*args)) + check_target = target + while isinstance(check_target, ft.partial): + check_target = check_target.func + + if isinstance(check_target, Mock) and not isinstance(target, AsyncMock): + fut = asyncio.Future() + fut.set_result(target(*args)) + return fut + return orig_async_add_job(target, *args) def async_add_executor_job(target, *args): """Add executor job.""" - if isinstance(target, Mock): - return mock_coro(target(*args)) + check_target = target + while isinstance(check_target, ft.partial): + check_target = check_target.func + + if isinstance(check_target, Mock): + fut = asyncio.Future() + fut.set_result(target(*args)) + return fut + return orig_async_add_executor_job(target, *args) def async_create_task(coroutine): """Create task.""" - if isinstance(coroutine, Mock): - return mock_coro() + if isinstance(coroutine, Mock) and not isinstance(coroutine, AsyncMock): + fut = asyncio.Future() + fut.set_result(None) + return fut + return orig_async_create_task(coroutine) hass.async_add_job = async_add_job @@ -311,15 +329,16 @@ async def async_mock_mqtt_component(hass, config=None): if config is None: config = {mqtt.CONF_BROKER: "mock-broker"} - async def _async_fire_mqtt_message(topic, payload, qos, retain): + @ha.callback + def _async_fire_mqtt_message(topic, payload, qos, retain): async_fire_mqtt_message(hass, topic, payload, qos, retain) with patch("paho.mqtt.client.Client") as mock_client: - mock_client().connect.return_value = 0 - mock_client().subscribe.return_value = (0, 0) - mock_client().unsubscribe.return_value = (0, 0) - mock_client().publish.return_value = (0, 0) - mock_client().publish.side_effect = _async_fire_mqtt_message + mock_client = mock_client.return_value + mock_client.connect.return_value = 0 + mock_client.subscribe.return_value = (0, 0) + mock_client.unsubscribe.return_value = (0, 0) + mock_client.publish.side_effect = _async_fire_mqtt_message result = await async_setup_component(hass, mqtt.DOMAIN, {mqtt.DOMAIN: config}) assert result @@ -503,7 +522,7 @@ class MockModule: self.async_setup = async_setup if setup is None and async_setup is None: - self.async_setup = mock_coro_func(True) + self.async_setup = AsyncMock(return_value=True) if async_setup_entry is not None: self.async_setup_entry = async_setup_entry @@ -561,7 +580,7 @@ class MockPlatform: self.async_setup_entry = async_setup_entry if setup_platform is None and async_setup_platform is None: - self.async_setup_platform = mock_coro_func() + self.async_setup_platform = AsyncMock(return_value=None) class MockEntityPlatform(entity_platform.EntityPlatform): @@ -731,14 +750,10 @@ def mock_coro(return_value=None, exception=None): def mock_coro_func(return_value=None, exception=None): """Return a method to create a coro function that returns a value.""" - @asyncio.coroutine - def coro(*args, **kwargs): - """Fake coroutine.""" - if exception: - raise exception - return return_value + if exception: + return AsyncMock(side_effect=exception) - return coro + return AsyncMock(return_value=return_value) @contextmanager diff --git a/tests/components/adguard/test_config_flow.py b/tests/components/adguard/test_config_flow.py index a0d575deac0..d0e874bacdc 100644 --- a/tests/components/adguard/test_config_flow.py +++ b/tests/components/adguard/test_config_flow.py @@ -1,5 +1,4 @@ """Tests for the AdGuard Home config flow.""" -from unittest.mock import patch import aiohttp @@ -15,7 +14,8 @@ from homeassistant.const import ( CONF_VERIFY_SSL, ) -from tests.common import MockConfigEntry, mock_coro +from tests.async_mock import patch +from tests.common import MockConfigEntry FIXTURE_USER_INPUT = { CONF_HOST: "127.0.0.1", @@ -156,22 +156,16 @@ async def test_hassio_update_instance_running(hass, aioclient_mock): entry.add_to_hass(hass) with patch.object( - hass.config_entries, - "async_forward_entry_setup", - side_effect=lambda *_: mock_coro(True), + hass.config_entries, "async_forward_entry_setup", return_value=True, ) as mock_load: assert await hass.config_entries.async_setup(entry.entry_id) assert entry.state == config_entries.ENTRY_STATE_LOADED assert len(mock_load.mock_calls) == 2 with patch.object( - hass.config_entries, - "async_forward_entry_unload", - side_effect=lambda *_: mock_coro(True), + hass.config_entries, "async_forward_entry_unload", return_value=True, ) as mock_unload, patch.object( - hass.config_entries, - "async_forward_entry_setup", - side_effect=lambda *_: mock_coro(True), + hass.config_entries, "async_forward_entry_setup", return_value=True, ) as mock_load: result = await hass.config_entries.flow.async_init( "adguard", diff --git a/tests/components/airly/test_config_flow.py b/tests/components/airly/test_config_flow.py index 83e7d5d210e..243a92258eb 100644 --- a/tests/components/airly/test_config_flow.py +++ b/tests/components/airly/test_config_flow.py @@ -2,7 +2,6 @@ import json from airly.exceptions import AirlyError -from asynctest import patch from homeassistant import data_entry_flow from homeassistant.components.airly.const import DOMAIN @@ -15,6 +14,7 @@ from homeassistant.const import ( HTTP_FORBIDDEN, ) +from tests.async_mock import patch from tests.common import MockConfigEntry, load_fixture CONFIG = { diff --git a/tests/components/airvisual/test_config_flow.py b/tests/components/airvisual/test_config_flow.py index 9127e6b2780..fcb2360b6c6 100644 --- a/tests/components/airvisual/test_config_flow.py +++ b/tests/components/airvisual/test_config_flow.py @@ -1,5 +1,4 @@ """Define tests for the AirVisual config flow.""" -from asynctest import patch from pyairvisual.errors import InvalidKeyError, NodeProError from homeassistant import data_entry_flow @@ -21,6 +20,7 @@ from homeassistant.const import ( ) from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/almond/test_config_flow.py b/tests/components/almond/test_config_flow.py index 0b4869ee2a6..d1403c017aa 100644 --- a/tests/components/almond/test_config_flow.py +++ b/tests/components/almond/test_config_flow.py @@ -1,14 +1,13 @@ """Test the Almond config flow.""" import asyncio -from asynctest import patch - from homeassistant import config_entries, data_entry_flow, setup from homeassistant.components.almond import config_flow from homeassistant.components.almond.const import DOMAIN from homeassistant.helpers import config_entry_oauth2_flow -from tests.common import MockConfigEntry, mock_coro +from tests.async_mock import patch +from tests.common import MockConfigEntry CLIENT_ID_VALUE = "1234" CLIENT_SECRET_VALUE = "5678" @@ -16,7 +15,7 @@ CLIENT_SECRET_VALUE = "5678" async def test_import(hass): """Test that we can import a config entry.""" - with patch("pyalmond.WebAlmondAPI.async_list_apps", side_effect=mock_coro): + with patch("pyalmond.WebAlmondAPI.async_list_apps"): assert await setup.async_setup_component( hass, "almond", diff --git a/tests/components/ambiclimate/test_config_flow.py b/tests/components/ambiclimate/test_config_flow.py index 045eac1328b..6dee15c27f9 100644 --- a/tests/components/ambiclimate/test_config_flow.py +++ b/tests/components/ambiclimate/test_config_flow.py @@ -1,13 +1,12 @@ """Tests for the Ambiclimate config flow.""" import ambiclimate -from asynctest import Mock, patch from homeassistant import data_entry_flow from homeassistant.components.ambiclimate import config_flow from homeassistant.setup import async_setup_component from homeassistant.util import aiohttp -from tests.common import mock_coro +from tests.async_mock import AsyncMock, patch async def init_config_flow(hass): @@ -67,9 +66,7 @@ async def test_full_flow_implementation(hass): assert "response_type=code" in url assert "redirect_uri=https%3A%2F%2Fhass.com%2Fapi%2Fambiclimate" in url - with patch( - "ambiclimate.AmbiclimateOAuth.get_access_token", return_value=mock_coro("test") - ): + with patch("ambiclimate.AmbiclimateOAuth.get_access_token", return_value="test"): result = await flow.async_step_code("123ABC") assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == "Ambiclimate" @@ -77,9 +74,7 @@ async def test_full_flow_implementation(hass): assert result["data"]["client_secret"] == "secret" assert result["data"]["client_id"] == "id" - with patch( - "ambiclimate.AmbiclimateOAuth.get_access_token", return_value=mock_coro(None) - ): + with patch("ambiclimate.AmbiclimateOAuth.get_access_token", return_value=None): result = await flow.async_step_code("123ABC") assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT @@ -96,9 +91,7 @@ async def test_abort_invalid_code(hass): config_flow.register_flow_implementation(hass, None, None) flow = await init_config_flow(hass) - with patch( - "ambiclimate.AmbiclimateOAuth.get_access_token", return_value=mock_coro(None) - ): + with patch("ambiclimate.AmbiclimateOAuth.get_access_token", return_value=None): result = await flow.async_step_code("invalid") assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "access_token" @@ -118,7 +111,7 @@ async def test_already_setup(hass): async def test_view(hass): """Test view.""" - hass.config_entries.flow.async_init = Mock() + hass.config_entries.flow.async_init = AsyncMock() request = aiohttp.MockRequest(b"", query_string="code=test_code") request.app = {"hass": hass} diff --git a/tests/components/arcam_fmj/conftest.py b/tests/components/arcam_fmj/conftest.py index ec9c6bb1f36..e515b71468b 100644 --- a/tests/components/arcam_fmj/conftest.py +++ b/tests/components/arcam_fmj/conftest.py @@ -1,7 +1,6 @@ """Tests for the arcam_fmj component.""" from arcam.fmj.client import Client from arcam.fmj.state import State -from asynctest import Mock import pytest from homeassistant.components.arcam_fmj import DEVICE_SCHEMA @@ -9,6 +8,8 @@ from homeassistant.components.arcam_fmj.const import DOMAIN from homeassistant.components.arcam_fmj.media_player import ArcamFmj from homeassistant.const import CONF_HOST, CONF_PORT +from tests.async_mock import Mock + MOCK_HOST = "127.0.0.1" MOCK_PORT = 1234 MOCK_TURN_ON = { diff --git a/tests/components/arcam_fmj/test_media_player.py b/tests/components/arcam_fmj/test_media_player.py index a6b36a71d1c..5a73e770129 100644 --- a/tests/components/arcam_fmj/test_media_player.py +++ b/tests/components/arcam_fmj/test_media_player.py @@ -2,7 +2,6 @@ from math import isclose from arcam.fmj import DecodeMode2CH, DecodeModeMCH, IncomingAudioFormat, SourceCodes -from asynctest.mock import ANY, MagicMock, Mock, PropertyMock, patch import pytest from homeassistant.components.media_player.const import MEDIA_TYPE_MUSIC @@ -10,6 +9,8 @@ from homeassistant.core import HomeAssistant from .conftest import MOCK_ENTITY_ID, MOCK_HOST, MOCK_NAME, MOCK_PORT +from tests.async_mock import ANY, MagicMock, Mock, PropertyMock, patch + MOCK_TURN_ON = { "service": "switch.turn_on", "data": {"entity_id": "switch.test"}, diff --git a/tests/components/asuswrt/test_sensor.py b/tests/components/asuswrt/test_sensor.py index 991be0bac50..6d58b909280 100644 --- a/tests/components/asuswrt/test_sensor.py +++ b/tests/components/asuswrt/test_sensor.py @@ -2,7 +2,6 @@ from datetime import datetime, timedelta from aioasuswrt.asuswrt import Device -from asynctest import CoroutineMock, patch from homeassistant.components import sensor from homeassistant.components.asuswrt import ( @@ -20,6 +19,7 @@ from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util from homeassistant.util.dt import utcnow +from tests.async_mock import AsyncMock, patch from tests.common import async_fire_time_changed VALID_CONFIG_ROUTER_SSH = { @@ -54,10 +54,10 @@ MOCK_CURRENT_TRANSFER_RATES = [20000000, 10000000] async def test_sensors(hass: HomeAssistant): """Test creating an AsusWRT sensor.""" with patch("homeassistant.components.asuswrt.AsusWrt") as AsusWrt: - AsusWrt().connection.async_connect = CoroutineMock() - AsusWrt().async_get_connected_devices = CoroutineMock(return_value=MOCK_DEVICES) - AsusWrt().async_get_bytes_total = CoroutineMock(return_value=MOCK_BYTES_TOTAL) - AsusWrt().async_get_current_transfer_rates = CoroutineMock( + AsusWrt().connection.async_connect = AsyncMock() + AsusWrt().async_get_connected_devices = AsyncMock(return_value=MOCK_DEVICES) + AsusWrt().async_get_bytes_total = AsyncMock(return_value=MOCK_BYTES_TOTAL) + AsusWrt().async_get_current_transfer_rates = AsyncMock( return_value=MOCK_CURRENT_TRANSFER_RATES ) diff --git a/tests/components/atag/test_config_flow.py b/tests/components/atag/test_config_flow.py index bda4ccc9023..c860b85c240 100644 --- a/tests/components/atag/test_config_flow.py +++ b/tests/components/atag/test_config_flow.py @@ -1,13 +1,13 @@ """Tests for the Atag config flow.""" from unittest.mock import PropertyMock -from asynctest import patch from pyatag import AtagException from homeassistant import config_entries, data_entry_flow from homeassistant.components.atag import DOMAIN from homeassistant.const import CONF_DEVICE, CONF_HOST, CONF_PORT +from tests.async_mock import patch from tests.common import MockConfigEntry FIXTURE_USER_INPUT = { diff --git a/tests/components/august/mocks.py b/tests/components/august/mocks.py index 39b18411d66..0e1e9866c1d 100644 --- a/tests/components/august/mocks.py +++ b/tests/components/august/mocks.py @@ -3,8 +3,6 @@ import json import os import time -from asynctest import mock -from asynctest.mock import CoroutineMock, MagicMock, PropertyMock from august.activity import ( ACTIVITY_ACTIONS_DOOR_OPERATION, ACTIVITY_ACTIONS_DOORBELL_DING, @@ -29,6 +27,8 @@ from homeassistant.components.august import ( ) from homeassistant.setup import async_setup_component +# from tests.async_mock import AsyncMock +from tests.async_mock import AsyncMock, MagicMock, PropertyMock, patch from tests.common import load_fixture @@ -43,10 +43,8 @@ def _mock_get_config(): } -@mock.patch("homeassistant.components.august.gateway.ApiAsync") -@mock.patch( - "homeassistant.components.august.gateway.AuthenticatorAsync.async_authenticate" -) +@patch("homeassistant.components.august.gateway.ApiAsync") +@patch("homeassistant.components.august.gateway.AuthenticatorAsync.async_authenticate") async def _mock_setup_august(hass, api_instance, authenticate_mock, api_mock): """Set up august integration.""" authenticate_mock.side_effect = MagicMock( @@ -150,37 +148,37 @@ async def _mock_setup_august_with_api_side_effects(hass, api_call_side_effects): api_instance = MagicMock(name="Api") if api_call_side_effects["get_lock_detail"]: - type(api_instance).async_get_lock_detail = CoroutineMock( + type(api_instance).async_get_lock_detail = AsyncMock( side_effect=api_call_side_effects["get_lock_detail"] ) if api_call_side_effects["get_operable_locks"]: - type(api_instance).async_get_operable_locks = CoroutineMock( + type(api_instance).async_get_operable_locks = AsyncMock( side_effect=api_call_side_effects["get_operable_locks"] ) if api_call_side_effects["get_doorbells"]: - type(api_instance).async_get_doorbells = CoroutineMock( + type(api_instance).async_get_doorbells = AsyncMock( side_effect=api_call_side_effects["get_doorbells"] ) if api_call_side_effects["get_doorbell_detail"]: - type(api_instance).async_get_doorbell_detail = CoroutineMock( + type(api_instance).async_get_doorbell_detail = AsyncMock( side_effect=api_call_side_effects["get_doorbell_detail"] ) if api_call_side_effects["get_house_activities"]: - type(api_instance).async_get_house_activities = CoroutineMock( + type(api_instance).async_get_house_activities = AsyncMock( side_effect=api_call_side_effects["get_house_activities"] ) if api_call_side_effects["lock_return_activities"]: - type(api_instance).async_lock_return_activities = CoroutineMock( + type(api_instance).async_lock_return_activities = AsyncMock( side_effect=api_call_side_effects["lock_return_activities"] ) if api_call_side_effects["unlock_return_activities"]: - type(api_instance).async_unlock_return_activities = CoroutineMock( + type(api_instance).async_unlock_return_activities = AsyncMock( side_effect=api_call_side_effects["unlock_return_activities"] ) diff --git a/tests/components/august/test_camera.py b/tests/components/august/test_camera.py index e47bafece42..3ec1b2d608c 100644 --- a/tests/components/august/test_camera.py +++ b/tests/components/august/test_camera.py @@ -1,9 +1,8 @@ """The camera tests for the august platform.""" -from asynctest import mock - from homeassistant.const import STATE_IDLE +from tests.async_mock import patch from tests.components.august.mocks import ( _create_august_with_devices, _mock_doorbell_from_fixture, @@ -14,7 +13,7 @@ async def test_create_doorbell(hass, aiohttp_client): """Test creation of a doorbell.""" doorbell_one = await _mock_doorbell_from_fixture(hass, "get_doorbell.json") - with mock.patch.object( + with patch.object( doorbell_one, "async_get_doorbell_image", create=False, return_value="image" ): await _create_august_with_devices(hass, [doorbell_one]) diff --git a/tests/components/august/test_config_flow.py b/tests/components/august/test_config_flow.py index 8d29ba650fa..ed75bc3685c 100644 --- a/tests/components/august/test_config_flow.py +++ b/tests/components/august/test_config_flow.py @@ -1,5 +1,4 @@ """Test the August config flow.""" -from asynctest import patch from august.authenticator import ValidationResult from homeassistant import config_entries, setup @@ -17,6 +16,8 @@ from homeassistant.components.august.exceptions import ( ) from homeassistant.const import CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME +from tests.async_mock import patch + async def test_form(hass): """Test we get the form.""" diff --git a/tests/components/august/test_gateway.py b/tests/components/august/test_gateway.py index f5fe35b4b19..b9d1959d18a 100644 --- a/tests/components/august/test_gateway.py +++ b/tests/components/august/test_gateway.py @@ -1,11 +1,10 @@ """The gateway tests for the august platform.""" from unittest.mock import MagicMock -from asynctest import mock - from homeassistant.components.august.const import DOMAIN from homeassistant.components.august.gateway import AugustGateway +from tests.async_mock import patch from tests.components.august.mocks import _mock_august_authentication, _mock_get_config @@ -14,11 +13,9 @@ async def test_refresh_access_token(hass): await _patched_refresh_access_token(hass, "new_token", 5678) -@mock.patch( - "homeassistant.components.august.gateway.AuthenticatorAsync.async_authenticate" -) -@mock.patch("homeassistant.components.august.gateway.AuthenticatorAsync.should_refresh") -@mock.patch( +@patch("homeassistant.components.august.gateway.AuthenticatorAsync.async_authenticate") +@patch("homeassistant.components.august.gateway.AuthenticatorAsync.should_refresh") +@patch( "homeassistant.components.august.gateway.AuthenticatorAsync.async_refresh_access_token" ) async def _patched_refresh_access_token( diff --git a/tests/components/august/test_init.py b/tests/components/august/test_init.py index c287a26b34f..f29403c9f21 100644 --- a/tests/components/august/test_init.py +++ b/tests/components/august/test_init.py @@ -1,7 +1,6 @@ """The tests for the august platform.""" import asyncio -from asynctest import patch from august.exceptions import AugustApiAIOHTTPError from homeassistant import setup @@ -27,6 +26,7 @@ from homeassistant.const import ( from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import MockConfigEntry from tests.components.august.mocks import ( _create_august_with_devices, diff --git a/tests/components/auth/test_indieauth.py b/tests/components/auth/test_indieauth.py index b359144ab97..3d1ba068c85 100644 --- a/tests/components/auth/test_indieauth.py +++ b/tests/components/auth/test_indieauth.py @@ -1,12 +1,11 @@ """Tests for the client validator.""" import asyncio -from unittest.mock import patch import pytest from homeassistant.components.auth import indieauth -from tests.common import mock_coro +from tests.async_mock import patch from tests.test_util.aiohttp import AiohttpClientMocker @@ -113,9 +112,7 @@ async def test_verify_redirect_uri(): None, "http://ex.com", "http://ex.com/callback" ) - with patch.object( - indieauth, "fetch_redirect_uris", side_effect=lambda *_: mock_coro([]) - ): + with patch.object(indieauth, "fetch_redirect_uris", return_value=[]): # Different domain assert not await indieauth.verify_redirect_uri( None, "http://ex.com", "http://different.com/callback" @@ -174,9 +171,7 @@ async def test_find_link_tag_max_size(hass, mock_session): ) async def test_verify_redirect_uri_android_ios(client_id): """Test that we verify redirect uri correctly for Android/iOS.""" - with patch.object( - indieauth, "fetch_redirect_uris", side_effect=lambda *_: mock_coro([]) - ): + with patch.object(indieauth, "fetch_redirect_uris", return_value=[]): assert await indieauth.verify_redirect_uri( None, client_id, "homeassistant://auth-callback" ) diff --git a/tests/components/automatic/test_device_tracker.py b/tests/components/automatic/test_device_tracker.py index 09ea7c61858..492421a77cc 100644 --- a/tests/components/automatic/test_device_tracker.py +++ b/tests/components/automatic/test_device_tracker.py @@ -3,11 +3,12 @@ from datetime import datetime import logging import aioautomatic -from asynctest import MagicMock, patch from homeassistant.components.automatic.device_tracker import async_setup_scanner from homeassistant.setup import async_setup_component +from tests.async_mock import MagicMock, patch + _LOGGER = logging.getLogger(__name__) diff --git a/tests/components/automation/test_homeassistant.py b/tests/components/automation/test_homeassistant.py index a0985e54976..b0db66e16a9 100644 --- a/tests/components/automation/test_homeassistant.py +++ b/tests/components/automation/test_homeassistant.py @@ -1,11 +1,12 @@ """The tests for the Event automation.""" -from unittest.mock import Mock, patch +from unittest.mock import patch import homeassistant.components.automation as automation from homeassistant.core import CoreState from homeassistant.setup import async_setup_component -from tests.common import async_mock_service, mock_coro +from tests.async_mock import AsyncMock +from tests.common import async_mock_service async def test_if_fires_on_hass_start(hass): @@ -30,8 +31,7 @@ async def test_if_fires_on_hass_start(hass): assert len(calls) == 1 with patch( - "homeassistant.config.async_hass_config_yaml", - Mock(return_value=mock_coro(config)), + "homeassistant.config.async_hass_config_yaml", AsyncMock(return_value=config), ): await hass.services.async_call( automation.DOMAIN, automation.SERVICE_RELOAD, blocking=True diff --git a/tests/components/awair/test_sensor.py b/tests/components/awair/test_sensor.py index 8ae5bb8017f..d1a3b933d05 100644 --- a/tests/components/awair/test_sensor.py +++ b/tests/components/awair/test_sensor.py @@ -5,8 +5,6 @@ from datetime import timedelta import json import logging -from asynctest import patch - from homeassistant.components.awair.sensor import ( ATTR_LAST_API_UPDATE, ATTR_TIMESTAMP, @@ -29,6 +27,7 @@ from homeassistant.const import ( from homeassistant.setup import async_setup_component from homeassistant.util.dt import parse_datetime, utcnow +from tests.async_mock import patch from tests.common import async_fire_time_changed, load_fixture DISCOVERY_CONFIG = {"sensor": {"platform": "awair", "access_token": "qwerty"}} diff --git a/tests/components/aws/test_init.py b/tests/components/aws/test_init.py index c7fa9d0a5c1..045ad2ff609 100644 --- a/tests/components/aws/test_init.py +++ b/tests/components/aws/test_init.py @@ -1,32 +1,32 @@ """Tests for the aws component config and setup.""" -from asynctest import CoroutineMock, MagicMock, patch as async_patch - from homeassistant.components import aws from homeassistant.setup import async_setup_component +from tests.async_mock import AsyncMock, MagicMock, patch as async_patch + class MockAioSession: """Mock AioSession.""" def __init__(self, *args, **kwargs): """Init a mock session.""" - self.get_user = CoroutineMock() - self.invoke = CoroutineMock() - self.publish = CoroutineMock() - self.send_message = CoroutineMock() + self.get_user = AsyncMock() + self.invoke = AsyncMock() + self.publish = AsyncMock() + self.send_message = AsyncMock() def create_client(self, *args, **kwargs): # pylint: disable=no-self-use """Create a mocked client.""" return MagicMock( - __aenter__=CoroutineMock( - return_value=CoroutineMock( + __aenter__=AsyncMock( + return_value=AsyncMock( get_user=self.get_user, # iam invoke=self.invoke, # lambda publish=self.publish, # sns send_message=self.send_message, # sqs ) ), - __aexit__=CoroutineMock(), + __aexit__=AsyncMock(), ) diff --git a/tests/components/axis/test_config_flow.py b/tests/components/axis/test_config_flow.py index e0bf06e3468..d3972332c89 100644 --- a/tests/components/axis/test_config_flow.py +++ b/tests/components/axis/test_config_flow.py @@ -1,11 +1,10 @@ """Test Axis config flow.""" -from asynctest import Mock, patch - from homeassistant.components import axis from homeassistant.components.axis import config_flow from .test_device import MAC, MODEL, NAME, setup_axis_integration +from tests.async_mock import Mock, patch from tests.common import MockConfigEntry diff --git a/tests/components/axis/test_device.py b/tests/components/axis/test_device.py index 3d2ed432c1c..74b0ab3b992 100644 --- a/tests/components/axis/test_device.py +++ b/tests/components/axis/test_device.py @@ -1,13 +1,13 @@ """Test Axis device.""" from copy import deepcopy -from asynctest import Mock, patch import axis as axislib import pytest from homeassistant import config_entries from homeassistant.components import axis +from tests.async_mock import Mock, patch from tests.common import MockConfigEntry MAC = "00408C12345" diff --git a/tests/components/axis/test_init.py b/tests/components/axis/test_init.py index d11f8c91fc3..5803f31d526 100644 --- a/tests/components/axis/test_init.py +++ b/tests/components/axis/test_init.py @@ -6,7 +6,8 @@ from homeassistant.setup import async_setup_component from .test_device import MAC, setup_axis_integration -from tests.common import MockConfigEntry, mock_coro +from tests.async_mock import AsyncMock +from tests.common import MockConfigEntry async def test_setup_no_config(hass): @@ -30,7 +31,7 @@ async def test_setup_entry_fails(hass): config_entry.add_to_hass(hass) mock_device = Mock() - mock_device.async_setup.return_value = mock_coro(False) + mock_device.async_setup = AsyncMock(return_value=False) with patch.object(axis, "AxisNetworkDevice") as mock_device_class: mock_device_class.return_value = mock_device diff --git a/tests/components/braviatv/test_config_flow.py b/tests/components/braviatv/test_config_flow.py index 93d1bccba73..87fa26c242a 100644 --- a/tests/components/braviatv/test_config_flow.py +++ b/tests/components/braviatv/test_config_flow.py @@ -1,11 +1,10 @@ """Define tests for the Bravia TV config flow.""" -from asynctest import patch - from homeassistant import data_entry_flow from homeassistant.components.braviatv.const import CONF_IGNORED_SOURCES, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PIN +from tests.async_mock import patch from tests.common import MockConfigEntry BRAVIA_SYSTEM_INFO = { diff --git a/tests/components/brother/__init__.py b/tests/components/brother/__init__.py index d6c1fedd31d..1a3ba2a3e20 100644 --- a/tests/components/brother/__init__.py +++ b/tests/components/brother/__init__.py @@ -1,11 +1,10 @@ """Tests for Brother Printer integration.""" import json -from asynctest import patch - from homeassistant.components.brother.const import DOMAIN from homeassistant.const import CONF_HOST, CONF_TYPE +from tests.async_mock import patch from tests.common import MockConfigEntry, load_fixture diff --git a/tests/components/brother/test_config_flow.py b/tests/components/brother/test_config_flow.py index 3f07fca49f0..06e58b83522 100644 --- a/tests/components/brother/test_config_flow.py +++ b/tests/components/brother/test_config_flow.py @@ -1,7 +1,6 @@ """Define tests for the Brother Printer config flow.""" import json -from asynctest import patch from brother import SnmpError, UnsupportedModel from homeassistant import data_entry_flow @@ -9,6 +8,7 @@ from homeassistant.components.brother.const import DOMAIN from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF from homeassistant.const import CONF_HOST, CONF_TYPE +from tests.async_mock import patch from tests.common import MockConfigEntry, load_fixture CONFIG = {CONF_HOST: "localhost", CONF_TYPE: "laser"} diff --git a/tests/components/brother/test_init.py b/tests/components/brother/test_init.py index 13378e9dbb9..04c3c130fc9 100644 --- a/tests/components/brother/test_init.py +++ b/tests/components/brother/test_init.py @@ -1,6 +1,4 @@ """Test init of Brother integration.""" -from asynctest import patch - from homeassistant.components.brother.const import DOMAIN from homeassistant.config_entries import ( ENTRY_STATE_LOADED, @@ -9,6 +7,7 @@ from homeassistant.config_entries import ( ) from homeassistant.const import CONF_HOST, CONF_TYPE, STATE_UNAVAILABLE +from tests.async_mock import patch from tests.common import MockConfigEntry from tests.components.brother import init_integration diff --git a/tests/components/brother/test_sensor.py b/tests/components/brother/test_sensor.py index e88c22f3f40..8e1d52fd2a8 100644 --- a/tests/components/brother/test_sensor.py +++ b/tests/components/brother/test_sensor.py @@ -2,8 +2,6 @@ from datetime import timedelta import json -from asynctest import patch - from homeassistant.components.brother.const import UNIT_PAGES from homeassistant.const import ( ATTR_ENTITY_ID, @@ -16,6 +14,7 @@ from homeassistant.const import ( from homeassistant.setup import async_setup_component from homeassistant.util.dt import utcnow +from tests.async_mock import patch from tests.common import async_fire_time_changed, load_fixture from tests.components.brother import init_integration diff --git a/tests/components/caldav/test_calendar.py b/tests/components/caldav/test_calendar.py index fa6f331363f..8e88c6e564e 100644 --- a/tests/components/caldav/test_calendar.py +++ b/tests/components/caldav/test_calendar.py @@ -2,7 +2,6 @@ import datetime from unittest.mock import MagicMock, Mock -from asynctest import patch from caldav.objects import Event import pytest @@ -10,6 +9,8 @@ from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.setup import async_setup_component from homeassistant.util import dt +from tests.async_mock import patch + # pylint: disable=redefined-outer-name DEVICE_DATA = {"name": "Private Calendar", "device_id": "Private Calendar"} diff --git a/tests/components/camera/test_init.py b/tests/components/camera/test_init.py index e8ab05abb90..401350ec93c 100644 --- a/tests/components/camera/test_init.py +++ b/tests/components/camera/test_init.py @@ -4,7 +4,6 @@ import base64 import io from unittest.mock import PropertyMock, mock_open -from asynctest import patch import pytest from homeassistant.components import camera @@ -15,6 +14,7 @@ from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.components.camera import common diff --git a/tests/components/cast/test_media_player.py b/tests/components/cast/test_media_player.py index e2c1064218d..2adb8b63052 100644 --- a/tests/components/cast/test_media_player.py +++ b/tests/components/cast/test_media_player.py @@ -3,7 +3,6 @@ from typing import Optional from uuid import UUID -from asynctest import MagicMock, Mock, patch import attr import pytest @@ -14,6 +13,7 @@ from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.typing import HomeAssistantType from homeassistant.setup import async_setup_component +from tests.async_mock import MagicMock, Mock, patch from tests.common import MockConfigEntry diff --git a/tests/components/cert_expiry/test_config_flow.py b/tests/components/cert_expiry/test_config_flow.py index 1b2cc175dcb..9618525ef32 100644 --- a/tests/components/cert_expiry/test_config_flow.py +++ b/tests/components/cert_expiry/test_config_flow.py @@ -2,14 +2,13 @@ import socket import ssl -from asynctest import patch - from homeassistant import data_entry_flow from homeassistant.components.cert_expiry.const import DEFAULT_PORT, DOMAIN from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT from .const import HOST, PORT +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/cert_expiry/test_init.py b/tests/components/cert_expiry/test_init.py index d4419b48370..3a2aeb84734 100644 --- a/tests/components/cert_expiry/test_init.py +++ b/tests/components/cert_expiry/test_init.py @@ -1,8 +1,6 @@ """Tests for Cert Expiry setup.""" from datetime import timedelta -from asynctest import patch - from homeassistant.components.cert_expiry.const import DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.config_entries import ENTRY_STATE_LOADED, ENTRY_STATE_NOT_LOADED @@ -12,6 +10,7 @@ import homeassistant.util.dt as dt_util from .const import HOST, PORT +from tests.async_mock import patch from tests.common import MockConfigEntry, async_fire_time_changed diff --git a/tests/components/cert_expiry/test_sensors.py b/tests/components/cert_expiry/test_sensors.py index 6594b0988e7..9fcd1ac3efe 100644 --- a/tests/components/cert_expiry/test_sensors.py +++ b/tests/components/cert_expiry/test_sensors.py @@ -3,13 +3,12 @@ from datetime import timedelta import socket import ssl -from asynctest import patch - from homeassistant.const import CONF_HOST, CONF_PORT, STATE_UNAVAILABLE import homeassistant.util.dt as dt_util from .const import HOST, PORT +from tests.async_mock import patch from tests.common import MockConfigEntry, async_fire_time_changed diff --git a/tests/components/cloud/test_account_link.py b/tests/components/cloud/test_account_link.py index a5f3bef7353..ae34318c452 100644 --- a/tests/components/cloud/test_account_link.py +++ b/tests/components/cloud/test_account_link.py @@ -3,7 +3,6 @@ import asyncio import logging from time import time -from asynctest import CoroutineMock, Mock, patch import pytest from homeassistant import config_entries, data_entry_flow @@ -11,6 +10,7 @@ from homeassistant.components.cloud import account_link from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.util.dt import utcnow +from tests.async_mock import AsyncMock, Mock, patch from tests.common import async_fire_time_changed, mock_platform TEST_DOMAIN = "oauth2_test" @@ -109,7 +109,7 @@ async def test_implementation(hass, flow_handler): flow_finished = asyncio.Future() helper = Mock( - async_get_authorize_url=CoroutineMock(return_value="http://example.com/auth"), + async_get_authorize_url=AsyncMock(return_value="http://example.com/auth"), async_get_tokens=Mock(return_value=flow_finished), ) diff --git a/tests/components/cloud/test_alexa_config.py b/tests/components/cloud/test_alexa_config.py index f65b810d690..c239636e1d3 100644 --- a/tests/components/cloud/test_alexa_config.py +++ b/tests/components/cloud/test_alexa_config.py @@ -1,12 +1,12 @@ """Test Alexa config.""" import contextlib -from unittest.mock import Mock, patch from homeassistant.components.cloud import ALEXA_SCHEMA, alexa_config from homeassistant.helpers.entity_registry import EVENT_ENTITY_REGISTRY_UPDATED from homeassistant.util.dt import utcnow -from tests.common import async_fire_time_changed, mock_coro +from tests.async_mock import AsyncMock, Mock, patch +from tests.common import async_fire_time_changed async def test_alexa_config_expose_entity_prefs(hass, cloud_prefs): @@ -28,7 +28,7 @@ async def test_alexa_config_report_state(hass, cloud_prefs): assert conf.should_report_state is False assert conf.is_reporting_states is False - with patch.object(conf, "async_get_access_token", return_value=mock_coro("hello")): + with patch.object(conf, "async_get_access_token", AsyncMock(return_value="hello")): await cloud_prefs.async_update(alexa_report_state=True) await hass.async_block_till_done() @@ -60,7 +60,7 @@ async def test_alexa_config_invalidate_token(hass, cloud_prefs, aioclient_mock): cloud_prefs, Mock( alexa_access_token_url="http://example/alexa_token", - auth=Mock(async_check_token=Mock(side_effect=mock_coro)), + auth=Mock(async_check_token=AsyncMock()), websession=hass.helpers.aiohttp_client.async_get_clientsession(), ), ) @@ -189,13 +189,9 @@ async def test_alexa_update_report_state(hass, cloud_prefs): alexa_config.AlexaConfig(hass, ALEXA_SCHEMA({}), cloud_prefs, None) with patch( - "homeassistant.components.cloud.alexa_config.AlexaConfig." - "async_sync_entities", - side_effect=mock_coro, + "homeassistant.components.cloud.alexa_config.AlexaConfig.async_sync_entities", ) as mock_sync, patch( - "homeassistant.components.cloud.alexa_config." - "AlexaConfig.async_enable_proactive_mode", - side_effect=mock_coro, + "homeassistant.components.cloud.alexa_config.AlexaConfig.async_enable_proactive_mode", ): await cloud_prefs.async_update(alexa_report_state=True) await hass.async_block_till_done() diff --git a/tests/components/cloud/test_binary_sensor.py b/tests/components/cloud/test_binary_sensor.py index c4ad22abb2f..38c3067873f 100644 --- a/tests/components/cloud/test_binary_sensor.py +++ b/tests/components/cloud/test_binary_sensor.py @@ -1,11 +1,11 @@ """Tests for the cloud binary sensor.""" from unittest.mock import Mock -from asynctest import patch - from homeassistant.components.cloud.const import DISPATCHER_REMOTE_UPDATE from homeassistant.setup import async_setup_component +from tests.async_mock import patch + async def test_remote_connection_sensor(hass): """Test the remote connection sensor.""" diff --git a/tests/components/cloud/test_client.py b/tests/components/cloud/test_client.py index b9e6524b62e..0ce79daab15 100644 --- a/tests/components/cloud/test_client.py +++ b/tests/components/cloud/test_client.py @@ -12,6 +12,7 @@ from homeassistant.setup import async_setup_component from . import mock_cloud, mock_cloud_prefs +from tests.async_mock import AsyncMock from tests.common import mock_coro from tests.components.alexa import test_smart_home as test_alexa @@ -221,7 +222,7 @@ async def test_set_username(hass): prefs = MagicMock( alexa_enabled=False, google_enabled=False, - async_set_username=MagicMock(return_value=mock_coro()), + async_set_username=AsyncMock(return_value=None), ) client = CloudClient(hass, prefs, None, {}, {}) client.cloud = MagicMock(is_logged_in=True, username="mock-username") diff --git a/tests/components/cloud/test_google_config.py b/tests/components/cloud/test_google_config.py index b08b950a590..9866270473d 100644 --- a/tests/components/cloud/test_google_config.py +++ b/tests/components/cloud/test_google_config.py @@ -1,8 +1,6 @@ """Test the Cloud Google Config.""" from unittest.mock import Mock -from asynctest import patch - from homeassistant.components.cloud import GACTIONS_SCHEMA from homeassistant.components.cloud.google_config import CloudGoogleConfig from homeassistant.components.google_assistant import helpers as ga_helpers @@ -11,7 +9,8 @@ from homeassistant.core import CoreState from homeassistant.helpers.entity_registry import EVENT_ENTITY_REGISTRY_UPDATED from homeassistant.util.dt import utcnow -from tests.common import async_fire_time_changed, mock_coro +from tests.async_mock import AsyncMock, patch +from tests.common import async_fire_time_changed async def test_google_update_report_state(hass, cloud_prefs): @@ -43,12 +42,12 @@ async def test_sync_entities(aioclient_mock, hass, cloud_prefs): GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, - Mock(auth=Mock(async_check_token=Mock(side_effect=mock_coro))), + Mock(auth=Mock(async_check_token=AsyncMock())), ) with patch( "hass_nabucasa.cloud_api.async_google_actions_request_sync", - return_value=mock_coro(Mock(status=HTTP_NOT_FOUND)), + return_value=Mock(status=HTTP_NOT_FOUND), ) as mock_request_sync: assert await config.async_sync_entities("user") == HTTP_NOT_FOUND assert len(mock_request_sync.mock_calls) == 1 diff --git a/tests/components/cloud/test_http_api.py b/tests/components/cloud/test_http_api.py index 2cfca8e6b92..df506d2d8fc 100644 --- a/tests/components/cloud/test_http_api.py +++ b/tests/components/cloud/test_http_api.py @@ -1,9 +1,7 @@ """Tests for the HTTP API for the cloud component.""" import asyncio from ipaddress import ip_network -from unittest.mock import MagicMock, Mock -from asynctest import patch from hass_nabucasa import thingtalk from hass_nabucasa.auth import Unauthenticated, UnknownError from hass_nabucasa.const import STATE_CONNECTED @@ -20,7 +18,7 @@ from homeassistant.core import State from . import mock_cloud, mock_cloud_prefs -from tests.common import mock_coro +from tests.async_mock import AsyncMock, MagicMock, Mock, patch from tests.components.google_assistant import MockConfig SUBSCRIPTION_INFO_URL = "https://api-test.hass.io/subscription_info" @@ -29,9 +27,7 @@ SUBSCRIPTION_INFO_URL = "https://api-test.hass.io/subscription_info" @pytest.fixture() def mock_auth(): """Mock check token.""" - with patch( - "hass_nabucasa.auth.CognitoAuth.async_check_token", side_effect=mock_coro - ): + with patch("hass_nabucasa.auth.CognitoAuth.async_check_token"): yield @@ -89,7 +85,7 @@ async def test_google_actions_sync(mock_cognito, mock_cloud_login, cloud_client) """Test syncing Google Actions.""" with patch( "hass_nabucasa.cloud_api.async_google_actions_request_sync", - return_value=mock_coro(Mock(status=200)), + return_value=Mock(status=200), ) as mock_request_sync: req = await cloud_client.post("/api/cloud/google_actions/sync") assert req.status == 200 @@ -100,7 +96,7 @@ async def test_google_actions_sync_fails(mock_cognito, mock_cloud_login, cloud_c """Test syncing Google Actions gone bad.""" with patch( "hass_nabucasa.cloud_api.async_google_actions_request_sync", - return_value=mock_coro(Mock(status=HTTP_INTERNAL_SERVER_ERROR)), + return_value=Mock(status=HTTP_INTERNAL_SERVER_ERROR), ) as mock_request_sync: req = await cloud_client.post("/api/cloud/google_actions/sync") assert req.status == HTTP_INTERNAL_SERVER_ERROR @@ -109,7 +105,7 @@ async def test_google_actions_sync_fails(mock_cognito, mock_cloud_login, cloud_c async def test_login_view(hass, cloud_client): """Test logging in.""" - hass.data["cloud"] = MagicMock(login=MagicMock(return_value=mock_coro())) + hass.data["cloud"] = MagicMock(login=AsyncMock()) req = await cloud_client.post( "/api/cloud/login", json={"email": "my_username", "password": "my_password"} @@ -184,7 +180,7 @@ async def test_login_view_unknown_error(cloud_client): async def test_logout_view(hass, cloud_client): """Test logging out.""" cloud = hass.data["cloud"] = MagicMock() - cloud.logout.return_value = mock_coro() + cloud.logout = AsyncMock(return_value=None) req = await cloud_client.post("/api/cloud/logout") assert req.status == 200 data = await req.json() @@ -450,8 +446,7 @@ async def test_websocket_subscription_not_logged_in(hass, hass_ws_client): """Test querying the status.""" client = await hass_ws_client(hass) with patch( - "hass_nabucasa.Cloud.fetch_subscription_info", - return_value=mock_coro({"return": "value"}), + "hass_nabucasa.Cloud.fetch_subscription_info", return_value={"return": "value"}, ): await client.send_json({"id": 5, "type": "cloud/subscription"}) response = await client.receive_json() @@ -529,7 +524,7 @@ async def test_enabling_webhook(hass, hass_ws_client, setup_api, mock_cloud_logi """Test we call right code to enable webhooks.""" client = await hass_ws_client(hass) with patch( - "hass_nabucasa.cloudhooks.Cloudhooks.async_create", return_value=mock_coro() + "hass_nabucasa.cloudhooks.Cloudhooks.async_create", return_value={} ) as mock_enable: await client.send_json( {"id": 5, "type": "cloud/cloudhook/create", "webhook_id": "mock-webhook-id"} @@ -544,9 +539,7 @@ async def test_enabling_webhook(hass, hass_ws_client, setup_api, mock_cloud_logi async def test_disabling_webhook(hass, hass_ws_client, setup_api, mock_cloud_login): """Test we call right code to disable webhooks.""" client = await hass_ws_client(hass) - with patch( - "hass_nabucasa.cloudhooks.Cloudhooks.async_delete", return_value=mock_coro() - ) as mock_disable: + with patch("hass_nabucasa.cloudhooks.Cloudhooks.async_delete") as mock_disable: await client.send_json( {"id": 5, "type": "cloud/cloudhook/delete", "webhook_id": "mock-webhook-id"} ) @@ -562,9 +555,7 @@ async def test_enabling_remote(hass, hass_ws_client, setup_api, mock_cloud_login client = await hass_ws_client(hass) cloud = hass.data[DOMAIN] - with patch( - "hass_nabucasa.remote.RemoteUI.connect", return_value=mock_coro() - ) as mock_connect: + with patch("hass_nabucasa.remote.RemoteUI.connect") as mock_connect: await client.send_json({"id": 5, "type": "cloud/remote/connect"}) response = await client.receive_json() assert response["success"] @@ -578,9 +569,7 @@ async def test_disabling_remote(hass, hass_ws_client, setup_api, mock_cloud_logi client = await hass_ws_client(hass) cloud = hass.data[DOMAIN] - with patch( - "hass_nabucasa.remote.RemoteUI.disconnect", return_value=mock_coro() - ) as mock_disconnect: + with patch("hass_nabucasa.remote.RemoteUI.disconnect") as mock_disconnect: await client.send_json({"id": 5, "type": "cloud/remote/disconnect"}) response = await client.receive_json() assert response["success"] @@ -670,9 +659,7 @@ async def test_enabling_remote_trusted_networks_other( client = await hass_ws_client(hass) cloud = hass.data[DOMAIN] - with patch( - "hass_nabucasa.remote.RemoteUI.connect", return_value=mock_coro() - ) as mock_connect: + with patch("hass_nabucasa.remote.RemoteUI.connect") as mock_connect: await client.send_json({"id": 5, "type": "cloud/remote/connect"}) response = await client.receive_json() @@ -885,7 +872,7 @@ async def test_thingtalk_convert(hass, hass_ws_client, setup_api): with patch( "homeassistant.components.cloud.http_api.thingtalk.async_convert", - return_value=mock_coro({"hello": "world"}), + return_value={"hello": "world"}, ): await client.send_json( {"id": 5, "type": "cloud/thingtalk/convert", "query": "some-data"} diff --git a/tests/components/config/test_automation.py b/tests/components/config/test_automation.py index 45ffa1d08ec..1d160870169 100644 --- a/tests/components/config/test_automation.py +++ b/tests/components/config/test_automation.py @@ -1,11 +1,11 @@ """Test Automation config panel.""" import json -from asynctest import patch - from homeassistant.bootstrap import async_setup_component from homeassistant.components import config +from tests.async_mock import patch + async def test_get_device_config(hass, hass_client): """Test getting device config.""" diff --git a/tests/components/config/test_core.py b/tests/components/config/test_core.py index a722333c037..7c87d8da689 100644 --- a/tests/components/config/test_core.py +++ b/tests/components/config/test_core.py @@ -1,5 +1,4 @@ """Test hassbian config.""" -from asynctest import patch import pytest from homeassistant.bootstrap import async_setup_component @@ -8,6 +7,8 @@ from homeassistant.components.websocket_api.const import TYPE_RESULT from homeassistant.const import CONF_UNIT_SYSTEM, CONF_UNIT_SYSTEM_IMPERIAL from homeassistant.util import dt as dt_util, location +from tests.async_mock import patch + ORIG_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE diff --git a/tests/components/config/test_customize.py b/tests/components/config/test_customize.py index d8c9ea19b70..30a475dab77 100644 --- a/tests/components/config/test_customize.py +++ b/tests/components/config/test_customize.py @@ -1,12 +1,12 @@ """Test Customize config panel.""" import json -from asynctest import patch - from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.config import DATA_CUSTOMIZE +from tests.async_mock import patch + async def test_get_entity(hass, hass_client): """Test getting entity.""" diff --git a/tests/components/config/test_group.py b/tests/components/config/test_group.py index d00e0317e9e..f555660fb7a 100644 --- a/tests/components/config/test_group.py +++ b/tests/components/config/test_group.py @@ -2,11 +2,11 @@ import json from unittest.mock import patch -from asynctest import CoroutineMock - from homeassistant.bootstrap import async_setup_component from homeassistant.components import config +from tests.async_mock import AsyncMock + VIEW_NAME = "api:config:group:config" @@ -52,7 +52,7 @@ async def test_update_device_config(hass, hass_client): """Mock writing data.""" written.append(data) - mock_call = CoroutineMock() + mock_call = AsyncMock() with patch("homeassistant.components.config._read", mock_read), patch( "homeassistant.components.config._write", mock_write diff --git a/tests/components/config/test_init.py b/tests/components/config/test_init.py index 7f9b62d71f6..6dd16fef7ec 100644 --- a/tests/components/config/test_init.py +++ b/tests/components/config/test_init.py @@ -1,11 +1,11 @@ """Test config init.""" -from unittest.mock import patch from homeassistant.components import config from homeassistant.const import EVENT_COMPONENT_LOADED from homeassistant.setup import ATTR_COMPONENT, async_setup_component -from tests.common import mock_component, mock_coro +from tests.async_mock import patch +from tests.common import mock_component async def test_config_setup(hass, loop): @@ -20,8 +20,9 @@ async def test_load_on_demand_already_loaded(hass, aiohttp_client): with patch.object(config, "SECTIONS", []), patch.object( config, "ON_DEMAND", ["zwave"] - ), patch("homeassistant.components.config.zwave.async_setup") as stp: - stp.return_value = mock_coro(True) + ), patch( + "homeassistant.components.config.zwave.async_setup", return_value=True + ) as stp: await async_setup_component(hass, "config", {}) @@ -38,8 +39,9 @@ async def test_load_on_demand_on_load(hass, aiohttp_client): assert "config.zwave" not in hass.config.components - with patch("homeassistant.components.config.zwave.async_setup") as stp: - stp.return_value = mock_coro(True) + with patch( + "homeassistant.components.config.zwave.async_setup", return_value=True + ) as stp: hass.bus.async_fire(EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: "zwave"}) await hass.async_block_till_done() diff --git a/tests/components/config/test_scene.py b/tests/components/config/test_scene.py index b51628f87ae..dcaa950f342 100644 --- a/tests/components/config/test_scene.py +++ b/tests/components/config/test_scene.py @@ -1,12 +1,12 @@ """Test Automation config panel.""" import json -from asynctest import patch - from homeassistant.bootstrap import async_setup_component from homeassistant.components import config from homeassistant.util.yaml import dump +from tests.async_mock import patch + async def test_update_scene(hass, hass_client): """Test updating a scene.""" diff --git a/tests/components/conftest.py b/tests/components/conftest.py index 1670e0c2485..96ab3bca543 100644 --- a/tests/components/conftest.py +++ b/tests/components/conftest.py @@ -1,7 +1,8 @@ """Fixtures for component testing.""" -from asynctest import patch import pytest +from tests.async_mock import patch + @pytest.fixture(autouse=True) def prevent_io(): diff --git a/tests/components/coolmaster/test_config_flow.py b/tests/components/coolmaster/test_config_flow.py index 81219c41ff8..49058fc183e 100644 --- a/tests/components/coolmaster/test_config_flow.py +++ b/tests/components/coolmaster/test_config_flow.py @@ -1,9 +1,9 @@ """Test the Coolmaster config flow.""" -from asynctest import patch - from homeassistant import config_entries, setup from homeassistant.components.coolmaster.const import AVAILABLE_MODES, DOMAIN +from tests.async_mock import patch + def _flow_data(): options = {"host": "1.1.1.1"} diff --git a/tests/components/coronavirus/conftest.py b/tests/components/coronavirus/conftest.py index 45d2a00e69d..6e49d2aa164 100644 --- a/tests/components/coronavirus/conftest.py +++ b/tests/components/coronavirus/conftest.py @@ -1,8 +1,9 @@ """Test helpers.""" -from asynctest import Mock, patch import pytest +from tests.async_mock import Mock, patch + @pytest.fixture(autouse=True) def mock_cases(): diff --git a/tests/components/deconz/test_climate.py b/tests/components/deconz/test_climate.py index c03dc72019e..ddc89295cba 100644 --- a/tests/components/deconz/test_climate.py +++ b/tests/components/deconz/test_climate.py @@ -1,14 +1,14 @@ """deCONZ climate platform tests.""" from copy import deepcopy -from asynctest import patch - from homeassistant.components import deconz import homeassistant.components.climate as climate from homeassistant.setup import async_setup_component from .test_gateway import DECONZ_WEB_REQUEST, setup_deconz_integration +from tests.async_mock import patch + SENSORS = { "1": { "id": "Thermostat id", diff --git a/tests/components/deconz/test_cover.py b/tests/components/deconz/test_cover.py index 0eda8eb71ab..4f45e36c5b1 100644 --- a/tests/components/deconz/test_cover.py +++ b/tests/components/deconz/test_cover.py @@ -1,14 +1,14 @@ """deCONZ cover platform tests.""" from copy import deepcopy -from asynctest import patch - from homeassistant.components import deconz import homeassistant.components.cover as cover from homeassistant.setup import async_setup_component from .test_gateway import DECONZ_WEB_REQUEST, setup_deconz_integration +from tests.async_mock import patch + COVERS = { "1": { "id": "Level controllable cover id", diff --git a/tests/components/deconz/test_deconz_event.py b/tests/components/deconz/test_deconz_event.py index dd3289dea23..fc8d4f9d1ba 100644 --- a/tests/components/deconz/test_deconz_event.py +++ b/tests/components/deconz/test_deconz_event.py @@ -1,12 +1,12 @@ """Test deCONZ remote events.""" from copy import deepcopy -from asynctest import Mock - from homeassistant.components.deconz.deconz_event import CONF_DECONZ_EVENT from .test_gateway import DECONZ_WEB_REQUEST, setup_deconz_integration +from tests.common import async_capture_events + SENSORS = { "1": { "id": "Switch 1 id", @@ -67,53 +67,40 @@ async def test_deconz_events(hass): switch_2_battery_level = hass.states.get("sensor.switch_2_battery_level") assert switch_2_battery_level.state == "100" - mock_listener = Mock() - unsub = hass.bus.async_listen(CONF_DECONZ_EVENT, mock_listener) + events = async_capture_events(hass, CONF_DECONZ_EVENT) gateway.api.sensors["1"].update({"state": {"buttonevent": 2000}}) await hass.async_block_till_done() - assert len(mock_listener.mock_calls) == 1 - assert mock_listener.mock_calls[0][1][0].data == { + assert len(events) == 1 + assert events[0].data == { "id": "switch_1", "unique_id": "00:00:00:00:00:00:00:01", "event": 2000, } - unsub() - - mock_listener = Mock() - unsub = hass.bus.async_listen(CONF_DECONZ_EVENT, mock_listener) - gateway.api.sensors["3"].update({"state": {"buttonevent": 2000}}) await hass.async_block_till_done() - assert len(mock_listener.mock_calls) == 1 - assert mock_listener.mock_calls[0][1][0].data == { + assert len(events) == 2 + assert events[1].data == { "id": "switch_3", "unique_id": "00:00:00:00:00:00:00:03", "event": 2000, "gesture": 1, } - unsub() - - mock_listener = Mock() - unsub = hass.bus.async_listen(CONF_DECONZ_EVENT, mock_listener) - gateway.api.sensors["4"].update({"state": {"gesture": 0}}) await hass.async_block_till_done() - assert len(mock_listener.mock_calls) == 1 - assert mock_listener.mock_calls[0][1][0].data == { + assert len(events) == 3 + assert events[2].data == { "id": "switch_4", "unique_id": "00:00:00:00:00:00:00:04", "event": 1000, "gesture": 0, } - unsub() - await gateway.async_reset() assert len(hass.states.async_all()) == 0 diff --git a/tests/components/deconz/test_gateway.py b/tests/components/deconz/test_gateway.py index e8c9da42ada..9af1a3151e8 100644 --- a/tests/components/deconz/test_gateway.py +++ b/tests/components/deconz/test_gateway.py @@ -1,7 +1,6 @@ """Test deCONZ gateway.""" from copy import deepcopy -from asynctest import Mock, patch import pydeconz import pytest @@ -9,6 +8,7 @@ from homeassistant import config_entries from homeassistant.components import deconz, ssdp from homeassistant.helpers.dispatcher import async_dispatcher_connect +from tests.async_mock import Mock, patch from tests.common import MockConfigEntry API_KEY = "1234567890ABCDEF" diff --git a/tests/components/deconz/test_init.py b/tests/components/deconz/test_init.py index 3e2760bc632..8d9d387c91c 100644 --- a/tests/components/deconz/test_init.py +++ b/tests/components/deconz/test_init.py @@ -2,12 +2,12 @@ import asyncio from copy import deepcopy -from asynctest import patch - from homeassistant.components import deconz from .test_gateway import DECONZ_WEB_REQUEST, setup_deconz_integration +from tests.async_mock import patch + ENTRY1_HOST = "1.2.3.4" ENTRY1_PORT = 80 ENTRY1_API_KEY = "1234567890ABCDEF" diff --git a/tests/components/deconz/test_light.py b/tests/components/deconz/test_light.py index e39722fdacb..229c085916e 100644 --- a/tests/components/deconz/test_light.py +++ b/tests/components/deconz/test_light.py @@ -1,14 +1,14 @@ """deCONZ light platform tests.""" from copy import deepcopy -from asynctest import patch - from homeassistant.components import deconz import homeassistant.components.light as light from homeassistant.setup import async_setup_component from .test_gateway import DECONZ_WEB_REQUEST, setup_deconz_integration +from tests.async_mock import patch + GROUPS = { "1": { "id": "Light group id", diff --git a/tests/components/deconz/test_scene.py b/tests/components/deconz/test_scene.py index 3593fa32355..538c849e831 100644 --- a/tests/components/deconz/test_scene.py +++ b/tests/components/deconz/test_scene.py @@ -1,14 +1,14 @@ """deCONZ scene platform tests.""" from copy import deepcopy -from asynctest import patch - from homeassistant.components import deconz import homeassistant.components.scene as scene from homeassistant.setup import async_setup_component from .test_gateway import DECONZ_WEB_REQUEST, setup_deconz_integration +from tests.async_mock import patch + GROUPS = { "1": { "id": "Light group id", diff --git a/tests/components/deconz/test_services.py b/tests/components/deconz/test_services.py index 07985e4d9f4..e880ea1000b 100644 --- a/tests/components/deconz/test_services.py +++ b/tests/components/deconz/test_services.py @@ -1,6 +1,5 @@ """deCONZ service tests.""" -from asynctest import Mock, patch import pytest import voluptuous as vol @@ -9,6 +8,8 @@ from homeassistant.components.deconz.const import CONF_BRIDGE_ID from .test_gateway import BRIDGEID, setup_deconz_integration +from tests.async_mock import Mock, patch + GROUP = { "1": { "id": "Group 1 id", diff --git a/tests/components/deconz/test_switch.py b/tests/components/deconz/test_switch.py index 6e151ebd47a..b441868859b 100644 --- a/tests/components/deconz/test_switch.py +++ b/tests/components/deconz/test_switch.py @@ -1,14 +1,14 @@ """deCONZ switch platform tests.""" from copy import deepcopy -from asynctest import patch - from homeassistant.components import deconz import homeassistant.components.switch as switch from homeassistant.setup import async_setup_component from .test_gateway import DECONZ_WEB_REQUEST, setup_deconz_integration +from tests.async_mock import patch + SWITCHES = { "1": { "id": "On off switch id", diff --git a/tests/components/demo/test_media_player.py b/tests/components/demo/test_media_player.py index 26d0d2165e7..e663600f84f 100644 --- a/tests/components/demo/test_media_player.py +++ b/tests/components/demo/test_media_player.py @@ -1,5 +1,4 @@ """The tests for the Demo Media player platform.""" -from asynctest import patch import pytest import voluptuous as vol @@ -7,6 +6,7 @@ import homeassistant.components.media_player as mp from homeassistant.helpers.aiohttp_client import DATA_CLIENTSESSION from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.components.media_player import common TEST_ENTITY_ID = "media_player.walkman" diff --git a/tests/components/device_sun_light_trigger/test_init.py b/tests/components/device_sun_light_trigger/test_init.py index 1b51d93ae6c..23e400adac4 100644 --- a/tests/components/device_sun_light_trigger/test_init.py +++ b/tests/components/device_sun_light_trigger/test_init.py @@ -2,7 +2,6 @@ # pylint: disable=protected-access from datetime import datetime -from asynctest import patch import pytest from homeassistant.components import ( @@ -23,6 +22,7 @@ from homeassistant.const import ( from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util +from tests.async_mock import patch from tests.common import async_fire_time_changed diff --git a/tests/components/device_tracker/test_init.py b/tests/components/device_tracker/test_init.py index 6f384faa15c..1a366b0d2df 100644 --- a/tests/components/device_tracker/test_init.py +++ b/tests/components/device_tracker/test_init.py @@ -4,7 +4,6 @@ import json import logging import os -from asynctest import Mock, call, patch import pytest from homeassistant.components import zone @@ -28,6 +27,7 @@ from homeassistant.helpers.json import JSONEncoder from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util +from tests.async_mock import Mock, call, patch from tests.common import ( assert_setup_component, async_fire_time_changed, diff --git a/tests/components/directv/test_config_flow.py b/tests/components/directv/test_config_flow.py index c5cfec50637..78eddf57c30 100644 --- a/tests/components/directv/test_config_flow.py +++ b/tests/components/directv/test_config_flow.py @@ -1,6 +1,5 @@ """Test the DirecTV config flow.""" from aiohttp import ClientError as HTTPClientError -from asynctest import patch from homeassistant.components.directv.const import CONF_RECEIVER_ID, DOMAIN from homeassistant.components.ssdp import ATTR_UPNP_SERIAL @@ -13,6 +12,7 @@ from homeassistant.data_entry_flow import ( ) from homeassistant.helpers.typing import HomeAssistantType +from tests.async_mock import patch from tests.components.directv import ( HOST, MOCK_SSDP_DISCOVERY_INFO, diff --git a/tests/components/directv/test_media_player.py b/tests/components/directv/test_media_player.py index 8b428c1b708..7203325fbbe 100644 --- a/tests/components/directv/test_media_player.py +++ b/tests/components/directv/test_media_player.py @@ -2,7 +2,6 @@ from datetime import datetime, timedelta from typing import Optional -from asynctest import patch from pytest import fixture from homeassistant.components.directv.media_player import ( @@ -55,6 +54,7 @@ from homeassistant.const import ( from homeassistant.helpers.typing import HomeAssistantType from homeassistant.util import dt as dt_util +from tests.async_mock import patch from tests.components.directv import setup_integration from tests.test_util.aiohttp import AiohttpClientMocker diff --git a/tests/components/directv/test_remote.py b/tests/components/directv/test_remote.py index f93d839b78c..b00f62c0e0c 100644 --- a/tests/components/directv/test_remote.py +++ b/tests/components/directv/test_remote.py @@ -1,6 +1,4 @@ """The tests for the DirecTV remote platform.""" -from asynctest import patch - from homeassistant.components.remote import ( ATTR_COMMAND, DOMAIN as REMOTE_DOMAIN, @@ -9,6 +7,7 @@ from homeassistant.components.remote import ( from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON from homeassistant.helpers.typing import HomeAssistantType +from tests.async_mock import patch from tests.components.directv import setup_integration from tests.test_util.aiohttp import AiohttpClientMocker diff --git a/tests/components/discovery/test_init.py b/tests/components/discovery/test_init.py index 86865209de3..9490707e0f6 100644 --- a/tests/components/discovery/test_init.py +++ b/tests/components/discovery/test_init.py @@ -1,7 +1,6 @@ """The tests for the discovery component.""" from unittest.mock import MagicMock -from asynctest import patch import pytest from homeassistant import config_entries @@ -9,6 +8,7 @@ from homeassistant.bootstrap import async_setup_component from homeassistant.components import discovery from homeassistant.util.dt import utcnow +from tests.async_mock import patch from tests.common import async_fire_time_changed, mock_coro # One might consider to "mock" services, but it's easy enough to just use diff --git a/tests/components/doorbird/test_config_flow.py b/tests/components/doorbird/test_config_flow.py index 8b49f87bd0b..7c7c034c6b4 100644 --- a/tests/components/doorbird/test_config_flow.py +++ b/tests/components/doorbird/test_config_flow.py @@ -1,13 +1,12 @@ """Test the DoorBird config flow.""" import urllib -from asynctest import MagicMock, patch - from homeassistant import config_entries, data_entry_flow, setup from homeassistant.components.doorbird import CONF_CUSTOM_URL, CONF_TOKEN from homeassistant.components.doorbird.const import CONF_EVENTS, DOMAIN from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME +from tests.async_mock import MagicMock, patch from tests.common import MockConfigEntry, init_recorder_component VALID_CONFIG = { diff --git a/tests/components/dsmr/test_sensor.py b/tests/components/dsmr/test_sensor.py index 67c6d3bc58d..936a1e68037 100644 --- a/tests/components/dsmr/test_sensor.py +++ b/tests/components/dsmr/test_sensor.py @@ -11,13 +11,13 @@ from decimal import Decimal from itertools import chain, repeat from unittest.mock import DEFAULT, Mock -import asynctest import pytest from homeassistant.bootstrap import async_setup_component from homeassistant.components.dsmr.sensor import DerivativeDSMREntity from homeassistant.const import ENERGY_KILO_WATT_HOUR, TIME_HOURS, VOLUME_CUBIC_METERS +import tests.async_mock from tests.common import assert_setup_component @@ -26,8 +26,8 @@ def mock_connection_factory(monkeypatch): """Mock the create functions for serial and TCP Asyncio connections.""" from dsmr_parser.clients.protocol import DSMRProtocol - transport = asynctest.Mock(spec=asyncio.Transport) - protocol = asynctest.Mock(spec=DSMRProtocol) + transport = tests.async_mock.Mock(spec=asyncio.Transport) + protocol = tests.async_mock.Mock(spec=DSMRProtocol) async def connection_factory(*args, **kwargs): """Return mocked out Asyncio classes.""" @@ -327,7 +327,7 @@ async def test_connection_errors_retry(hass, monkeypatch, mock_connection_factor config = {"platform": "dsmr", "reconnect_interval": 0} # override the mock to have it fail the first time and succeed after - first_fail_connection_factory = asynctest.CoroutineMock( + first_fail_connection_factory = tests.async_mock.AsyncMock( return_value=(transport, protocol), side_effect=chain([TimeoutError], repeat(DEFAULT)), ) diff --git a/tests/components/dynalite/common.py b/tests/components/dynalite/common.py index b90e6120444..f72e3f481b6 100644 --- a/tests/components/dynalite/common.py +++ b/tests/components/dynalite/common.py @@ -1,9 +1,8 @@ """Common functions for tests.""" -from asynctest import CoroutineMock, Mock, call, patch - from homeassistant.components import dynalite from homeassistant.helpers import entity_registry +from tests.async_mock import AsyncMock, Mock, call, patch from tests.common import MockConfigEntry ATTR_SERVICE = "service" @@ -38,7 +37,7 @@ async def create_entity_from_device(hass, device): with patch( "homeassistant.components.dynalite.bridge.DynaliteDevices" ) as mock_dyn_dev: - mock_dyn_dev().async_setup = CoroutineMock(return_value=True) + mock_dyn_dev().async_setup = AsyncMock(return_value=True) assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() new_device_func = mock_dyn_dev.mock_calls[1][2]["new_device_func"] diff --git a/tests/components/dynalite/test_bridge.py b/tests/components/dynalite/test_bridge.py index 0b093fd5c3e..ea73f75a390 100644 --- a/tests/components/dynalite/test_bridge.py +++ b/tests/components/dynalite/test_bridge.py @@ -1,10 +1,9 @@ """Test Dynalite bridge.""" -from asynctest import CoroutineMock, Mock, patch - from homeassistant.components import dynalite from homeassistant.helpers.dispatcher import async_dispatcher_connect +from tests.async_mock import AsyncMock, Mock, patch from tests.common import MockConfigEntry @@ -16,7 +15,7 @@ async def test_update_device(hass): with patch( "homeassistant.components.dynalite.bridge.DynaliteDevices" ) as mock_dyn_dev: - mock_dyn_dev().async_setup = CoroutineMock(return_value=True) + mock_dyn_dev().async_setup = AsyncMock(return_value=True) assert await hass.config_entries.async_setup(entry.entry_id) # Not waiting so it add the devices before registration update_device_func = mock_dyn_dev.mock_calls[1][2]["update_device_func"] @@ -46,7 +45,7 @@ async def test_add_devices_then_register(hass): with patch( "homeassistant.components.dynalite.bridge.DynaliteDevices" ) as mock_dyn_dev: - mock_dyn_dev().async_setup = CoroutineMock(return_value=True) + mock_dyn_dev().async_setup = AsyncMock(return_value=True) assert await hass.config_entries.async_setup(entry.entry_id) # Not waiting so it add the devices before registration new_device_func = mock_dyn_dev.mock_calls[1][2]["new_device_func"] @@ -79,7 +78,7 @@ async def test_register_then_add_devices(hass): with patch( "homeassistant.components.dynalite.bridge.DynaliteDevices" ) as mock_dyn_dev: - mock_dyn_dev().async_setup = CoroutineMock(return_value=True) + mock_dyn_dev().async_setup = AsyncMock(return_value=True) assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() new_device_func = mock_dyn_dev.mock_calls[1][2]["new_device_func"] diff --git a/tests/components/dynalite/test_config_flow.py b/tests/components/dynalite/test_config_flow.py index 1a1cdc16f49..11b4d6b524c 100644 --- a/tests/components/dynalite/test_config_flow.py +++ b/tests/components/dynalite/test_config_flow.py @@ -1,11 +1,11 @@ """Test Dynalite config flow.""" -from asynctest import CoroutineMock, patch import pytest from homeassistant import config_entries from homeassistant.components import dynalite +from tests.async_mock import AsyncMock, patch from tests.common import MockConfigEntry @@ -69,7 +69,7 @@ async def test_existing_update(hass): with patch( "homeassistant.components.dynalite.bridge.DynaliteDevices" ) as mock_dyn_dev: - mock_dyn_dev().async_setup = CoroutineMock(return_value=True) + mock_dyn_dev().async_setup = AsyncMock(return_value=True) assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() mock_dyn_dev().configure.assert_called_once() diff --git a/tests/components/dynalite/test_init.py b/tests/components/dynalite/test_init.py index 8e2290a9c40..8b1393cb32d 100644 --- a/tests/components/dynalite/test_init.py +++ b/tests/components/dynalite/test_init.py @@ -1,12 +1,11 @@ """Test Dynalite __init__.""" -from asynctest import call, patch - import homeassistant.components.dynalite.const as dynalite from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT, CONF_ROOM from homeassistant.setup import async_setup_component +from tests.async_mock import call, patch from tests.common import MockConfigEntry diff --git a/tests/components/dyson/test_air_quality.py b/tests/components/dyson/test_air_quality.py index fcd801616c9..ab11a1ad897 100644 --- a/tests/components/dyson/test_air_quality.py +++ b/tests/components/dyson/test_air_quality.py @@ -2,7 +2,6 @@ import json from unittest import mock -import asynctest from libpurecool.dyson_pure_cool import DysonPureCool from libpurecool.dyson_pure_state_v2 import DysonEnvironmentalSensorV2State @@ -19,6 +18,8 @@ from homeassistant.setup import async_setup_component from .common import load_mock_device +from tests.async_mock import patch + def _get_dyson_purecool_device(): """Return a valid device as provided by the Dyson web services.""" @@ -46,8 +47,8 @@ def _get_config(): } -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -65,8 +66,8 @@ async def test_purecool_aiq_attributes(devices, login, hass): assert attributes[dyson.ATTR_VOC] == 35 -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -108,8 +109,8 @@ async def test_purecool_aiq_update_state(devices, login, hass): assert attributes[dyson.ATTR_VOC] == 55 -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -124,8 +125,8 @@ async def test_purecool_component_setup_only_once(devices, login, hass): assert len(hass.data[dyson.DYSON_AIQ_DEVICES]) == 1 -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -140,8 +141,8 @@ async def test_purecool_aiq_without_discovery(devices, login, hass): assert add_entities_mock.call_count == 0 -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) diff --git a/tests/components/dyson/test_climate.py b/tests/components/dyson/test_climate.py index 345eae6f553..af17d1f0ab4 100644 --- a/tests/components/dyson/test_climate.py +++ b/tests/components/dyson/test_climate.py @@ -2,7 +2,6 @@ import unittest from unittest import mock -import asynctest from libpurecool.const import FocusMode, HeatMode, HeatState, HeatTarget from libpurecool.dyson_pure_hotcool_link import DysonPureHotCoolLink from libpurecool.dyson_pure_state import DysonPureHotCoolState @@ -14,6 +13,7 @@ from homeassistant.setup import async_setup_component from .common import load_mock_device +from tests.async_mock import patch from tests.common import get_test_home_assistant @@ -344,11 +344,11 @@ class DysonTest(unittest.TestCase): assert entity.target_temperature == 23 -@asynctest.patch( +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_device_heat_on(), _get_device_cool()], ) -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) async def test_setup_component_with_parent_discovery( mocked_login, mocked_devices, hass ): diff --git a/tests/components/dyson/test_fan.py b/tests/components/dyson/test_fan.py index 7801c897723..d4db6051960 100644 --- a/tests/components/dyson/test_fan.py +++ b/tests/components/dyson/test_fan.py @@ -3,7 +3,6 @@ import json import unittest from unittest import mock -import asynctest from libpurecool.const import FanMode, FanSpeed, NightMode, Oscillation from libpurecool.dyson_pure_cool import DysonPureCool from libpurecool.dyson_pure_cool_link import DysonPureCoolLink @@ -28,6 +27,7 @@ from homeassistant.setup import async_setup_component from .common import load_mock_device +from tests.async_mock import patch from tests.common import get_test_home_assistant @@ -386,8 +386,8 @@ class DysonTest(unittest.TestCase): dyson_device.set_night_mode.assert_called_with(True) -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecoollink_device()], ) @@ -404,8 +404,8 @@ async def test_purecoollink_attributes(devices, login, hass): assert attributes[ATTR_OSCILLATING] is True -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -426,8 +426,8 @@ async def test_purecool_turn_on(devices, login, hass): assert device.turn_on.call_count == 1 -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -470,8 +470,8 @@ async def test_purecool_set_speed(devices, login, hass): device.set_fan_speed.assert_called_with(FanSpeed.FAN_SPEED_10) -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -492,8 +492,8 @@ async def test_purecool_turn_off(devices, login, hass): assert device.turn_off.call_count == 1 -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -526,8 +526,8 @@ async def test_purecool_set_dyson_speed(devices, login, hass): device.set_fan_speed.assert_called_with(FanSpeed.FAN_SPEED_2) -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -562,8 +562,8 @@ async def test_purecool_oscillate(devices, login, hass): assert device.disable_oscillation.call_count == 1 -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -599,8 +599,8 @@ async def test_purecool_set_night_mode(devices, login, hass): assert device.disable_night_mode.call_count == 1 -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -635,8 +635,8 @@ async def test_purecool_set_auto_mode(devices, login, hass): assert device.disable_auto_mode.call_count == 1 -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -671,8 +671,8 @@ async def test_purecool_set_angle(devices, login, hass): device.enable_oscillation.assert_called_with(90, 180) -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -707,8 +707,8 @@ async def test_purecool_set_flow_direction_front(devices, login, hass): assert device.disable_frontal_direction.call_count == 1 -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -743,8 +743,8 @@ async def test_purecool_set_timer(devices, login, hass): assert device.disable_sleep_timer.call_count == 1 -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -804,8 +804,8 @@ async def test_purecool_update_state(devices, login, hass): assert attributes[dyson.ATTR_DYSON_SPEED_LIST] == _get_supported_speeds() -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) @@ -865,8 +865,8 @@ async def test_purecool_update_state_filter_inv(devices, login, hass): assert attributes[dyson.ATTR_DYSON_SPEED_LIST] == _get_supported_speeds() -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) diff --git a/tests/components/dyson/test_sensor.py b/tests/components/dyson/test_sensor.py index 4d3d1c96101..92bd3bba9aa 100644 --- a/tests/components/dyson/test_sensor.py +++ b/tests/components/dyson/test_sensor.py @@ -2,7 +2,6 @@ import unittest from unittest import mock -import asynctest from libpurecool.dyson_pure_cool import DysonPureCool from libpurecool.dyson_pure_cool_link import DysonPureCoolLink @@ -20,6 +19,7 @@ from homeassistant.setup import async_setup_component from .common import load_mock_device +from tests.async_mock import patch from tests.common import get_test_home_assistant @@ -258,8 +258,8 @@ class DysonTest(unittest.TestCase): assert sensor.entity_id == "sensor.dyson_1" -@asynctest.patch("libpurecool.dyson.DysonAccount.login", return_value=True) -@asynctest.patch( +@patch("libpurecool.dyson.DysonAccount.login", return_value=True) +@patch( "libpurecool.dyson.DysonAccount.devices", return_value=[_get_dyson_purecool_device()], ) diff --git a/tests/components/ee_brightbox/test_device_tracker.py b/tests/components/ee_brightbox/test_device_tracker.py index f862539f1df..64f24ec289c 100644 --- a/tests/components/ee_brightbox/test_device_tracker.py +++ b/tests/components/ee_brightbox/test_device_tracker.py @@ -1,7 +1,6 @@ """Tests for the EE BrightBox device scanner.""" from datetime import datetime -from asynctest import patch from eebrightbox import EEBrightBoxException import pytest @@ -9,6 +8,8 @@ from homeassistant.components.device_tracker import DOMAIN from homeassistant.const import CONF_PASSWORD, CONF_PLATFORM from homeassistant.setup import async_setup_component +from tests.async_mock import patch + def _configure_mock_get_devices(eebrightbox_mock): eebrightbox_instance = eebrightbox_mock.return_value diff --git a/tests/components/elkm1/test_config_flow.py b/tests/components/elkm1/test_config_flow.py index 2f701a2e146..992483529a5 100644 --- a/tests/components/elkm1/test_config_flow.py +++ b/tests/components/elkm1/test_config_flow.py @@ -1,16 +1,16 @@ """Test the Elk-M1 Control config flow.""" -from asynctest import CoroutineMock, MagicMock, PropertyMock, patch - from homeassistant import config_entries, setup from homeassistant.components.elkm1.const import DOMAIN +from tests.async_mock import AsyncMock, MagicMock, PropertyMock, patch + def mock_elk(invalid_auth=None, sync_complete=None): """Mock m1lib Elk.""" mocked_elk = MagicMock() type(mocked_elk).invalid_auth = PropertyMock(return_value=invalid_auth) - type(mocked_elk).sync_complete = CoroutineMock() + type(mocked_elk).sync_complete = AsyncMock() return mocked_elk diff --git a/tests/components/esphome/test_config_flow.py b/tests/components/esphome/test_config_flow.py index 4b951f9a369..b55621226fa 100644 --- a/tests/components/esphome/test_config_flow.py +++ b/tests/components/esphome/test_config_flow.py @@ -1,12 +1,12 @@ """Test config flow.""" from collections import namedtuple -from unittest.mock import MagicMock, patch import pytest from homeassistant.components.esphome import DATA_KEY, config_flow -from tests.common import MockConfigEntry, mock_coro +from tests.async_mock import AsyncMock, MagicMock, patch +from tests.common import MockConfigEntry MockDeviceInfo = namedtuple("DeviceInfo", ["uses_password", "name"]) @@ -24,8 +24,8 @@ def mock_client(): return mock_client mock_client.side_effect = mock_constructor - mock_client.connect.return_value = mock_coro() - mock_client.disconnect.return_value = mock_coro() + mock_client.connect = AsyncMock() + mock_client.disconnect = AsyncMock() yield mock_client @@ -53,7 +53,7 @@ async def test_user_connection_works(hass, mock_client): result = await flow.async_step_user(user_input=None) assert result["type"] == "form" - mock_client.device_info.return_value = mock_coro(MockDeviceInfo(False, "test")) + mock_client.device_info = AsyncMock(return_value=MockDeviceInfo(False, "test")) result = await flow.async_step_user(user_input={"host": "127.0.0.1", "port": 80}) @@ -119,7 +119,7 @@ async def test_user_with_password(hass, mock_client): flow = _setup_flow_handler(hass) await flow.async_step_user(user_input=None) - mock_client.device_info.return_value = mock_coro(MockDeviceInfo(True, "test")) + mock_client.device_info = AsyncMock(return_value=MockDeviceInfo(True, "test")) result = await flow.async_step_user(user_input={"host": "127.0.0.1", "port": 6053}) @@ -142,7 +142,7 @@ async def test_user_invalid_password(hass, mock_api_connection_error, mock_clien flow = _setup_flow_handler(hass) await flow.async_step_user(user_input=None) - mock_client.device_info.return_value = mock_coro(MockDeviceInfo(True, "test")) + mock_client.device_info = AsyncMock(return_value=MockDeviceInfo(True, "test")) await flow.async_step_user(user_input={"host": "127.0.0.1", "port": 6053}) mock_client.connect.side_effect = mock_api_connection_error @@ -163,7 +163,7 @@ async def test_discovery_initiation(hass, mock_client): "properties": {}, } - mock_client.device_info.return_value = mock_coro(MockDeviceInfo(False, "test8266")) + mock_client.device_info = AsyncMock(return_value=MockDeviceInfo(False, "test8266")) result = await flow.async_step_zeroconf(user_input=service_info) assert result["type"] == "form" @@ -245,7 +245,7 @@ async def test_discovery_duplicate_data(hass, mock_client): "properties": {"address": "test8266.local"}, } - mock_client.device_info.return_value = mock_coro(MockDeviceInfo(False, "test8266")) + mock_client.device_info = AsyncMock(return_value=MockDeviceInfo(False, "test8266")) result = await hass.config_entries.flow.async_init( "esphome", data=service_info, context={"source": "zeroconf"} diff --git a/tests/components/flume/test_config_flow.py b/tests/components/flume/test_config_flow.py index 6ce3391c2c6..a408a652f32 100644 --- a/tests/components/flume/test_config_flow.py +++ b/tests/components/flume/test_config_flow.py @@ -1,10 +1,11 @@ """Test the flume config flow.""" -from asynctest import MagicMock, patch import requests.exceptions from homeassistant import config_entries, setup from homeassistant.components.flume.const import DOMAIN +from tests.async_mock import MagicMock, patch + def _get_mocked_flume_device_list(): flume_device_list_mock = MagicMock() diff --git a/tests/components/flunearyou/test_config_flow.py b/tests/components/flunearyou/test_config_flow.py index 21fcb4798db..a3a0d41e885 100644 --- a/tests/components/flunearyou/test_config_flow.py +++ b/tests/components/flunearyou/test_config_flow.py @@ -1,5 +1,4 @@ """Define tests for the flunearyou config flow.""" -from asynctest import patch from pyflunearyou.errors import FluNearYouError from homeassistant import data_entry_flow @@ -7,6 +6,7 @@ from homeassistant.components.flunearyou import DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/flux/test_switch.py b/tests/components/flux/test_switch.py index c0befe8e69c..ed16e94a283 100644 --- a/tests/components/flux/test_switch.py +++ b/tests/components/flux/test_switch.py @@ -1,5 +1,4 @@ """The tests for the Flux switch platform.""" -from asynctest.mock import patch import pytest from homeassistant.components import light, switch @@ -14,6 +13,7 @@ from homeassistant.core import State from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util +from tests.async_mock import patch from tests.common import ( assert_setup_component, async_fire_time_changed, diff --git a/tests/components/freebox/test_config_flow.py b/tests/components/freebox/test_config_flow.py index 4d8fadf0654..a4c8a950299 100644 --- a/tests/components/freebox/test_config_flow.py +++ b/tests/components/freebox/test_config_flow.py @@ -4,7 +4,6 @@ from aiofreepybox.exceptions import ( HttpRequestError, InvalidTokenError, ) -from asynctest import CoroutineMock, patch import pytest from homeassistant import data_entry_flow @@ -12,6 +11,7 @@ from homeassistant.components.freebox.const import DOMAIN from homeassistant.config_entries import SOURCE_DISCOVERY, SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_HOST, CONF_PORT +from tests.async_mock import AsyncMock, patch from tests.common import MockConfigEntry HOST = "myrouter.freeboxos.fr" @@ -22,17 +22,17 @@ PORT = 1234 def mock_controller_connect(): """Mock a successful connection.""" with patch("homeassistant.components.freebox.router.Freepybox") as service_mock: - service_mock.return_value.open = CoroutineMock() - service_mock.return_value.system.get_config = CoroutineMock( + service_mock.return_value.open = AsyncMock() + service_mock.return_value.system.get_config = AsyncMock( return_value={ "mac": "abcd", "model_info": {"pretty_name": "Pretty Model"}, "firmware_version": "123", } ) - service_mock.return_value.lan.get_hosts_list = CoroutineMock() - service_mock.return_value.connection.get_status = CoroutineMock() - service_mock.return_value.close = CoroutineMock() + service_mock.return_value.lan.get_hosts_list = AsyncMock() + service_mock.return_value.connection.get_status = AsyncMock() + service_mock.return_value.close = AsyncMock() yield service_mock diff --git a/tests/components/frontend/test_init.py b/tests/components/frontend/test_init.py index ef254871830..10f55bd4db3 100644 --- a/tests/components/frontend/test_init.py +++ b/tests/components/frontend/test_init.py @@ -1,7 +1,6 @@ """The tests for Home Assistant frontend.""" import re -from asynctest import patch import pytest from homeassistant.components.frontend import ( @@ -17,6 +16,7 @@ from homeassistant.const import HTTP_NOT_FOUND from homeassistant.loader import async_get_integration from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import async_capture_events CONFIG_THEMES = {DOMAIN: {CONF_THEMES: {"happy": {"primary-color": "red"}}}} diff --git a/tests/components/gdacs/test_config_flow.py b/tests/components/gdacs/test_config_flow.py index c3c5f5609c4..10e4312eb38 100644 --- a/tests/components/gdacs/test_config_flow.py +++ b/tests/components/gdacs/test_config_flow.py @@ -1,7 +1,6 @@ """Define tests for the GDACS config flow.""" from datetime import timedelta -from asynctest import patch import pytest from homeassistant import data_entry_flow @@ -13,6 +12,8 @@ from homeassistant.const import ( CONF_SCAN_INTERVAL, ) +from tests.async_mock import patch + @pytest.fixture(name="gdacs_setup", autouse=True) def gdacs_setup_fixture(): diff --git a/tests/components/gdacs/test_geo_location.py b/tests/components/gdacs/test_geo_location.py index 3b49fe2af71..2162340154f 100644 --- a/tests/components/gdacs/test_geo_location.py +++ b/tests/components/gdacs/test_geo_location.py @@ -1,8 +1,6 @@ """The tests for the GDACS Feed integration.""" import datetime -from asynctest import patch - from homeassistant.components import gdacs from homeassistant.components.gdacs import DEFAULT_SCAN_INTERVAL, DOMAIN, FEED from homeassistant.components.gdacs.geo_location import ( @@ -35,6 +33,7 @@ from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util from homeassistant.util.unit_system import IMPERIAL_SYSTEM +from tests.async_mock import patch from tests.common import async_fire_time_changed from tests.components.gdacs import _generate_mock_feed_entry diff --git a/tests/components/gdacs/test_init.py b/tests/components/gdacs/test_init.py index 40bda2a196b..c0ac83ebcc2 100644 --- a/tests/components/gdacs/test_init.py +++ b/tests/components/gdacs/test_init.py @@ -1,8 +1,8 @@ """Define tests for the GDACS general setup.""" -from asynctest import patch - from homeassistant.components.gdacs import DOMAIN, FEED +from tests.async_mock import patch + async def test_component_unload_config_entry(hass, config_entry): """Test that loading and unloading of a config entry works.""" diff --git a/tests/components/gdacs/test_sensor.py b/tests/components/gdacs/test_sensor.py index 5e8fd5ad30f..aa8c2a43428 100644 --- a/tests/components/gdacs/test_sensor.py +++ b/tests/components/gdacs/test_sensor.py @@ -1,6 +1,4 @@ """The tests for the GDACS Feed integration.""" -from asynctest import patch - from homeassistant.components import gdacs from homeassistant.components.gdacs import DEFAULT_SCAN_INTERVAL from homeassistant.components.gdacs.sensor import ( @@ -20,6 +18,7 @@ from homeassistant.const import ( from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util +from tests.async_mock import patch from tests.common import async_fire_time_changed from tests.components.gdacs import _generate_mock_feed_entry diff --git a/tests/components/generic_thermostat/test_climate.py b/tests/components/generic_thermostat/test_climate.py index 264146a6fda..f0b29539ed5 100644 --- a/tests/components/generic_thermostat/test_climate.py +++ b/tests/components/generic_thermostat/test_climate.py @@ -1,7 +1,6 @@ """The tests for the generic_thermostat.""" import datetime -from asynctest import mock import pytest import pytz import voluptuous as vol @@ -32,6 +31,7 @@ from homeassistant.core import DOMAIN as HASS_DOMAIN, CoreState, State, callback from homeassistant.setup import async_setup_component from homeassistant.util.unit_system import METRIC_SYSTEM +from tests.async_mock import patch from tests.common import assert_setup_component, mock_restore_cache from tests.components.climate import common @@ -622,7 +622,7 @@ async def test_temp_change_ac_trigger_on_long_enough(hass, setup_comp_4): fake_changed = datetime.datetime( 1918, 11, 11, 11, 11, 11, tzinfo=datetime.timezone.utc ) - with mock.patch( + with patch( "homeassistant.helpers.condition.dt_util.utcnow", return_value=fake_changed ): calls = _setup_switch(hass, False) @@ -650,7 +650,7 @@ async def test_temp_change_ac_trigger_off_long_enough(hass, setup_comp_4): fake_changed = datetime.datetime( 1918, 11, 11, 11, 11, 11, tzinfo=datetime.timezone.utc ) - with mock.patch( + with patch( "homeassistant.helpers.condition.dt_util.utcnow", return_value=fake_changed ): calls = _setup_switch(hass, True) @@ -733,7 +733,7 @@ async def test_temp_change_ac_trigger_on_long_enough_2(hass, setup_comp_5): fake_changed = datetime.datetime( 1918, 11, 11, 11, 11, 11, tzinfo=datetime.timezone.utc ) - with mock.patch( + with patch( "homeassistant.helpers.condition.dt_util.utcnow", return_value=fake_changed ): calls = _setup_switch(hass, False) @@ -761,7 +761,7 @@ async def test_temp_change_ac_trigger_off_long_enough_2(hass, setup_comp_5): fake_changed = datetime.datetime( 1918, 11, 11, 11, 11, 11, tzinfo=datetime.timezone.utc ) - with mock.patch( + with patch( "homeassistant.helpers.condition.dt_util.utcnow", return_value=fake_changed ): calls = _setup_switch(hass, True) @@ -852,7 +852,7 @@ async def test_temp_change_heater_trigger_on_long_enough(hass, setup_comp_6): fake_changed = datetime.datetime( 1918, 11, 11, 11, 11, 11, tzinfo=datetime.timezone.utc ) - with mock.patch( + with patch( "homeassistant.helpers.condition.dt_util.utcnow", return_value=fake_changed ): calls = _setup_switch(hass, False) @@ -871,7 +871,7 @@ async def test_temp_change_heater_trigger_off_long_enough(hass, setup_comp_6): fake_changed = datetime.datetime( 1918, 11, 11, 11, 11, 11, tzinfo=datetime.timezone.utc ) - with mock.patch( + with patch( "homeassistant.helpers.condition.dt_util.utcnow", return_value=fake_changed ): calls = _setup_switch(hass, True) diff --git a/tests/components/geo_json_events/test_geo_location.py b/tests/components/geo_json_events/test_geo_location.py index 6b7535a8c85..d79fa3cb18d 100644 --- a/tests/components/geo_json_events/test_geo_location.py +++ b/tests/components/geo_json_events/test_geo_location.py @@ -1,6 +1,4 @@ """The tests for the geojson platform.""" -from asynctest.mock import MagicMock, call, patch - from homeassistant.components import geo_location from homeassistant.components.geo_json_events.geo_location import ( ATTR_EXTERNAL_ID, @@ -23,6 +21,7 @@ from homeassistant.helpers.dispatcher import DATA_DISPATCHER from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util +from tests.async_mock import MagicMock, call, patch from tests.common import assert_setup_component, async_fire_time_changed URL = "http://geo.json.local/geo_json_events.json" diff --git a/tests/components/geonetnz_quakes/test_geo_location.py b/tests/components/geonetnz_quakes/test_geo_location.py index 0264baa8e87..89644445ef1 100644 --- a/tests/components/geonetnz_quakes/test_geo_location.py +++ b/tests/components/geonetnz_quakes/test_geo_location.py @@ -1,8 +1,6 @@ """The tests for the GeoNet NZ Quakes Feed integration.""" import datetime -from asynctest import patch - from homeassistant.components import geonetnz_quakes from homeassistant.components.geo_location import ATTR_SOURCE from homeassistant.components.geonetnz_quakes import DEFAULT_SCAN_INTERVAL, DOMAIN, FEED @@ -31,6 +29,7 @@ from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util from homeassistant.util.unit_system import IMPERIAL_SYSTEM +from tests.async_mock import patch from tests.common import async_fire_time_changed from tests.components.geonetnz_quakes import _generate_mock_feed_entry diff --git a/tests/components/geonetnz_quakes/test_init.py b/tests/components/geonetnz_quakes/test_init.py index 85724879f7b..87f2f2a7947 100644 --- a/tests/components/geonetnz_quakes/test_init.py +++ b/tests/components/geonetnz_quakes/test_init.py @@ -1,8 +1,8 @@ """Define tests for the GeoNet NZ Quakes general setup.""" -from asynctest import patch - from homeassistant.components.geonetnz_quakes import DOMAIN, FEED +from tests.async_mock import patch + async def test_component_unload_config_entry(hass, config_entry): """Test that loading and unloading of a config entry works.""" diff --git a/tests/components/geonetnz_quakes/test_sensor.py b/tests/components/geonetnz_quakes/test_sensor.py index 7d7f8333bc0..f02a803994e 100644 --- a/tests/components/geonetnz_quakes/test_sensor.py +++ b/tests/components/geonetnz_quakes/test_sensor.py @@ -1,8 +1,6 @@ """The tests for the GeoNet NZ Quakes Feed integration.""" import datetime -from asynctest import patch - from homeassistant.components import geonetnz_quakes from homeassistant.components.geonetnz_quakes import DEFAULT_SCAN_INTERVAL from homeassistant.components.geonetnz_quakes.sensor import ( @@ -22,6 +20,7 @@ from homeassistant.const import ( from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util +from tests.async_mock import patch from tests.common import async_fire_time_changed from tests.components.geonetnz_quakes import _generate_mock_feed_entry diff --git a/tests/components/geonetnz_volcano/test_init.py b/tests/components/geonetnz_volcano/test_init.py index 3e2566ffb81..4edf8f452fe 100644 --- a/tests/components/geonetnz_volcano/test_init.py +++ b/tests/components/geonetnz_volcano/test_init.py @@ -1,15 +1,15 @@ """Define tests for the GeoNet NZ Volcano general setup.""" -from asynctest import CoroutineMock, patch - from homeassistant.components.geonetnz_volcano import DOMAIN, FEED +from tests.async_mock import AsyncMock, patch + async def test_component_unload_config_entry(hass, config_entry): """Test that loading and unloading of a config entry works.""" config_entry.add_to_hass(hass) with patch( "aio_geojson_geonetnz_volcano.GeonetnzVolcanoFeedManager.update", - new_callable=CoroutineMock, + new_callable=AsyncMock, ) as mock_feed_manager_update: # Load config entry. assert await hass.config_entries.async_setup(config_entry.entry_id) diff --git a/tests/components/geonetnz_volcano/test_sensor.py b/tests/components/geonetnz_volcano/test_sensor.py index 8f71e3c4757..ccf6248bfa9 100644 --- a/tests/components/geonetnz_volcano/test_sensor.py +++ b/tests/components/geonetnz_volcano/test_sensor.py @@ -1,6 +1,4 @@ """The tests for the GeoNet NZ Volcano Feed integration.""" -from asynctest import CoroutineMock, patch - from homeassistant.components import geonetnz_volcano from homeassistant.components.geo_location import ATTR_DISTANCE from homeassistant.components.geonetnz_volcano import DEFAULT_SCAN_INTERVAL @@ -23,6 +21,7 @@ from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util from homeassistant.util.unit_system import IMPERIAL_SYSTEM +from tests.async_mock import AsyncMock, patch from tests.common import async_fire_time_changed from tests.components.geonetnz_volcano import _generate_mock_feed_entry @@ -49,7 +48,7 @@ async def test_setup(hass): # Patching 'utcnow' to gain more control over the timed update. utcnow = dt_util.utcnow() with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch( - "aio_geojson_client.feed.GeoJsonFeed.update", new_callable=CoroutineMock + "aio_geojson_client.feed.GeoJsonFeed.update", new_callable=AsyncMock ) as mock_feed_update: mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3] assert await async_setup_component(hass, geonetnz_volcano.DOMAIN, CONFIG) @@ -139,7 +138,7 @@ async def test_setup_imperial(hass): # Patching 'utcnow' to gain more control over the timed update. utcnow = dt_util.utcnow() with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch( - "aio_geojson_client.feed.GeoJsonFeed.update", new_callable=CoroutineMock + "aio_geojson_client.feed.GeoJsonFeed.update", new_callable=AsyncMock ) as mock_feed_update, patch( "aio_geojson_client.feed.GeoJsonFeed.__init__" ) as mock_feed_init: diff --git a/tests/components/gios/test_config_flow.py b/tests/components/gios/test_config_flow.py index 3a4aff6d9ad..b2f7ceec9e4 100644 --- a/tests/components/gios/test_config_flow.py +++ b/tests/components/gios/test_config_flow.py @@ -1,5 +1,4 @@ """Define tests for the GIOS config flow.""" -from asynctest import patch from gios import ApiError from homeassistant import data_entry_flow @@ -7,6 +6,8 @@ from homeassistant.components.gios import config_flow from homeassistant.components.gios.const import CONF_STATION_ID from homeassistant.const import CONF_NAME +from tests.async_mock import patch + CONFIG = { CONF_NAME: "Foo", CONF_STATION_ID: 123, diff --git a/tests/components/google_assistant/__init__.py b/tests/components/google_assistant/__init__.py index 79684bdeb44..8f6b0908f83 100644 --- a/tests/components/google_assistant/__init__.py +++ b/tests/components/google_assistant/__init__.py @@ -1,8 +1,8 @@ """Tests for the Google Assistant integration.""" -from asynctest.mock import MagicMock - from homeassistant.components.google_assistant import helpers +from tests.async_mock import MagicMock + def mock_google_config_store(agent_user_ids=None): """Fake a storage for google assistant.""" diff --git a/tests/components/google_assistant/test_helpers.py b/tests/components/google_assistant/test_helpers.py index 9f6f83fab59..4943212bd5a 100644 --- a/tests/components/google_assistant/test_helpers.py +++ b/tests/components/google_assistant/test_helpers.py @@ -1,7 +1,6 @@ """Test Google Assistant helpers.""" from datetime import timedelta -from asynctest.mock import Mock, call, patch import pytest from homeassistant.components.google_assistant import helpers @@ -14,6 +13,7 @@ from homeassistant.util import dt from . import MockConfig +from tests.async_mock import Mock, call, patch from tests.common import ( async_capture_events, async_fire_time_changed, diff --git a/tests/components/google_assistant/test_http.py b/tests/components/google_assistant/test_http.py index ff159e4e10c..4b9461e6304 100644 --- a/tests/components/google_assistant/test_http.py +++ b/tests/components/google_assistant/test_http.py @@ -1,8 +1,6 @@ """Test Google http services.""" from datetime import datetime, timedelta, timezone -from asynctest import ANY, patch - from homeassistant.components.google_assistant import GOOGLE_ASSISTANT_SCHEMA from homeassistant.components.google_assistant.const import ( HOMEGRAPH_TOKEN_URL, @@ -14,6 +12,8 @@ from homeassistant.components.google_assistant.http import ( _get_homegraph_token, ) +from tests.async_mock import ANY, patch + DUMMY_CONFIG = GOOGLE_ASSISTANT_SCHEMA( { "project_id": "1234", diff --git a/tests/components/google_assistant/test_report_state.py b/tests/components/google_assistant/test_report_state.py index fd9cad27ffa..7dd3faba7ab 100644 --- a/tests/components/google_assistant/test_report_state.py +++ b/tests/components/google_assistant/test_report_state.py @@ -1,12 +1,11 @@ """Test Google report state.""" -from unittest.mock import patch - from homeassistant.components.google_assistant import error, report_state from homeassistant.util.dt import utcnow from . import BASIC_CONFIG -from tests.common import async_fire_time_changed, mock_coro +from tests.async_mock import AsyncMock, patch +from tests.common import async_fire_time_changed async def test_report_state(hass, caplog): @@ -15,7 +14,7 @@ async def test_report_state(hass, caplog): hass.states.async_set("switch.ac", "on") with patch.object( - BASIC_CONFIG, "async_report_state_all", side_effect=mock_coro + BASIC_CONFIG, "async_report_state_all", AsyncMock() ) as mock_report, patch.object(report_state, "INITIAL_REPORT_DELAY", 0): unsub = report_state.async_enable_report_state(hass, BASIC_CONFIG) @@ -34,7 +33,7 @@ async def test_report_state(hass, caplog): } with patch.object( - BASIC_CONFIG, "async_report_state_all", side_effect=mock_coro + BASIC_CONFIG, "async_report_state_all", AsyncMock() ) as mock_report: hass.states.async_set("light.kitchen", "on") await hass.async_block_till_done() @@ -47,7 +46,7 @@ async def test_report_state(hass, caplog): # Test that state changes that change something that Google doesn't care about # do not trigger a state report. with patch.object( - BASIC_CONFIG, "async_report_state_all", side_effect=mock_coro + BASIC_CONFIG, "async_report_state_all", AsyncMock() ) as mock_report: hass.states.async_set( "light.kitchen", "on", {"irrelevant": "should_be_ignored"} @@ -58,7 +57,7 @@ async def test_report_state(hass, caplog): # Test that entities that we can't query don't report a state with patch.object( - BASIC_CONFIG, "async_report_state_all", side_effect=mock_coro + BASIC_CONFIG, "async_report_state_all", AsyncMock() ) as mock_report, patch( "homeassistant.components.google_assistant.report_state.GoogleEntity.query_serialize", side_effect=error.SmartHomeError("mock-error", "mock-msg"), @@ -72,7 +71,7 @@ async def test_report_state(hass, caplog): unsub() with patch.object( - BASIC_CONFIG, "async_report_state_all", side_effect=mock_coro + BASIC_CONFIG, "async_report_state_all", AsyncMock() ) as mock_report: hass.states.async_set("light.kitchen", "on") await hass.async_block_till_done() diff --git a/tests/components/google_assistant/test_smart_home.py b/tests/components/google_assistant/test_smart_home.py index d3c9da94f04..c469b8b9efe 100644 --- a/tests/components/google_assistant/test_smart_home.py +++ b/tests/components/google_assistant/test_smart_home.py @@ -1,5 +1,4 @@ """Test Google Smart Home.""" -from asynctest import Mock, patch import pytest from homeassistant.components import camera @@ -28,6 +27,7 @@ from homeassistant.setup import async_setup_component from . import BASIC_CONFIG, MockConfig +from tests.async_mock import Mock, patch from tests.common import mock_area_registry, mock_device_registry, mock_registry REQ_ID = "ff36a3cc-ec34-11e6-b1a0-64510650abcf" diff --git a/tests/components/google_assistant/test_trait.py b/tests/components/google_assistant/test_trait.py index fed084586cc..f133db26d89 100644 --- a/tests/components/google_assistant/test_trait.py +++ b/tests/components/google_assistant/test_trait.py @@ -2,7 +2,6 @@ import logging from unittest.mock import Mock -from asynctest import patch import pytest from homeassistant.components import ( @@ -46,6 +45,7 @@ from homeassistant.util import color from . import BASIC_CONFIG, MockConfig +from tests.async_mock import patch from tests.common import async_mock_service _LOGGER = logging.getLogger(__name__) diff --git a/tests/components/griddy/test_config_flow.py b/tests/components/griddy/test_config_flow.py index 1ab29aebece..79f99d7f8b1 100644 --- a/tests/components/griddy/test_config_flow.py +++ b/tests/components/griddy/test_config_flow.py @@ -1,11 +1,11 @@ """Test the Griddy Power config flow.""" import asyncio -from asynctest import MagicMock, patch - from homeassistant import config_entries, setup from homeassistant.components.griddy.const import DOMAIN +from tests.async_mock import MagicMock, patch + async def test_form(hass): """Test we get the form.""" diff --git a/tests/components/griddy/test_sensor.py b/tests/components/griddy/test_sensor.py index 995327a9b56..ae3d0c3be84 100644 --- a/tests/components/griddy/test_sensor.py +++ b/tests/components/griddy/test_sensor.py @@ -2,12 +2,12 @@ import json import os -from asynctest import patch from griddypower.async_api import GriddyPriceData from homeassistant.components.griddy import CONF_LOADZONE, DOMAIN from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import load_fixture diff --git a/tests/components/group/test_light.py b/tests/components/group/test_light.py index 94d78d62877..ed807ed57d9 100644 --- a/tests/components/group/test_light.py +++ b/tests/components/group/test_light.py @@ -1,8 +1,6 @@ """The tests for the Group Light platform.""" from unittest.mock import MagicMock -import asynctest - from homeassistant.components.group import DOMAIN import homeassistant.components.group.light as group from homeassistant.components.light import ( @@ -32,6 +30,8 @@ from homeassistant.const import ( ) from homeassistant.setup import async_setup_component +import tests.async_mock + async def test_default_state(hass): """Test light group default state.""" @@ -559,7 +559,7 @@ async def test_invalid_service_calls(hass): grouped_light = add_entities.call_args[0][0][0] grouped_light.hass = hass - with asynctest.patch.object(hass.services, "async_call") as mock_call: + with tests.async_mock.patch.object(hass.services, "async_call") as mock_call: await grouped_light.async_turn_on(brightness=150, four_oh_four="404") data = {ATTR_ENTITY_ID: ["light.test1", "light.test2"], ATTR_BRIGHTNESS: 150} mock_call.assert_called_once_with( diff --git a/tests/components/harmony/test_config_flow.py b/tests/components/harmony/test_config_flow.py index 30421756d22..079923330e2 100644 --- a/tests/components/harmony/test_config_flow.py +++ b/tests/components/harmony/test_config_flow.py @@ -1,15 +1,15 @@ """Test the Logitech Harmony Hub config flow.""" -from asynctest import CoroutineMock, MagicMock, patch - from homeassistant import config_entries, setup from homeassistant.components.harmony.config_flow import CannotConnect from homeassistant.components.harmony.const import DOMAIN +from tests.async_mock import AsyncMock, MagicMock, patch + def _get_mock_harmonyapi(connect=None, close=None): harmonyapi_mock = MagicMock() - type(harmonyapi_mock).connect = CoroutineMock(return_value=connect) - type(harmonyapi_mock).close = CoroutineMock(return_value=close) + type(harmonyapi_mock).connect = AsyncMock(return_value=connect) + type(harmonyapi_mock).close = AsyncMock(return_value=close) return harmonyapi_mock diff --git a/tests/components/hassio/conftest.py b/tests/components/hassio/conftest.py index 9a50da4ce41..abcf62915b6 100644 --- a/tests/components/hassio/conftest.py +++ b/tests/components/hassio/conftest.py @@ -1,6 +1,5 @@ """Fixtures for Hass.io.""" import os -from unittest.mock import Mock, patch import pytest @@ -10,7 +9,7 @@ from homeassistant.setup import async_setup_component from . import HASSIO_TOKEN -from tests.common import mock_coro +from tests.async_mock import Mock, patch @pytest.fixture @@ -18,7 +17,7 @@ def hassio_env(): """Fixture to inject hassio env.""" with patch.dict(os.environ, {"HASSIO": "127.0.0.1"}), patch( "homeassistant.components.hassio.HassIO.is_connected", - Mock(return_value=mock_coro({"result": "ok", "data": {}})), + return_value={"result": "ok", "data": {}}, ), patch.dict(os.environ, {"HASSIO_TOKEN": "123456"}), patch( "homeassistant.components.hassio.HassIO.get_homeassistant_info", Mock(side_effect=HassioAPIError()), @@ -31,10 +30,10 @@ def hassio_stubs(hassio_env, hass, hass_client, aioclient_mock): """Create mock hassio http client.""" with patch( "homeassistant.components.hassio.HassIO.update_hass_api", - return_value=mock_coro({"result": "ok"}), + return_value={"result": "ok"}, ) as hass_api, patch( "homeassistant.components.hassio.HassIO.update_hass_timezone", - return_value=mock_coro({"result": "ok"}), + return_value={"result": "ok"}, ), patch( "homeassistant.components.hassio.HassIO.get_homeassistant_info", side_effect=HassioAPIError(), diff --git a/tests/components/hassio/test_addon_panel.py b/tests/components/hassio/test_addon_panel.py index d2ad673111d..9b11fd6dfc2 100644 --- a/tests/components/hassio/test_addon_panel.py +++ b/tests/components/hassio/test_addon_panel.py @@ -1,11 +1,9 @@ """Test add-on panel.""" -from unittest.mock import Mock, patch - import pytest from homeassistant.setup import async_setup_component -from tests.common import mock_coro +from tests.async_mock import patch @pytest.fixture(autouse=True) @@ -49,7 +47,6 @@ async def test_hassio_addon_panel_startup(hass, aioclient_mock, hassio_env): with patch( "homeassistant.components.hassio.addon_panel._register_panel", - Mock(return_value=mock_coro()), ) as mock_panel: await async_setup_component(hass, "hassio", {}) await hass.async_block_till_done() @@ -92,7 +89,6 @@ async def test_hassio_addon_panel_api(hass, aioclient_mock, hassio_env, hass_cli with patch( "homeassistant.components.hassio.addon_panel._register_panel", - Mock(return_value=mock_coro()), ) as mock_panel: await async_setup_component(hass, "hassio", {}) await hass.async_block_till_done() diff --git a/tests/components/hassio/test_auth.py b/tests/components/hassio/test_auth.py index 621efa1cb9e..e97c5bc66fb 100644 --- a/tests/components/hassio/test_auth.py +++ b/tests/components/hassio/test_auth.py @@ -1,10 +1,9 @@ """The tests for the hassio component.""" -from unittest.mock import Mock, patch from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR from homeassistant.exceptions import HomeAssistantError -from tests.common import mock_coro +from tests.async_mock import Mock, patch async def test_auth_success(hass, hassio_client_supervisor): @@ -12,7 +11,6 @@ async def test_auth_success(hass, hassio_client_supervisor): with patch( "homeassistant.auth.providers.homeassistant." "HassAuthProvider.async_validate_login", - Mock(return_value=mock_coro()), ) as mock_login: resp = await hassio_client_supervisor.post( "/api/hassio_auth", @@ -29,7 +27,6 @@ async def test_auth_fails_no_supervisor(hass, hassio_client): with patch( "homeassistant.auth.providers.homeassistant." "HassAuthProvider.async_validate_login", - Mock(return_value=mock_coro()), ) as mock_login: resp = await hassio_client.post( "/api/hassio_auth", @@ -46,7 +43,6 @@ async def test_auth_fails_no_auth(hass, hassio_noauth_client): with patch( "homeassistant.auth.providers.homeassistant." "HassAuthProvider.async_validate_login", - Mock(return_value=mock_coro()), ) as mock_login: resp = await hassio_noauth_client.post( "/api/hassio_auth", @@ -110,7 +106,6 @@ async def test_login_success_extra(hass, hassio_client_supervisor): with patch( "homeassistant.auth.providers.homeassistant." "HassAuthProvider.async_validate_login", - Mock(return_value=mock_coro()), ) as mock_login: resp = await hassio_client_supervisor.post( "/api/hassio_auth", @@ -131,7 +126,6 @@ async def test_password_success(hass, hassio_client_supervisor): """Test no auth needed for .""" with patch( "homeassistant.components.hassio.auth.HassIOPasswordReset._change_password", - Mock(return_value=mock_coro()), ) as mock_change: resp = await hassio_client_supervisor.post( "/api/hassio_auth/password_reset", @@ -147,7 +141,6 @@ async def test_password_fails_no_supervisor(hass, hassio_client): """Test if only supervisor can access.""" with patch( "homeassistant.auth.providers.homeassistant.Data.async_save", - Mock(return_value=mock_coro()), ) as mock_save: resp = await hassio_client.post( "/api/hassio_auth/password_reset", @@ -163,7 +156,6 @@ async def test_password_fails_no_auth(hass, hassio_noauth_client): """Test if only supervisor can access.""" with patch( "homeassistant.auth.providers.homeassistant.Data.async_save", - Mock(return_value=mock_coro()), ) as mock_save: resp = await hassio_noauth_client.post( "/api/hassio_auth/password_reset", @@ -179,7 +171,6 @@ async def test_password_no_user(hass, hassio_client_supervisor): """Test no auth needed for .""" with patch( "homeassistant.auth.providers.homeassistant.Data.async_save", - Mock(return_value=mock_coro()), ) as mock_save: resp = await hassio_client_supervisor.post( "/api/hassio_auth/password_reset", diff --git a/tests/components/hassio/test_discovery.py b/tests/components/hassio/test_discovery.py index a0d64440041..fd4fa26f813 100644 --- a/tests/components/hassio/test_discovery.py +++ b/tests/components/hassio/test_discovery.py @@ -1,11 +1,9 @@ """Test config flow.""" -from unittest.mock import Mock, patch - from homeassistant.components.hassio.handler import HassioAPIError from homeassistant.const import EVENT_HOMEASSISTANT_START from homeassistant.setup import async_setup_component -from tests.common import mock_coro +from tests.async_mock import Mock, patch async def test_hassio_discovery_startup(hass, aioclient_mock, hassio_client): @@ -41,7 +39,7 @@ async def test_hassio_discovery_startup(hass, aioclient_mock, hassio_client): with patch( "homeassistant.components.mqtt.config_flow.FlowHandler.async_step_hassio", - Mock(return_value=mock_coro({"type": "abort"})), + return_value={"type": "abort"}, ) as mock_mqtt: hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() @@ -91,13 +89,13 @@ async def test_hassio_discovery_startup_done(hass, aioclient_mock, hassio_client with patch( "homeassistant.components.hassio.HassIO.update_hass_api", - Mock(return_value=mock_coro({"result": "ok"})), + return_value={"result": "ok"}, ), patch( "homeassistant.components.hassio.HassIO.get_homeassistant_info", Mock(side_effect=HassioAPIError()), ), patch( "homeassistant.components.mqtt.config_flow.FlowHandler.async_step_hassio", - Mock(return_value=mock_coro({"type": "abort"})), + return_value={"type": "abort"}, ) as mock_mqtt: await hass.async_start() await async_setup_component(hass, "hassio", {}) @@ -144,7 +142,7 @@ async def test_hassio_discovery_webhook(hass, aioclient_mock, hassio_client): with patch( "homeassistant.components.mqtt.config_flow.FlowHandler.async_step_hassio", - Mock(return_value=mock_coro({"type": "abort"})), + return_value={"type": "abort"}, ) as mock_mqtt: resp = await hassio_client.post( "/api/hassio_push/discovery/testuuid", diff --git a/tests/components/hassio/test_init.py b/tests/components/hassio/test_init.py index 26caec65b40..13bae001448 100644 --- a/tests/components/hassio/test_init.py +++ b/tests/components/hassio/test_init.py @@ -1,7 +1,6 @@ """The tests for the hassio component.""" import os -from asynctest import patch import pytest from homeassistant.auth.const import GROUP_ID_ADMIN @@ -9,6 +8,8 @@ from homeassistant.components import frontend from homeassistant.components.hassio import STORAGE_KEY from homeassistant.setup import async_setup_component +from tests.async_mock import patch + MOCK_ENVIRON = {"HASSIO": "127.0.0.1", "HASSIO_TOKEN": "abcdefgh"} diff --git a/tests/components/heos/conftest.py b/tests/components/heos/conftest.py index 5201b7f7b8a..86be36e8188 100644 --- a/tests/components/heos/conftest.py +++ b/tests/components/heos/conftest.py @@ -1,7 +1,6 @@ """Configuration for HEOS tests.""" from typing import Dict, Sequence -from asynctest.mock import Mock, patch as patch from pyheos import Dispatcher, Heos, HeosPlayer, HeosSource, InputSource, const import pytest @@ -9,6 +8,7 @@ from homeassistant.components import ssdp from homeassistant.components.heos import DOMAIN from homeassistant.const import CONF_HOST +from tests.async_mock import Mock, patch as patch from tests.common import MockConfigEntry diff --git a/tests/components/heos/test_config_flow.py b/tests/components/heos/test_config_flow.py index b83923943bd..d90c4263240 100644 --- a/tests/components/heos/test_config_flow.py +++ b/tests/components/heos/test_config_flow.py @@ -1,7 +1,6 @@ """Tests for the Heos config flow module.""" from urllib.parse import urlparse -from asynctest import patch from pyheos import HeosError from homeassistant import data_entry_flow @@ -10,6 +9,8 @@ from homeassistant.components.heos.config_flow import HeosFlowHandler from homeassistant.components.heos.const import DATA_DISCOVERED_HOSTS from homeassistant.const import CONF_HOST +from tests.async_mock import patch + async def test_flow_aborts_already_setup(hass, config_entry): """Test flow aborts when entry already setup.""" diff --git a/tests/components/heos/test_init.py b/tests/components/heos/test_init.py index cfbdcb9198a..a6852e3db41 100644 --- a/tests/components/heos/test_init.py +++ b/tests/components/heos/test_init.py @@ -1,7 +1,6 @@ """Tests for the init module.""" import asyncio -from asynctest import Mock, patch from pyheos import CommandFailedError, HeosError, const import pytest @@ -20,6 +19,8 @@ from homeassistant.const import CONF_HOST from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.setup import async_setup_component +from tests.async_mock import Mock, patch + async def test_async_setup_creates_entry(hass, config): """Test component setup creates entry from config.""" diff --git a/tests/components/hisense_aehw4a1/test_init.py b/tests/components/hisense_aehw4a1/test_init.py index f2af78fe160..498e8c4c306 100644 --- a/tests/components/hisense_aehw4a1/test_init.py +++ b/tests/components/hisense_aehw4a1/test_init.py @@ -1,11 +1,12 @@ """Tests for the Hisense AEH-W4A1 init file.""" -from asynctest import patch from pyaehw4a1 import exceptions from homeassistant import config_entries, data_entry_flow from homeassistant.components import hisense_aehw4a1 from homeassistant.setup import async_setup_component +from tests.async_mock import patch + async def test_creating_entry_sets_up_climate_discovery(hass): """Test setting up Hisense AEH-W4A1 loads the climate component.""" diff --git a/tests/components/homeassistant/test_init.py b/tests/components/homeassistant/test_init.py index fddd149942e..b9309d70d63 100644 --- a/tests/components/homeassistant/test_init.py +++ b/tests/components/homeassistant/test_init.py @@ -3,7 +3,6 @@ import asyncio import unittest -from asynctest import Mock, patch import pytest import voluptuous as vol import yaml @@ -33,6 +32,7 @@ from homeassistant.exceptions import HomeAssistantError, Unauthorized from homeassistant.helpers import entity from homeassistant.setup import async_setup_component +from tests.async_mock import Mock, patch from tests.common import ( async_capture_events, async_mock_service, diff --git a/tests/components/homekit/test_aidmanager.py b/tests/components/homekit/test_aidmanager.py index 12d12082a33..258f26e78a6 100644 --- a/tests/components/homekit/test_aidmanager.py +++ b/tests/components/homekit/test_aidmanager.py @@ -2,7 +2,6 @@ import os from zlib import adler32 -from asynctest import patch import pytest from homeassistant.components.homekit.aidmanager import ( @@ -13,6 +12,7 @@ from homeassistant.components.homekit.aidmanager import ( from homeassistant.helpers import device_registry from homeassistant.helpers.storage import STORAGE_DIR +from tests.async_mock import patch from tests.common import MockConfigEntry, mock_device_registry, mock_registry diff --git a/tests/components/homekit/test_homekit.py b/tests/components/homekit/test_homekit.py index b63ee6d0bd9..8a1d911ef04 100644 --- a/tests/components/homekit/test_homekit.py +++ b/tests/components/homekit/test_homekit.py @@ -1,7 +1,6 @@ """Tests for the HomeKit component.""" from unittest.mock import ANY, Mock, patch -from asynctest import CoroutineMock import pytest from zeroconf import InterfaceChoice @@ -44,6 +43,7 @@ from homeassistant.core import State from homeassistant.helpers import device_registry from homeassistant.helpers.entityfilter import generate_filter +from tests.async_mock import AsyncMock from tests.common import MockConfigEntry, mock_device_registry, mock_registry from tests.components.homekit.common import patch_debounce @@ -104,7 +104,7 @@ async def test_setup_auto_start_disabled(hass): with patch(f"{PATH_HOMEKIT}.HomeKit") as mock_homekit: mock_homekit.return_value = homekit = Mock() - type(homekit).async_start = CoroutineMock() + type(homekit).async_start = AsyncMock() assert await setup.async_setup_component(hass, DOMAIN, config) mock_homekit.assert_any_call( diff --git a/tests/components/homekit/test_init.py b/tests/components/homekit/test_init.py index e01588305d5..6d01413da8f 100644 --- a/tests/components/homekit/test_init.py +++ b/tests/components/homekit/test_init.py @@ -1,6 +1,4 @@ """Test HomeKit initialization.""" -from asynctest import patch - from homeassistant import core as ha from homeassistant.components import logbook from homeassistant.components.homekit.const import ( @@ -12,6 +10,8 @@ from homeassistant.components.homekit.const import ( from homeassistant.const import ATTR_ENTITY_ID, ATTR_SERVICE from homeassistant.setup import async_setup_component +from tests.async_mock import patch + async def test_humanify_homekit_changed_event(hass, hk_driver): """Test humanifying HomeKit changed event.""" diff --git a/tests/components/homekit_controller/conftest.py b/tests/components/homekit_controller/conftest.py index 99e86335cdb..ac4a0b4b5d6 100644 --- a/tests/components/homekit_controller/conftest.py +++ b/tests/components/homekit_controller/conftest.py @@ -3,9 +3,10 @@ import datetime from unittest import mock from aiohomekit.testing import FakeController -import asynctest import pytest +import tests.async_mock + @pytest.fixture def utcnow(request): @@ -20,5 +21,5 @@ def utcnow(request): def controller(hass): """Replace aiohomekit.Controller with an instance of aiohomekit.testing.FakeController.""" instance = FakeController() - with asynctest.patch("aiohomekit.Controller", return_value=instance): + with tests.async_mock.patch("aiohomekit.Controller", return_value=instance): yield instance diff --git a/tests/components/homekit_controller/test_config_flow.py b/tests/components/homekit_controller/test_config_flow.py index 302104c0f49..a9aef723164 100644 --- a/tests/components/homekit_controller/test_config_flow.py +++ b/tests/components/homekit_controller/test_config_flow.py @@ -5,12 +5,12 @@ import aiohomekit from aiohomekit.model import Accessories, Accessory from aiohomekit.model.characteristics import CharacteristicsTypes from aiohomekit.model.services import ServicesTypes -import asynctest -from asynctest import patch import pytest from homeassistant.components.homekit_controller import config_flow +import tests.async_mock +from tests.async_mock import patch from tests.common import MockConfigEntry PAIRING_START_FORM_ERRORS = [ @@ -63,15 +63,15 @@ def _setup_flow_handler(hass, pairing=None): flow.hass = hass flow.context = {} - finish_pairing = asynctest.CoroutineMock(return_value=pairing) + finish_pairing = tests.async_mock.AsyncMock(return_value=pairing) discovery = mock.Mock() discovery.device_id = "00:00:00:00:00:00" - discovery.start_pairing = asynctest.CoroutineMock(return_value=finish_pairing) + discovery.start_pairing = tests.async_mock.AsyncMock(return_value=finish_pairing) flow.controller = mock.Mock() flow.controller.pairings = {} - flow.controller.find_ip_by_device_id = asynctest.CoroutineMock( + flow.controller.find_ip_by_device_id = tests.async_mock.AsyncMock( return_value=discovery ) @@ -368,7 +368,7 @@ async def test_pair_abort_errors_on_finish(hass, controller, exception, expected # User initiates pairing - this triggers the device to show a pairing code # and then HA to show a pairing form - finish_pairing = asynctest.CoroutineMock(side_effect=exception("error")) + finish_pairing = tests.async_mock.AsyncMock(side_effect=exception("error")) with patch.object(device, "start_pairing", return_value=finish_pairing): result = await hass.config_entries.flow.async_configure(result["flow_id"]) @@ -408,7 +408,7 @@ async def test_pair_form_errors_on_finish(hass, controller, exception, expected) # User initiates pairing - this triggers the device to show a pairing code # and then HA to show a pairing form - finish_pairing = asynctest.CoroutineMock(side_effect=exception("error")) + finish_pairing = tests.async_mock.AsyncMock(side_effect=exception("error")) with patch.object(device, "start_pairing", return_value=finish_pairing): result = await hass.config_entries.flow.async_configure(result["flow_id"]) diff --git a/tests/components/homematicip_cloud/conftest.py b/tests/components/homematicip_cloud/conftest.py index b1933604fbe..3ada7e7de0a 100644 --- a/tests/components/homematicip_cloud/conftest.py +++ b/tests/components/homematicip_cloud/conftest.py @@ -1,5 +1,4 @@ """Initializer helpers for HomematicIP fake server.""" -from asynctest import CoroutineMock, MagicMock, Mock, patch from homematicip.aio.auth import AsyncAuth from homematicip.aio.connection import AsyncConnection from homematicip.aio.home import AsyncHome @@ -23,6 +22,7 @@ from homeassistant.helpers.typing import ConfigType, HomeAssistantType from .helper import AUTH_TOKEN, HAPID, HAPPIN, HomeFactory +from tests.async_mock import AsyncMock, MagicMock, Mock, patch from tests.common import MockConfigEntry @@ -37,8 +37,8 @@ def mock_connection_fixture() -> AsyncConnection: connection._restCall.side_effect = ( # pylint: disable=protected-access _rest_call_side_effect ) - connection.api_call = CoroutineMock(return_value=True) - connection.init = CoroutineMock(side_effect=True) + connection.api_call = AsyncMock(return_value=True) + connection.init = AsyncMock(side_effect=True) return connection diff --git a/tests/components/homematicip_cloud/helper.py b/tests/components/homematicip_cloud/helper.py index 403dbd873be..fede095e57d 100644 --- a/tests/components/homematicip_cloud/helper.py +++ b/tests/components/homematicip_cloud/helper.py @@ -1,7 +1,6 @@ """Helper for HomematicIP Cloud Tests.""" import json -from asynctest import Mock, patch from homematicip.aio.class_maps import ( TYPE_CLASS_MAP, TYPE_GROUP_MAP, @@ -22,6 +21,7 @@ from homeassistant.components.homematicip_cloud.hap import HomematicipHAP from homeassistant.helpers.typing import HomeAssistantType from homeassistant.setup import async_setup_component +from tests.async_mock import Mock, patch from tests.common import load_fixture HAPID = "3014F7110000000000000001" diff --git a/tests/components/homematicip_cloud/test_config_flow.py b/tests/components/homematicip_cloud/test_config_flow.py index e6e145fefba..e9ecab2dbfb 100644 --- a/tests/components/homematicip_cloud/test_config_flow.py +++ b/tests/components/homematicip_cloud/test_config_flow.py @@ -1,6 +1,4 @@ """Tests for HomematicIP Cloud config flow.""" -from asynctest import patch - from homeassistant.components.homematicip_cloud.const import ( DOMAIN as HMIPC_DOMAIN, HMIPC_AUTHTOKEN, @@ -9,6 +7,7 @@ from homeassistant.components.homematicip_cloud.const import ( HMIPC_PIN, ) +from tests.async_mock import patch from tests.common import MockConfigEntry DEFAULT_CONFIG = {HMIPC_HAPID: "ABC123", HMIPC_PIN: "123", HMIPC_NAME: "hmip"} diff --git a/tests/components/homematicip_cloud/test_device.py b/tests/components/homematicip_cloud/test_device.py index 71efac3a7c9..8a8d52d167a 100644 --- a/tests/components/homematicip_cloud/test_device.py +++ b/tests/components/homematicip_cloud/test_device.py @@ -1,5 +1,4 @@ """Common tests for HomematicIP devices.""" -from asynctest import patch from homematicip.base.enums import EventType from homeassistant.components.homematicip_cloud import DOMAIN as HMIPC_DOMAIN @@ -14,6 +13,8 @@ from .helper import ( get_and_check_entity_basics, ) +from tests.async_mock import patch + async def test_hmip_load_all_supported_devices(hass, default_mock_hap_factory): """Ensure that all supported devices could be loaded.""" diff --git a/tests/components/homematicip_cloud/test_hap.py b/tests/components/homematicip_cloud/test_hap.py index e6e143973f3..ca701622e90 100644 --- a/tests/components/homematicip_cloud/test_hap.py +++ b/tests/components/homematicip_cloud/test_hap.py @@ -1,6 +1,5 @@ """Test HomematicIP Cloud accesspoint.""" -from asynctest import Mock, patch from homematicip.aio.auth import AsyncAuth from homematicip.base.base_connection import HmipConnectionError import pytest @@ -22,6 +21,8 @@ from homeassistant.exceptions import ConfigEntryNotReady from .helper import HAPID, HAPPIN +from tests.async_mock import Mock, patch + async def test_auth_setup(hass): """Test auth setup for client registration.""" diff --git a/tests/components/homematicip_cloud/test_init.py b/tests/components/homematicip_cloud/test_init.py index 8f2753bc499..5b201da8aa8 100644 --- a/tests/components/homematicip_cloud/test_init.py +++ b/tests/components/homematicip_cloud/test_init.py @@ -1,6 +1,5 @@ """Test HomematicIP Cloud setup process.""" -from asynctest import CoroutineMock, Mock, patch from homematicip.base.base_connection import HmipConnectionError from homeassistant.components.homematicip_cloud.const import ( @@ -21,6 +20,7 @@ from homeassistant.config_entries import ( from homeassistant.const import CONF_NAME from homeassistant.setup import async_setup_component +from tests.async_mock import AsyncMock, Mock, patch from tests.common import MockConfigEntry @@ -139,12 +139,12 @@ async def test_unload_entry(hass): with patch("homeassistant.components.homematicip_cloud.HomematicipHAP") as mock_hap: instance = mock_hap.return_value - instance.async_setup = CoroutineMock(return_value=True) + instance.async_setup = AsyncMock(return_value=True) instance.home.id = "1" instance.home.modelType = "mock-type" instance.home.name = "mock-name" instance.home.currentAPVersion = "mock-ap-version" - instance.async_reset = CoroutineMock(return_value=True) + instance.async_reset = AsyncMock(return_value=True) assert await async_setup_component(hass, HMIPC_DOMAIN, {}) @@ -181,12 +181,12 @@ async def test_setup_services_and_unload_services(hass): with patch("homeassistant.components.homematicip_cloud.HomematicipHAP") as mock_hap: instance = mock_hap.return_value - instance.async_setup = CoroutineMock(return_value=True) + instance.async_setup = AsyncMock(return_value=True) instance.home.id = "1" instance.home.modelType = "mock-type" instance.home.name = "mock-name" instance.home.currentAPVersion = "mock-ap-version" - instance.async_reset = CoroutineMock(return_value=True) + instance.async_reset = AsyncMock(return_value=True) assert await async_setup_component(hass, HMIPC_DOMAIN, {}) @@ -214,12 +214,12 @@ async def test_setup_two_haps_unload_one_by_one(hass): with patch("homeassistant.components.homematicip_cloud.HomematicipHAP") as mock_hap: instance = mock_hap.return_value - instance.async_setup = CoroutineMock(return_value=True) + instance.async_setup = AsyncMock(return_value=True) instance.home.id = "1" instance.home.modelType = "mock-type" instance.home.name = "mock-name" instance.home.currentAPVersion = "mock-ap-version" - instance.async_reset = CoroutineMock(return_value=True) + instance.async_reset = AsyncMock(return_value=True) assert await async_setup_component(hass, HMIPC_DOMAIN, {}) diff --git a/tests/components/http/test_ban.py b/tests/components/http/test_ban.py index ddf08de42b4..d13581e12a2 100644 --- a/tests/components/http/test_ban.py +++ b/tests/components/http/test_ban.py @@ -7,7 +7,6 @@ from unittest.mock import Mock, mock_open from aiohttp import web from aiohttp.web_exceptions import HTTPUnauthorized from aiohttp.web_middlewares import middleware -from asynctest import patch import pytest import homeassistant.components.http as http @@ -25,6 +24,8 @@ from homeassistant.setup import async_setup_component from . import mock_real_ip +from tests.async_mock import patch + SUPERVISOR_IP = "1.2.3.4" BANNED_IPS = ["200.201.202.203", "100.64.0.2"] BANNED_IPS_WITH_SUPERVISOR = BANNED_IPS + [SUPERVISOR_IP] diff --git a/tests/components/hue/test_bridge.py b/tests/components/hue/test_bridge.py index 780c77e0196..385097514f8 100644 --- a/tests/components/hue/test_bridge.py +++ b/tests/components/hue/test_bridge.py @@ -1,15 +1,16 @@ """Test Hue bridge.""" -from asynctest import CoroutineMock, Mock, patch import pytest from homeassistant.components.hue import bridge, errors from homeassistant.exceptions import ConfigEntryNotReady +from tests.async_mock import AsyncMock, Mock, patch + async def test_bridge_setup(hass): """Test a successful setup.""" entry = Mock() - api = Mock(initialize=CoroutineMock()) + api = Mock(initialize=AsyncMock()) entry.data = {"host": "1.2.3.4", "username": "mock-username"} hue_bridge = bridge.HueBridge(hass, entry, False, False) @@ -92,7 +93,7 @@ async def test_reset_unloads_entry_if_setup(hass): async def test_handle_unauthorized(hass): """Test handling an unauthorized error on update.""" - entry = Mock(async_setup=CoroutineMock()) + entry = Mock(async_setup=AsyncMock()) entry.data = {"host": "1.2.3.4", "username": "mock-username"} hue_bridge = bridge.HueBridge(hass, entry, False, False) diff --git a/tests/components/hue/test_config_flow.py b/tests/components/hue/test_config_flow.py index 87d4dc2b887..b5ea2e4e0ea 100644 --- a/tests/components/hue/test_config_flow.py +++ b/tests/components/hue/test_config_flow.py @@ -5,7 +5,6 @@ from unittest.mock import Mock from aiohttp import client_exceptions import aiohue from aiohue.discovery import URL_NUPNP -from asynctest import CoroutineMock, patch import pytest import voluptuous as vol @@ -13,6 +12,7 @@ from homeassistant import config_entries from homeassistant.components import ssdp from homeassistant.components.hue import config_flow, const +from tests.async_mock import AsyncMock, patch from tests.common import MockConfigEntry @@ -41,7 +41,7 @@ def get_mock_bridge( mock_create_user = create_user mock_bridge.create_user = mock_create_user - mock_bridge.initialize = CoroutineMock() + mock_bridge.initialize = AsyncMock() return mock_bridge @@ -190,7 +190,7 @@ async def test_flow_timeout_discovery(hass): async def test_flow_link_timeout(hass): """Test config flow.""" mock_bridge = get_mock_bridge( - mock_create_user=CoroutineMock(side_effect=asyncio.TimeoutError), + mock_create_user=AsyncMock(side_effect=asyncio.TimeoutError), ) with patch( "homeassistant.components.hue.config_flow.discover_nupnp", @@ -211,7 +211,7 @@ async def test_flow_link_timeout(hass): async def test_flow_link_unknown_error(hass): """Test if a unknown error happened during the linking processes.""" - mock_bridge = get_mock_bridge(mock_create_user=CoroutineMock(side_effect=OSError),) + mock_bridge = get_mock_bridge(mock_create_user=AsyncMock(side_effect=OSError),) with patch( "homeassistant.components.hue.config_flow.discover_nupnp", return_value=[mock_bridge], @@ -232,7 +232,7 @@ async def test_flow_link_unknown_error(hass): async def test_flow_link_button_not_pressed(hass): """Test config flow .""" mock_bridge = get_mock_bridge( - mock_create_user=CoroutineMock(side_effect=aiohue.LinkButtonNotPressed), + mock_create_user=AsyncMock(side_effect=aiohue.LinkButtonNotPressed), ) with patch( "homeassistant.components.hue.config_flow.discover_nupnp", @@ -254,7 +254,7 @@ async def test_flow_link_button_not_pressed(hass): async def test_flow_link_unknown_host(hass): """Test config flow .""" mock_bridge = get_mock_bridge( - mock_create_user=CoroutineMock(side_effect=client_exceptions.ClientOSError), + mock_create_user=AsyncMock(side_effect=client_exceptions.ClientOSError), ) with patch( "homeassistant.components.hue.config_flow.discover_nupnp", diff --git a/tests/components/hue/test_init.py b/tests/components/hue/test_init.py index 51ea3f2ae71..a144902bbc8 100644 --- a/tests/components/hue/test_init.py +++ b/tests/components/hue/test_init.py @@ -1,11 +1,10 @@ """Test Hue setup process.""" from unittest.mock import Mock -from asynctest import CoroutineMock, patch - from homeassistant.components import hue from homeassistant.setup import async_setup_component +from tests.async_mock import AsyncMock, patch from tests.common import MockConfigEntry, mock_coro @@ -102,9 +101,9 @@ async def test_config_passed_to_config_entry(hass): mock_registry = Mock() with patch.object(hue, "HueBridge") as mock_bridge, patch( "homeassistant.helpers.device_registry.async_get_registry", - return_value=mock_coro(mock_registry), + return_value=mock_registry, ): - mock_bridge.return_value.async_setup.return_value = mock_coro(True) + mock_bridge.return_value.async_setup = AsyncMock(return_value=True) mock_bridge.return_value.api.config = Mock( mac="mock-mac", bridgeid="mock-bridgeid", @@ -159,13 +158,13 @@ async def test_unload_entry(hass): "homeassistant.helpers.device_registry.async_get_registry", return_value=mock_coro(Mock()), ): - mock_bridge.return_value.async_setup.return_value = mock_coro(True) + mock_bridge.return_value.async_setup = AsyncMock(return_value=True) mock_bridge.return_value.api.config = Mock(bridgeid="aabbccddeeff") assert await async_setup_component(hass, hue.DOMAIN, {}) is True assert len(mock_bridge.return_value.mock_calls) == 1 - mock_bridge.return_value.async_reset.return_value = mock_coro(True) + mock_bridge.return_value.async_reset = AsyncMock(return_value=True) assert await hue.async_unload_entry(hass, entry) assert len(mock_bridge.return_value.async_reset.mock_calls) == 1 assert hass.data[hue.DOMAIN] == {} @@ -180,7 +179,7 @@ async def test_setting_unique_id(hass): "homeassistant.helpers.device_registry.async_get_registry", return_value=mock_coro(Mock()), ): - mock_bridge.return_value.async_setup.return_value = mock_coro(True) + mock_bridge.return_value.async_setup = AsyncMock(return_value=True) mock_bridge.return_value.api.config = Mock(bridgeid="mock-id") assert await async_setup_component(hass, hue.DOMAIN, {}) is True @@ -201,7 +200,7 @@ async def test_security_vuln_check(hass): "HueBridge", Mock( return_value=Mock( - async_setup=CoroutineMock(return_value=True), api=Mock(config=config) + async_setup=AsyncMock(return_value=True), api=Mock(config=config) ) ), ): diff --git a/tests/components/hunterdouglas_powerview/test_config_flow.py b/tests/components/hunterdouglas_powerview/test_config_flow.py index 67b2c2dc954..e5b0d472304 100644 --- a/tests/components/hunterdouglas_powerview/test_config_flow.py +++ b/tests/components/hunterdouglas_powerview/test_config_flow.py @@ -2,11 +2,10 @@ import asyncio import json -from asynctest import CoroutineMock, MagicMock, patch - from homeassistant import config_entries, setup from homeassistant.components.hunterdouglas_powerview.const import DOMAIN +from tests.async_mock import AsyncMock, MagicMock, patch from tests.common import load_fixture @@ -15,13 +14,11 @@ def _get_mock_powerview_userdata(userdata=None, get_resources=None): if not userdata: userdata = json.loads(load_fixture("hunterdouglas_powerview/userdata.json")) if get_resources: - type(mock_powerview_userdata).get_resources = CoroutineMock( + type(mock_powerview_userdata).get_resources = AsyncMock( side_effect=get_resources ) else: - type(mock_powerview_userdata).get_resources = CoroutineMock( - return_value=userdata - ) + type(mock_powerview_userdata).get_resources = AsyncMock(return_value=userdata) return mock_powerview_userdata diff --git a/tests/components/image_processing/test_init.py b/tests/components/image_processing/test_init.py index 399523dd779..a2a2ec2d7a6 100644 --- a/tests/components/image_processing/test_init.py +++ b/tests/components/image_processing/test_init.py @@ -1,8 +1,6 @@ """The tests for the image_processing component.""" from unittest.mock import PropertyMock -from asynctest import patch - import homeassistant.components.http as http import homeassistant.components.image_processing as ip from homeassistant.const import ATTR_ENTITY_PICTURE @@ -10,6 +8,7 @@ from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import setup_component +from tests.async_mock import patch from tests.common import ( assert_setup_component, get_test_home_assistant, diff --git a/tests/components/ipma/test_config_flow.py b/tests/components/ipma/test_config_flow.py index fd44f8b2a58..b3b8968f451 100644 --- a/tests/components/ipma/test_config_flow.py +++ b/tests/components/ipma/test_config_flow.py @@ -1,10 +1,9 @@ """Tests for IPMA config flow.""" -from unittest.mock import Mock, patch from homeassistant.components.ipma import config_flow from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE -from tests.common import mock_coro +from tests.async_mock import Mock, patch async def test_show_config_form(): @@ -58,8 +57,8 @@ async def test_flow_show_form(): flow = config_flow.IpmaFlowHandler() flow.hass = hass - with patch.object( - flow, "_show_config_form", return_value=mock_coro() + with patch( + "homeassistant.components.ipma.config_flow.IpmaFlowHandler._show_config_form" ) as config_form: await flow.async_step_user() assert len(config_form.mock_calls) == 1 @@ -77,10 +76,10 @@ async def test_flow_entry_created_from_user_input(): test_data = {"name": "home", CONF_LONGITUDE: "0", CONF_LATITUDE: "0"} # Test that entry created when user_input name not exists - with patch.object( - flow, "_show_config_form", return_value=mock_coro() + with patch( + "homeassistant.components.ipma.config_flow.IpmaFlowHandler._show_config_form" ) as config_form, patch.object( - flow.hass.config_entries, "async_entries", return_value=mock_coro() + flow.hass.config_entries, "async_entries", return_value=[], ) as config_entries: result = await flow.async_step_user(user_input=test_data) @@ -104,8 +103,8 @@ async def test_flow_entry_config_entry_already_exists(): test_data = {"name": "home", CONF_LONGITUDE: "0", CONF_LATITUDE: "0"} # Test that entry created when user_input name not exists - with patch.object( - flow, "_show_config_form", return_value=mock_coro() + with patch( + "homeassistant.components.ipma.config_flow.IpmaFlowHandler._show_config_form" ) as config_form, patch.object( flow.hass.config_entries, "async_entries", return_value={"home": test_data} ) as config_entries: diff --git a/tests/components/ipma/test_weather.py b/tests/components/ipma/test_weather.py index b3d398377f0..e7542070d2c 100644 --- a/tests/components/ipma/test_weather.py +++ b/tests/components/ipma/test_weather.py @@ -1,8 +1,6 @@ """The tests for the IPMA weather component.""" from collections import namedtuple -from asynctest import patch - from homeassistant.components import weather from homeassistant.components.weather import ( ATTR_FORECAST, @@ -23,6 +21,7 @@ from homeassistant.components.weather import ( from homeassistant.setup import async_setup_component from homeassistant.util.dt import now +from tests.async_mock import patch from tests.common import MockConfigEntry TEST_CONFIG = {"name": "HomeTown", "latitude": "40.00", "longitude": "-8.00"} diff --git a/tests/components/ipp/test_sensor.py b/tests/components/ipp/test_sensor.py index e6830f559c6..51caadfceb3 100644 --- a/tests/components/ipp/test_sensor.py +++ b/tests/components/ipp/test_sensor.py @@ -1,14 +1,13 @@ """Tests for the IPP sensor platform.""" from datetime import datetime -from asynctest import patch - from homeassistant.components.ipp.const import DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.const import ATTR_ICON, ATTR_UNIT_OF_MEASUREMENT, UNIT_PERCENTAGE from homeassistant.core import HomeAssistant from homeassistant.util import dt as dt_util +from tests.async_mock import patch from tests.components.ipp import init_integration from tests.test_util.aiohttp import AiohttpClientMocker diff --git a/tests/components/izone/test_config_flow.py b/tests/components/izone/test_config_flow.py index 942d95cc503..72b80e75bcf 100644 --- a/tests/components/izone/test_config_flow.py +++ b/tests/components/izone/test_config_flow.py @@ -1,11 +1,12 @@ """Tests for iZone.""" -from asynctest import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE +from tests.async_mock import Mock, patch + @pytest.fixture def mock_disco(): diff --git a/tests/components/konnected/test_config_flow.py b/tests/components/konnected/test_config_flow.py index 0bf6e7846ae..a0d870b37ff 100644 --- a/tests/components/konnected/test_config_flow.py +++ b/tests/components/konnected/test_config_flow.py @@ -1,10 +1,10 @@ """Tests for Konnected Alarm Panel config flow.""" -from asynctest import patch import pytest from homeassistant.components import konnected from homeassistant.components.konnected import config_flow +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/konnected/test_init.py b/tests/components/konnected/test_init.py index f87c66fe412..1bdd1278b93 100644 --- a/tests/components/konnected/test_init.py +++ b/tests/components/konnected/test_init.py @@ -1,5 +1,4 @@ """Test Konnected setup process.""" -from asynctest import patch import pytest from homeassistant.components import konnected @@ -7,6 +6,7 @@ from homeassistant.components.konnected import config_flow from homeassistant.const import HTTP_NOT_FOUND from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/konnected/test_panel.py b/tests/components/konnected/test_panel.py index f1ae8a4357c..f167c558d01 100644 --- a/tests/components/konnected/test_panel.py +++ b/tests/components/konnected/test_panel.py @@ -1,10 +1,10 @@ """Test Konnected setup process.""" -from asynctest import patch import pytest from homeassistant.components.konnected import config_flow, panel from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/logbook/test_init.py b/tests/components/logbook/test_init.py index 814e304f9f5..abe6f6ec515 100644 --- a/tests/components/logbook/test_init.py +++ b/tests/components/logbook/test_init.py @@ -5,7 +5,6 @@ from functools import partial import logging import unittest -from asynctest import patch import pytest import voluptuous as vol @@ -28,6 +27,7 @@ import homeassistant.core as ha from homeassistant.setup import async_setup_component, setup_component import homeassistant.util.dt as dt_util +from tests.async_mock import patch from tests.common import get_test_home_assistant, init_recorder_component from tests.components.recorder.common import trigger_db_commit diff --git a/tests/components/logi_circle/test_config_flow.py b/tests/components/logi_circle/test_config_flow.py index 7ba3816b5e2..43dea15f7e6 100644 --- a/tests/components/logi_circle/test_config_flow.py +++ b/tests/components/logi_circle/test_config_flow.py @@ -13,6 +13,7 @@ from homeassistant.components.logi_circle.config_flow import ( ) from homeassistant.setup import async_setup_component +from tests.async_mock import AsyncMock from tests.common import mock_coro @@ -51,8 +52,8 @@ def mock_logi_circle(): "homeassistant.components.logi_circle.config_flow.LogiCircle" ) as logi_circle: LogiCircle = logi_circle() - LogiCircle.authorize = Mock(return_value=mock_coro(return_value=True)) - LogiCircle.close = Mock(return_value=mock_coro(return_value=True)) + LogiCircle.authorize = AsyncMock(return_value=True) + LogiCircle.close = AsyncMock(return_value=True) LogiCircle.account = mock_coro(return_value={"accountId": "testId"}) LogiCircle.authorize_url = "http://authorize.url" yield LogiCircle diff --git a/tests/components/lovelace/test_resources.py b/tests/components/lovelace/test_resources.py index a44af14d3a0..d32dc9388f1 100644 --- a/tests/components/lovelace/test_resources.py +++ b/tests/components/lovelace/test_resources.py @@ -2,11 +2,11 @@ import copy import uuid -from asynctest import patch - from homeassistant.components.lovelace import dashboard, resources from homeassistant.setup import async_setup_component +from tests.async_mock import patch + RESOURCE_EXAMPLES = [ {"type": "js", "url": "/local/bla.js"}, {"type": "css", "url": "/local/bla.css"}, diff --git a/tests/components/luftdaten/test_config_flow.py b/tests/components/luftdaten/test_config_flow.py index e0e54a6b790..70b306d34c0 100644 --- a/tests/components/luftdaten/test_config_flow.py +++ b/tests/components/luftdaten/test_config_flow.py @@ -1,13 +1,12 @@ """Define tests for the Luftdaten config flow.""" from datetime import timedelta -from asynctest import patch - from homeassistant import data_entry_flow from homeassistant.components.luftdaten import DOMAIN, config_flow from homeassistant.components.luftdaten.const import CONF_SENSOR_ID from homeassistant.const import CONF_SCAN_INTERVAL, CONF_SHOW_ON_MAP +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/media_player/test_init.py b/tests/components/media_player/test_init.py index 330581d2d14..50924af5d76 100644 --- a/tests/components/media_player/test_init.py +++ b/tests/components/media_player/test_init.py @@ -1,13 +1,11 @@ """Test the base functions of the media player.""" import base64 -from asynctest import patch - from homeassistant.components import media_player from homeassistant.components.websocket_api.const import TYPE_RESULT from homeassistant.setup import async_setup_component -from tests.common import mock_coro +from tests.async_mock import patch async def test_get_image(hass, hass_ws_client, caplog): @@ -21,7 +19,7 @@ async def test_get_image(hass, hass_ws_client, caplog): with patch( "homeassistant.components.media_player.MediaPlayerEntity." "async_get_media_image", - return_value=mock_coro((b"image", "image/jpeg")), + return_value=(b"image", "image/jpeg"), ): await client.send_json( { diff --git a/tests/components/melcloud/test_config_flow.py b/tests/components/melcloud/test_config_flow.py index c936807484a..e6b36306986 100644 --- a/tests/components/melcloud/test_config_flow.py +++ b/tests/components/melcloud/test_config_flow.py @@ -2,7 +2,6 @@ import asyncio from aiohttp import ClientError, ClientResponseError -from asynctest import patch import pymelcloud import pytest @@ -10,6 +9,7 @@ from homeassistant import config_entries from homeassistant.components.melcloud.const import DOMAIN from homeassistant.const import HTTP_FORBIDDEN, HTTP_INTERNAL_SERVER_ERROR +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/met/conftest.py b/tests/components/met/conftest.py index e475889863d..164a8498465 100644 --- a/tests/components/met/conftest.py +++ b/tests/components/met/conftest.py @@ -1,9 +1,7 @@ """Fixtures for Met weather testing.""" -from unittest.mock import patch - import pytest -from tests.common import mock_coro +from tests.async_mock import AsyncMock, patch @pytest.fixture @@ -11,7 +9,7 @@ def mock_weather(): """Mock weather data.""" with patch("metno.MetWeatherData") as mock_data: mock_data = mock_data.return_value - mock_data.fetching_data.side_effect = lambda: mock_coro(True) + mock_data.fetching_data = AsyncMock(return_value=True) mock_data.get_current_weather.return_value = { "condition": "cloudy", "temperature": 15, diff --git a/tests/components/met/test_config_flow.py b/tests/components/met/test_config_flow.py index 980994f3fb2..a4c48f38245 100644 --- a/tests/components/met/test_config_flow.py +++ b/tests/components/met/test_config_flow.py @@ -1,10 +1,10 @@ """Tests for Met.no config flow.""" -from asynctest import patch import pytest from homeassistant.components.met.const import DOMAIN, HOME_LOCATION_NAME from homeassistant.const import CONF_ELEVATION, CONF_LATITUDE, CONF_LONGITUDE +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/microsoft_face/test_init.py b/tests/components/microsoft_face/test_init.py index 478a3fb29bd..abd35eca3e1 100644 --- a/tests/components/microsoft_face/test_init.py +++ b/tests/components/microsoft_face/test_init.py @@ -1,8 +1,6 @@ """The tests for the microsoft face platform.""" import asyncio -from asynctest import patch - from homeassistant.components import camera, microsoft_face as mf from homeassistant.components.microsoft_face import ( ATTR_CAMERA_ENTITY, @@ -19,6 +17,7 @@ from homeassistant.components.microsoft_face import ( from homeassistant.const import ATTR_NAME from homeassistant.setup import setup_component +from tests.async_mock import patch from tests.common import assert_setup_component, get_test_home_assistant, load_fixture diff --git a/tests/components/mikrotik/test_hub.py b/tests/components/mikrotik/test_hub.py index 9a2f75f7015..ecfb9add717 100644 --- a/tests/components/mikrotik/test_hub.py +++ b/tests/components/mikrotik/test_hub.py @@ -1,5 +1,4 @@ """Test Mikrotik hub.""" -from asynctest import patch import librouteros from homeassistant import config_entries @@ -7,6 +6,7 @@ from homeassistant.components import mikrotik from . import ARP_DATA, DHCP_DATA, MOCK_DATA, MOCK_OPTIONS, WIRELESS_DATA +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/mikrotik/test_init.py b/tests/components/mikrotik/test_init.py index 1a634916781..b3dca7269eb 100644 --- a/tests/components/mikrotik/test_init.py +++ b/tests/components/mikrotik/test_init.py @@ -1,11 +1,10 @@ """Test Mikrotik setup process.""" -from asynctest import CoroutineMock, Mock, patch - from homeassistant.components import mikrotik from homeassistant.setup import async_setup_component from . import MOCK_DATA +from tests.async_mock import AsyncMock, Mock, patch from tests.common import MockConfigEntry @@ -25,7 +24,7 @@ async def test_successful_config_entry(hass): "homeassistant.helpers.device_registry.async_get_registry", return_value=mock_registry, ): - mock_hub.return_value.async_setup = CoroutineMock(return_value=True) + mock_hub.return_value.async_setup = AsyncMock(return_value=True) mock_hub.return_value.serial_num = "12345678" mock_hub.return_value.model = "RB750" mock_hub.return_value.hostname = "mikrotik" @@ -55,7 +54,7 @@ async def test_hub_fail_setup(hass): entry.add_to_hass(hass) with patch.object(mikrotik, "MikrotikHub") as mock_hub: - mock_hub.return_value.async_setup = CoroutineMock(return_value=False) + mock_hub.return_value.async_setup = AsyncMock(return_value=False) assert await mikrotik.async_setup_entry(hass, entry) is False assert mikrotik.DOMAIN not in hass.data @@ -69,7 +68,7 @@ async def test_unload_entry(hass): with patch.object(mikrotik, "MikrotikHub") as mock_hub, patch( "homeassistant.helpers.device_registry.async_get_registry", return_value=Mock(), ): - mock_hub.return_value.async_setup = CoroutineMock(return_value=True) + mock_hub.return_value.async_setup = AsyncMock(return_value=True) mock_hub.return_value.serial_num = "12345678" mock_hub.return_value.model = "RB750" mock_hub.return_value.hostname = "mikrotik" diff --git a/tests/components/minecraft_server/test_config_flow.py b/tests/components/minecraft_server/test_config_flow.py index 7db6dc33b5a..17ec9080e86 100644 --- a/tests/components/minecraft_server/test_config_flow.py +++ b/tests/components/minecraft_server/test_config_flow.py @@ -3,7 +3,6 @@ import asyncio import aiodns -from asynctest import patch from mcstatus.pinger import PingResponse from homeassistant.components.minecraft_server.const import ( @@ -20,6 +19,7 @@ from homeassistant.data_entry_flow import ( ) from homeassistant.helpers.typing import HomeAssistantType +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/minio/test_minio.py b/tests/components/minio/test_minio.py index 4397f446a19..a1f3e107152 100644 --- a/tests/components/minio/test_minio.py +++ b/tests/components/minio/test_minio.py @@ -3,7 +3,6 @@ import asyncio import json from unittest.mock import MagicMock -from asynctest import call, patch import pytest from homeassistant.components.minio import ( @@ -20,6 +19,7 @@ from homeassistant.components.minio import ( from homeassistant.core import callback from homeassistant.setup import async_setup_component +from tests.async_mock import call, patch from tests.components.minio.common import TEST_EVENT diff --git a/tests/components/monoprice/test_config_flow.py b/tests/components/monoprice/test_config_flow.py index ecafa17e174..8c6e2a3916c 100644 --- a/tests/components/monoprice/test_config_flow.py +++ b/tests/components/monoprice/test_config_flow.py @@ -1,5 +1,4 @@ """Test the Monoprice 6-Zone Amplifier config flow.""" -from asynctest import patch from serial import SerialException from homeassistant import config_entries, data_entry_flow, setup @@ -12,6 +11,7 @@ from homeassistant.components.monoprice.const import ( ) from homeassistant.const import CONF_PORT +from tests.async_mock import patch from tests.common import MockConfigEntry CONFIG = { diff --git a/tests/components/monoprice/test_media_player.py b/tests/components/monoprice/test_media_player.py index 0006364b94e..f70a19f51fc 100644 --- a/tests/components/monoprice/test_media_player.py +++ b/tests/components/monoprice/test_media_player.py @@ -1,7 +1,6 @@ """The tests for Monoprice Media player platform.""" from collections import defaultdict -from asynctest import patch from serial import SerialException from homeassistant.components.media_player.const import ( @@ -34,6 +33,7 @@ from homeassistant.const import ( ) from homeassistant.helpers.entity_component import async_update_entity +from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_CONFIG = {CONF_PORT: "fake port", CONF_SOURCES: {"1": "one", "3": "three"}} diff --git a/tests/components/mqtt/test_device_tracker.py b/tests/components/mqtt/test_device_tracker.py index ababe8395f3..32f826422a8 100644 --- a/tests/components/mqtt/test_device_tracker.py +++ b/tests/components/mqtt/test_device_tracker.py @@ -1,11 +1,11 @@ """The tests for the MQTT device tracker platform.""" -from asynctest import patch import pytest from homeassistant.components.device_tracker.const import DOMAIN, SOURCE_TYPE_BLUETOOTH from homeassistant.const import CONF_PLATFORM, STATE_HOME, STATE_NOT_HOME from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import async_fire_mqtt_message diff --git a/tests/components/mqtt/test_discovery.py b/tests/components/mqtt/test_discovery.py index 1b2f76d6c5e..9d8ede4f516 100644 --- a/tests/components/mqtt/test_discovery.py +++ b/tests/components/mqtt/test_discovery.py @@ -13,10 +13,10 @@ from homeassistant.components.mqtt.abbreviations import ( from homeassistant.components.mqtt.discovery import ALREADY_DISCOVERED, async_start from homeassistant.const import STATE_OFF, STATE_ON +from tests.async_mock import AsyncMock from tests.common import ( MockConfigEntry, async_fire_mqtt_message, - mock_coro, mock_device_registry, mock_registry, ) @@ -57,7 +57,7 @@ async def test_invalid_topic(hass, mqtt_mock): domain=mqtt.DOMAIN, data={mqtt.CONF_BROKER: "test-broker"} ) - mock_dispatcher_send.return_value = mock_coro() + mock_dispatcher_send = AsyncMock(return_value=None) await async_start(hass, "homeassistant", {}, entry) async_fire_mqtt_message( @@ -76,7 +76,7 @@ async def test_invalid_json(hass, mqtt_mock, caplog): domain=mqtt.DOMAIN, data={mqtt.CONF_BROKER: "test-broker"} ) - mock_dispatcher_send.return_value = mock_coro() + mock_dispatcher_send = AsyncMock(return_value=None) await async_start(hass, "homeassistant", {}, entry) async_fire_mqtt_message( @@ -96,7 +96,7 @@ async def test_only_valid_components(hass, mqtt_mock, caplog): invalid_component = "timer" - mock_dispatcher_send.return_value = mock_coro() + mock_dispatcher_send = AsyncMock(return_value=None) await async_start(hass, "homeassistant", {}, entry) async_fire_mqtt_message( diff --git a/tests/components/mqtt/test_init.py b/tests/components/mqtt/test_init.py index 207529c2ad3..a139a942530 100644 --- a/tests/components/mqtt/test_init.py +++ b/tests/components/mqtt/test_init.py @@ -4,7 +4,6 @@ import json import ssl import unittest -from asynctest import CoroutineMock, MagicMock, call, mock_open, patch import pytest import voluptuous as vol @@ -24,6 +23,7 @@ from homeassistant.helpers import device_registry from homeassistant.setup import async_setup_component from homeassistant.util.dt import utcnow +from tests.async_mock import AsyncMock, MagicMock, call, mock_open, patch from tests.common import ( MockConfigEntry, async_fire_mqtt_message, @@ -60,8 +60,8 @@ def entity_reg(hass): def mock_mqtt(): """Make sure connection is established.""" with patch("homeassistant.components.mqtt.MQTT") as mock_mqtt: - mock_mqtt.return_value.async_connect = CoroutineMock(return_value=True) - mock_mqtt.return_value.async_disconnect = CoroutineMock(return_value=True) + mock_mqtt.return_value.async_connect = AsyncMock(return_value=True) + mock_mqtt.return_value.async_disconnect = AsyncMock(return_value=True) yield mock_mqtt diff --git a/tests/components/mqtt/test_light.py b/tests/components/mqtt/test_light.py index 205e7400eb3..ccf5935cecc 100644 --- a/tests/components/mqtt/test_light.py +++ b/tests/components/mqtt/test_light.py @@ -153,8 +153,6 @@ light: payload_off: "off" """ -from asynctest import call, patch - from homeassistant.components import light, mqtt from homeassistant.components.mqtt.discovery import async_start from homeassistant.const import ATTR_ASSUMED_STATE, STATE_OFF, STATE_ON @@ -183,6 +181,7 @@ from .test_common import ( help_test_update_with_json_attrs_not_dict, ) +from tests.async_mock import call, patch from tests.common import ( MockConfigEntry, assert_setup_component, diff --git a/tests/components/mqtt/test_light_json.py b/tests/components/mqtt/test_light_json.py index 1e3ac34af89..d4712e9f835 100644 --- a/tests/components/mqtt/test_light_json.py +++ b/tests/components/mqtt/test_light_json.py @@ -89,8 +89,6 @@ light: """ import json -from asynctest import call, patch - from homeassistant.components import light from homeassistant.const import ( ATTR_ASSUMED_STATE, @@ -123,6 +121,7 @@ from .test_common import ( help_test_update_with_json_attrs_not_dict, ) +from tests.async_mock import call, patch from tests.common import async_fire_mqtt_message from tests.components.light import common diff --git a/tests/components/mqtt/test_light_template.py b/tests/components/mqtt/test_light_template.py index 20b5ecefd89..29adc555bc5 100644 --- a/tests/components/mqtt/test_light_template.py +++ b/tests/components/mqtt/test_light_template.py @@ -26,8 +26,6 @@ If your light doesn't support white value feature, omit `white_value_template`. If your light doesn't support RGB feature, omit `(red|green|blue)_template`. """ -from asynctest import patch - from homeassistant.components import light from homeassistant.const import ( ATTR_ASSUMED_STATE, @@ -60,6 +58,7 @@ from .test_common import ( help_test_update_with_json_attrs_not_dict, ) +from tests.async_mock import patch from tests.common import assert_setup_component, async_fire_mqtt_message from tests.components.light import common diff --git a/tests/components/mqtt/test_server.py b/tests/components/mqtt/test_server.py index 3186b3a2734..b3320d6aaca 100644 --- a/tests/components/mqtt/test_server.py +++ b/tests/components/mqtt/test_server.py @@ -1,13 +1,13 @@ """The tests for the MQTT component embedded server.""" from unittest.mock import MagicMock, Mock -from asynctest import CoroutineMock, patch import pytest import homeassistant.components.mqtt as mqtt from homeassistant.const import CONF_PASSWORD from homeassistant.setup import setup_component +from tests.async_mock import AsyncMock, patch from tests.common import get_test_home_assistant, mock_coro @@ -29,15 +29,15 @@ class TestMQTT: @patch("passlib.apps.custom_app_context", Mock(return_value="")) @patch("tempfile.NamedTemporaryFile", Mock(return_value=MagicMock())) - @patch("hbmqtt.broker.Broker", Mock(return_value=MagicMock(start=CoroutineMock()))) - @patch("hbmqtt.broker.Broker.start", Mock(return_value=mock_coro())) + @patch("hbmqtt.broker.Broker", Mock(return_value=MagicMock(start=AsyncMock()))) + @patch("hbmqtt.broker.Broker.start", AsyncMock(return_value=None)) @patch("homeassistant.components.mqtt.MQTT") def test_creating_config_with_pass_and_no_http_pass(self, mock_mqtt): """Test if the MQTT server gets started with password. Since 0.77, MQTT server has to set up its own password. """ - mock_mqtt().async_connect.return_value = mock_coro(True) + mock_mqtt().async_connect = AsyncMock(return_value=True) self.hass.bus.listen_once = MagicMock() password = "mqtt_secret" @@ -51,15 +51,15 @@ class TestMQTT: @patch("passlib.apps.custom_app_context", Mock(return_value="")) @patch("tempfile.NamedTemporaryFile", Mock(return_value=MagicMock())) - @patch("hbmqtt.broker.Broker", Mock(return_value=MagicMock(start=CoroutineMock()))) - @patch("hbmqtt.broker.Broker.start", Mock(return_value=mock_coro())) + @patch("hbmqtt.broker.Broker", Mock(return_value=MagicMock(start=AsyncMock()))) + @patch("hbmqtt.broker.Broker.start", AsyncMock(return_value=None)) @patch("homeassistant.components.mqtt.MQTT") def test_creating_config_with_pass_and_http_pass(self, mock_mqtt): """Test if the MQTT server gets started with password. Since 0.77, MQTT server has to set up its own password. """ - mock_mqtt().async_connect.return_value = mock_coro(True) + mock_mqtt().async_connect = AsyncMock(return_value=True) self.hass.bus.listen_once = MagicMock() password = "mqtt_secret" diff --git a/tests/components/mqtt/test_switch.py b/tests/components/mqtt/test_switch.py index 1aaeb154dc2..c34d32a3c9d 100644 --- a/tests/components/mqtt/test_switch.py +++ b/tests/components/mqtt/test_switch.py @@ -1,5 +1,4 @@ """The tests for the MQTT switch platform.""" -from asynctest import patch import pytest from homeassistant.components import switch @@ -29,7 +28,8 @@ from .test_common import ( help_test_update_with_json_attrs_not_dict, ) -from tests.common import async_fire_mqtt_message, async_mock_mqtt_component, mock_coro +from tests.async_mock import patch +from tests.common import async_fire_mqtt_message, async_mock_mqtt_component from tests.components.switch import common DEFAULT_CONFIG = { @@ -81,7 +81,7 @@ async def test_sending_mqtt_commands_and_optimistic(hass, mock_publish): with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", - return_value=mock_coro(fake_state), + return_value=fake_state, ): assert await async_setup_component( hass, diff --git a/tests/components/mqtt_json/test_device_tracker.py b/tests/components/mqtt_json/test_device_tracker.py index 9efff135fe2..864b3c232ed 100644 --- a/tests/components/mqtt_json/test_device_tracker.py +++ b/tests/components/mqtt_json/test_device_tracker.py @@ -3,7 +3,6 @@ import json import logging import os -from asynctest import patch import pytest from homeassistant.components.device_tracker.legacy import ( @@ -13,6 +12,7 @@ from homeassistant.components.device_tracker.legacy import ( from homeassistant.const import CONF_PLATFORM from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import async_fire_mqtt_message, async_mock_mqtt_component _LOGGER = logging.getLogger(__name__) diff --git a/tests/components/myq/test_config_flow.py b/tests/components/myq/test_config_flow.py index 7620a9ad176..ed022df0dd7 100644 --- a/tests/components/myq/test_config_flow.py +++ b/tests/components/myq/test_config_flow.py @@ -1,11 +1,11 @@ """Test the MyQ config flow.""" -from asynctest import patch from pymyq.errors import InvalidCredentialsError, MyQError from homeassistant import config_entries, setup from homeassistant.components.myq.const import DOMAIN from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/myq/util.py b/tests/components/myq/util.py index 7cff7bd2af9..61e49a98b83 100644 --- a/tests/components/myq/util.py +++ b/tests/components/myq/util.py @@ -2,12 +2,11 @@ import json -from asynctest import patch - from homeassistant.components.myq.const import DOMAIN from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant +from tests.async_mock import patch from tests.common import MockConfigEntry, load_fixture diff --git a/tests/components/mythicbeastsdns/test_init.py b/tests/components/mythicbeastsdns/test_init.py index ee037a029ed..e8efac2c01d 100644 --- a/tests/components/mythicbeastsdns/test_init.py +++ b/tests/components/mythicbeastsdns/test_init.py @@ -1,11 +1,11 @@ """Test the Mythic Beasts DNS component.""" import logging -import asynctest - from homeassistant.components import mythicbeastsdns from homeassistant.setup import async_setup_component +from tests.async_mock import patch + _LOGGER = logging.getLogger(__name__) @@ -20,7 +20,7 @@ async def mbddns_update_mock(domain, password, host, ttl=60, session=None): return True -@asynctest.mock.patch("mbddns.update", new=mbddns_update_mock) +@patch("mbddns.update", new=mbddns_update_mock) async def test_update(hass): """Run with correct values and check true is returned.""" result = await async_setup_component( @@ -37,7 +37,7 @@ async def test_update(hass): assert result -@asynctest.mock.patch("mbddns.update", new=mbddns_update_mock) +@patch("mbddns.update", new=mbddns_update_mock) async def test_update_fails_if_wrong_token(hass): """Run with incorrect token and check false is returned.""" result = await async_setup_component( @@ -54,7 +54,7 @@ async def test_update_fails_if_wrong_token(hass): assert not result -@asynctest.mock.patch("mbddns.update", new=mbddns_update_mock) +@patch("mbddns.update", new=mbddns_update_mock) async def test_update_fails_if_invalid_host(hass): """Run with invalid characters in host and check false is returned.""" result = await async_setup_component( diff --git a/tests/components/ness_alarm/test_init.py b/tests/components/ness_alarm/test_init.py index 9da361852e9..f959b5345dd 100644 --- a/tests/components/ness_alarm/test_init.py +++ b/tests/components/ness_alarm/test_init.py @@ -1,7 +1,6 @@ """Tests for the ness_alarm component.""" from enum import Enum -from asynctest import MagicMock, patch import pytest from homeassistant.components import alarm_control_panel @@ -32,6 +31,8 @@ from homeassistant.const import ( ) from homeassistant.setup import async_setup_component +from tests.async_mock import MagicMock, patch + VALID_CONFIG = { DOMAIN: { CONF_HOST: "alarm.local", diff --git a/tests/components/nest/test_config_flow.py b/tests/components/nest/test_config_flow.py index ec6218fb0d7..6c0c0197a74 100644 --- a/tests/components/nest/test_config_flow.py +++ b/tests/components/nest/test_config_flow.py @@ -6,6 +6,7 @@ from homeassistant import data_entry_flow from homeassistant.components.nest import DOMAIN, config_flow from homeassistant.setup import async_setup_component +from tests.async_mock import AsyncMock from tests.common import mock_coro @@ -33,8 +34,8 @@ async def test_abort_if_already_setup(hass): async def test_full_flow_implementation(hass): """Test registering an implementation and finishing flow works.""" - gen_authorize_url = Mock(return_value=mock_coro("https://example.com")) - convert_code = Mock(return_value=mock_coro({"access_token": "yoo"})) + gen_authorize_url = AsyncMock(return_value="https://example.com") + convert_code = AsyncMock(return_value={"access_token": "yoo"}) config_flow.register_flow_implementation( hass, "test", "Test", gen_authorize_url, convert_code ) @@ -62,7 +63,7 @@ async def test_full_flow_implementation(hass): async def test_not_pick_implementation_if_only_one(hass): """Test we allow picking implementation if we have two.""" - gen_authorize_url = Mock(return_value=mock_coro("https://example.com")) + gen_authorize_url = AsyncMock(return_value="https://example.com") config_flow.register_flow_implementation( hass, "test", "Test", gen_authorize_url, None ) @@ -104,7 +105,7 @@ async def test_abort_if_exception_generating_auth_url(hass): async def test_verify_code_timeout(hass): """Test verify code timing out.""" - gen_authorize_url = Mock(return_value=mock_coro("https://example.com")) + gen_authorize_url = AsyncMock(return_value="https://example.com") convert_code = Mock(side_effect=asyncio.TimeoutError) config_flow.register_flow_implementation( hass, "test", "Test", gen_authorize_url, convert_code @@ -124,7 +125,7 @@ async def test_verify_code_timeout(hass): async def test_verify_code_invalid(hass): """Test verify code invalid.""" - gen_authorize_url = Mock(return_value=mock_coro("https://example.com")) + gen_authorize_url = AsyncMock(return_value="https://example.com") convert_code = Mock(side_effect=config_flow.CodeInvalid) config_flow.register_flow_implementation( hass, "test", "Test", gen_authorize_url, convert_code @@ -144,7 +145,7 @@ async def test_verify_code_invalid(hass): async def test_verify_code_unknown_error(hass): """Test verify code unknown error.""" - gen_authorize_url = Mock(return_value=mock_coro("https://example.com")) + gen_authorize_url = AsyncMock(return_value="https://example.com") convert_code = Mock(side_effect=config_flow.NestAuthError) config_flow.register_flow_implementation( hass, "test", "Test", gen_authorize_url, convert_code @@ -164,7 +165,7 @@ async def test_verify_code_unknown_error(hass): async def test_verify_code_exception(hass): """Test verify code blows up.""" - gen_authorize_url = Mock(return_value=mock_coro("https://example.com")) + gen_authorize_url = AsyncMock(return_value="https://example.com") convert_code = Mock(side_effect=ValueError) config_flow.register_flow_implementation( hass, "test", "Test", gen_authorize_url, convert_code diff --git a/tests/components/netatmo/test_config_flow.py b/tests/components/netatmo/test_config_flow.py index 29a1d4f53d5..047dd4c0c40 100644 --- a/tests/components/netatmo/test_config_flow.py +++ b/tests/components/netatmo/test_config_flow.py @@ -1,6 +1,4 @@ """Test the Netatmo config flow.""" -from asynctest import patch - from homeassistant import config_entries, data_entry_flow, setup from homeassistant.components.netatmo import config_flow from homeassistant.components.netatmo.const import ( @@ -10,6 +8,7 @@ from homeassistant.components.netatmo.const import ( ) from homeassistant.helpers import config_entry_oauth2_flow +from tests.async_mock import patch from tests.common import MockConfigEntry CLIENT_ID = "1234" diff --git a/tests/components/nexia/test_config_flow.py b/tests/components/nexia/test_config_flow.py index ff6f8590287..0dce512cff4 100644 --- a/tests/components/nexia/test_config_flow.py +++ b/tests/components/nexia/test_config_flow.py @@ -1,12 +1,12 @@ """Test the nexia config flow.""" -from asynctest import patch -from asynctest.mock import MagicMock from requests.exceptions import ConnectTimeout from homeassistant import config_entries, setup from homeassistant.components.nexia.const import DOMAIN from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from tests.async_mock import MagicMock, patch + async def test_form(hass): """Test we get the form.""" diff --git a/tests/components/nexia/util.py b/tests/components/nexia/util.py index cc2b11afcbe..2da56d50f37 100644 --- a/tests/components/nexia/util.py +++ b/tests/components/nexia/util.py @@ -1,7 +1,6 @@ """Tests for the nexia integration.""" import uuid -from asynctest import patch from nexia.home import NexiaHome import requests_mock @@ -9,6 +8,7 @@ from homeassistant.components.nexia.const import DOMAIN from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant +from tests.async_mock import patch from tests.common import MockConfigEntry, load_fixture diff --git a/tests/components/notion/test_config_flow.py b/tests/components/notion/test_config_flow.py index 7d3ddb1cf4b..6aaf7df9505 100644 --- a/tests/components/notion/test_config_flow.py +++ b/tests/components/notion/test_config_flow.py @@ -1,6 +1,5 @@ """Define tests for the Notion config flow.""" import aionotion -from asynctest import patch import pytest from homeassistant import data_entry_flow @@ -8,20 +7,21 @@ from homeassistant.components.notion import DOMAIN, config_flow from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_USERNAME -from tests.common import MockConfigEntry, mock_coro +from tests.async_mock import AsyncMock, patch +from tests.common import MockConfigEntry @pytest.fixture -def mock_client_coro(): +def mock_client(): """Define a fixture for a client creation coroutine.""" - return mock_coro() + return AsyncMock(return_value=None) @pytest.fixture -def mock_aionotion(mock_client_coro): +def mock_aionotion(mock_client): """Mock the aionotion library.""" with patch("homeassistant.components.notion.config_flow.async_get_client") as mock_: - mock_.return_value = mock_client_coro + mock_.side_effect = mock_client yield mock_ @@ -42,7 +42,7 @@ async def test_duplicate_error(hass): @pytest.mark.parametrize( - "mock_client_coro", [mock_coro(exception=aionotion.errors.NotionError)] + "mock_client", [AsyncMock(side_effect=aionotion.errors.NotionError)] ) async def test_invalid_credentials(hass, mock_aionotion): """Test that an invalid API/App Key throws an error.""" diff --git a/tests/components/nsw_rural_fire_service_feed/test_geo_location.py b/tests/components/nsw_rural_fire_service_feed/test_geo_location.py index 6834c557bd5..a5167104d48 100644 --- a/tests/components/nsw_rural_fire_service_feed/test_geo_location.py +++ b/tests/components/nsw_rural_fire_service_feed/test_geo_location.py @@ -3,7 +3,6 @@ import datetime from unittest.mock import ANY from aio_geojson_nsw_rfs_incidents import NswRuralFireServiceIncidentsFeed -from asynctest.mock import MagicMock, call, patch from homeassistant.components import geo_location from homeassistant.components.geo_location import ATTR_SOURCE @@ -37,6 +36,7 @@ from homeassistant.const import ( from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util +from tests.async_mock import MagicMock, call, patch from tests.common import assert_setup_component, async_fire_time_changed CONFIG = { diff --git a/tests/components/nuheat/mocks.py b/tests/components/nuheat/mocks.py index a9adfd3aa57..9755335ccc1 100644 --- a/tests/components/nuheat/mocks.py +++ b/tests/components/nuheat/mocks.py @@ -1,10 +1,11 @@ """The test for the NuHeat thermostat module.""" -from asynctest.mock import MagicMock, Mock from nuheat.config import SCHEDULE_HOLD, SCHEDULE_RUN, SCHEDULE_TEMPORARY_HOLD from homeassistant.components.nuheat.const import DOMAIN from homeassistant.const import CONF_DEVICES, CONF_PASSWORD, CONF_USERNAME +from tests.async_mock import MagicMock, Mock + def _get_mock_thermostat_run(): serial_number = "12345" diff --git a/tests/components/nuheat/test_climate.py b/tests/components/nuheat/test_climate.py index 7bf52026ef9..b407461fa89 100644 --- a/tests/components/nuheat/test_climate.py +++ b/tests/components/nuheat/test_climate.py @@ -1,6 +1,4 @@ """The test for the NuHeat thermostat module.""" -from asynctest.mock import patch - from homeassistant.components.nuheat.const import DOMAIN from homeassistant.setup import async_setup_component @@ -13,6 +11,8 @@ from .mocks import ( _mock_get_config, ) +from tests.async_mock import patch + async def test_climate_thermostat_run(hass): """Test a thermostat with the schedule running.""" diff --git a/tests/components/nuheat/test_config_flow.py b/tests/components/nuheat/test_config_flow.py index 338509f09d1..4c392841142 100644 --- a/tests/components/nuheat/test_config_flow.py +++ b/tests/components/nuheat/test_config_flow.py @@ -1,5 +1,4 @@ """Test the NuHeat config flow.""" -from asynctest import MagicMock, patch import requests from homeassistant import config_entries, setup @@ -8,6 +7,8 @@ from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, HTTP_INTERNAL_SERV from .mocks import _get_mock_thermostat_run +from tests.async_mock import MagicMock, patch + async def test_form_user(hass): """Test we get the form with user source.""" diff --git a/tests/components/nut/test_config_flow.py b/tests/components/nut/test_config_flow.py index ac20c989de9..7eb0ac20184 100644 --- a/tests/components/nut/test_config_flow.py +++ b/tests/components/nut/test_config_flow.py @@ -1,12 +1,11 @@ """Test the Network UPS Tools (NUT) config flow.""" -from asynctest import patch - from homeassistant import config_entries, data_entry_flow, setup from homeassistant.components.nut.const import DOMAIN from homeassistant.const import CONF_RESOURCES, CONF_SCAN_INTERVAL from .util import _get_mock_pynutclient +from tests.async_mock import patch from tests.common import MockConfigEntry VALID_CONFIG = { diff --git a/tests/components/nut/util.py b/tests/components/nut/util.py index 788076a7c9f..5622438d70b 100644 --- a/tests/components/nut/util.py +++ b/tests/components/nut/util.py @@ -2,12 +2,11 @@ import json -from asynctest import MagicMock, patch - from homeassistant.components.nut.const import DOMAIN from homeassistant.const import CONF_HOST, CONF_PORT, CONF_RESOURCES from homeassistant.core import HomeAssistant +from tests.async_mock import MagicMock, patch from tests.common import MockConfigEntry, load_fixture diff --git a/tests/components/nws/conftest.py b/tests/components/nws/conftest.py index 14cee7aa7cb..ac8428ddf48 100644 --- a/tests/components/nws/conftest.py +++ b/tests/components/nws/conftest.py @@ -3,7 +3,7 @@ from unittest.mock import patch import pytest -from tests.common import mock_coro +from tests.async_mock import AsyncMock from tests.components.nws.const import DEFAULT_FORECAST, DEFAULT_OBSERVATION @@ -12,10 +12,10 @@ def mock_simple_nws(): """Mock pynws SimpleNWS with default values.""" with patch("homeassistant.components.nws.SimpleNWS") as mock_nws: instance = mock_nws.return_value - instance.set_station.return_value = mock_coro() - instance.update_observation.return_value = mock_coro() - instance.update_forecast.return_value = mock_coro() - instance.update_forecast_hourly.return_value = mock_coro() + instance.set_station = AsyncMock(return_value=None) + instance.update_observation = AsyncMock(return_value=None) + instance.update_forecast = AsyncMock(return_value=None) + instance.update_forecast_hourly = AsyncMock(return_value=None) instance.station = "ABC" instance.stations = ["ABC"] instance.observation = DEFAULT_OBSERVATION @@ -29,7 +29,7 @@ def mock_simple_nws_config(): """Mock pynws SimpleNWS with default values in config_flow.""" with patch("homeassistant.components.nws.config_flow.SimpleNWS") as mock_nws: instance = mock_nws.return_value - instance.set_station.return_value = mock_coro() + instance.set_station = AsyncMock(return_value=None) instance.station = "ABC" instance.stations = ["ABC"] yield mock_nws diff --git a/tests/components/nws/test_config_flow.py b/tests/components/nws/test_config_flow.py index d4957d4c989..bca852fa379 100644 --- a/tests/components/nws/test_config_flow.py +++ b/tests/components/nws/test_config_flow.py @@ -1,10 +1,11 @@ """Test the National Weather Service (NWS) config flow.""" import aiohttp -from asynctest import patch from homeassistant import config_entries, setup from homeassistant.components.nws.const import DOMAIN +from tests.async_mock import patch + async def test_form(hass, mock_simple_nws_config): """Test we get the form.""" diff --git a/tests/components/openalpr_cloud/test_image_processing.py b/tests/components/openalpr_cloud/test_image_processing.py index f5a246bcb4d..c164f2f03a2 100644 --- a/tests/components/openalpr_cloud/test_image_processing.py +++ b/tests/components/openalpr_cloud/test_image_processing.py @@ -1,19 +1,13 @@ """The tests for the openalpr cloud platform.""" import asyncio -from asynctest import PropertyMock, patch - from homeassistant.components import camera, image_processing as ip from homeassistant.components.openalpr_cloud.image_processing import OPENALPR_API_URL from homeassistant.core import callback from homeassistant.setup import setup_component -from tests.common import ( - assert_setup_component, - get_test_home_assistant, - load_fixture, - mock_coro, -) +from tests.async_mock import PropertyMock, patch +from tests.common import assert_setup_component, get_test_home_assistant, load_fixture from tests.components.image_processing import common @@ -146,7 +140,7 @@ class TestOpenAlprCloud: with patch( "homeassistant.components.camera.async_get_image", - return_value=mock_coro(camera.Image("image/jpeg", b"image")), + return_value=camera.Image("image/jpeg", b"image"), ): common.scan(self.hass, entity_id="image_processing.test_local") self.hass.block_till_done() @@ -179,7 +173,7 @@ class TestOpenAlprCloud: with patch( "homeassistant.components.camera.async_get_image", - return_value=mock_coro(camera.Image("image/jpeg", b"image")), + return_value=camera.Image("image/jpeg", b"image"), ): common.scan(self.hass, entity_id="image_processing.test_local") self.hass.block_till_done() @@ -195,7 +189,7 @@ class TestOpenAlprCloud: with patch( "homeassistant.components.camera.async_get_image", - return_value=mock_coro(camera.Image("image/jpeg", b"image")), + return_value=camera.Image("image/jpeg", b"image"), ): common.scan(self.hass, entity_id="image_processing.test_local") self.hass.block_till_done() diff --git a/tests/components/openalpr_local/test_image_processing.py b/tests/components/openalpr_local/test_image_processing.py index 3f62c906974..996d23184a2 100644 --- a/tests/components/openalpr_local/test_image_processing.py +++ b/tests/components/openalpr_local/test_image_processing.py @@ -1,16 +1,15 @@ """The tests for the openalpr local platform.""" -from asynctest import MagicMock, PropertyMock, patch - import homeassistant.components.image_processing as ip from homeassistant.const import ATTR_ENTITY_PICTURE from homeassistant.core import callback from homeassistant.setup import setup_component +from tests.async_mock import MagicMock, PropertyMock, patch from tests.common import assert_setup_component, get_test_home_assistant, load_fixture from tests.components.image_processing import common -async def mock_async_subprocess(): +def mock_async_subprocess(): """Get a Popen mock back.""" async_popen = MagicMock() diff --git a/tests/components/opentherm_gw/test_config_flow.py b/tests/components/opentherm_gw/test_config_flow.py index 2dec360eca0..003d2ad7170 100644 --- a/tests/components/opentherm_gw/test_config_flow.py +++ b/tests/components/opentherm_gw/test_config_flow.py @@ -1,7 +1,6 @@ """Test the Opentherm Gateway config flow.""" import asyncio -from asynctest import patch from pyotgw.vars import OTGW_ABOUT from serial import SerialException @@ -13,7 +12,8 @@ from homeassistant.components.opentherm_gw.const import ( ) from homeassistant.const import CONF_DEVICE, CONF_ID, CONF_NAME, PRECISION_HALVES -from tests.common import MockConfigEntry, mock_coro +from tests.async_mock import patch +from tests.common import MockConfigEntry async def test_form_user(hass): @@ -26,16 +26,13 @@ async def test_form_user(hass): assert result["errors"] == {} with patch( - "homeassistant.components.opentherm_gw.async_setup", - return_value=mock_coro(True), + "homeassistant.components.opentherm_gw.async_setup", return_value=True, ) as mock_setup, patch( - "homeassistant.components.opentherm_gw.async_setup_entry", - return_value=mock_coro(True), + "homeassistant.components.opentherm_gw.async_setup_entry", return_value=True, ) as mock_setup_entry, patch( - "pyotgw.pyotgw.connect", - return_value=mock_coro({OTGW_ABOUT: "OpenTherm Gateway 4.2.5"}), + "pyotgw.pyotgw.connect", return_value={OTGW_ABOUT: "OpenTherm Gateway 4.2.5"}, ) as mock_pyotgw_connect, patch( - "pyotgw.pyotgw.disconnect", return_value=mock_coro(None) + "pyotgw.pyotgw.disconnect", return_value=None ) as mock_pyotgw_disconnect: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_NAME: "Test Entry 1", CONF_DEVICE: "/dev/ttyUSB0"} @@ -59,16 +56,13 @@ async def test_form_import(hass): """Test import from existing config.""" await setup.async_setup_component(hass, "persistent_notification", {}) with patch( - "homeassistant.components.opentherm_gw.async_setup", - return_value=mock_coro(True), + "homeassistant.components.opentherm_gw.async_setup", return_value=True, ) as mock_setup, patch( - "homeassistant.components.opentherm_gw.async_setup_entry", - return_value=mock_coro(True), + "homeassistant.components.opentherm_gw.async_setup_entry", return_value=True, ) as mock_setup_entry, patch( - "pyotgw.pyotgw.connect", - return_value=mock_coro({OTGW_ABOUT: "OpenTherm Gateway 4.2.5"}), + "pyotgw.pyotgw.connect", return_value={OTGW_ABOUT: "OpenTherm Gateway 4.2.5"}, ) as mock_pyotgw_connect, patch( - "pyotgw.pyotgw.disconnect", return_value=mock_coro(None) + "pyotgw.pyotgw.disconnect", return_value=None ) as mock_pyotgw_disconnect: result = await hass.config_entries.flow.async_init( DOMAIN, @@ -102,16 +96,13 @@ async def test_form_duplicate_entries(hass): ) with patch( - "homeassistant.components.opentherm_gw.async_setup", - return_value=mock_coro(True), + "homeassistant.components.opentherm_gw.async_setup", return_value=True, ) as mock_setup, patch( - "homeassistant.components.opentherm_gw.async_setup_entry", - return_value=mock_coro(True), + "homeassistant.components.opentherm_gw.async_setup_entry", return_value=True, ) as mock_setup_entry, patch( - "pyotgw.pyotgw.connect", - return_value=mock_coro({OTGW_ABOUT: "OpenTherm Gateway 4.2.5"}), + "pyotgw.pyotgw.connect", return_value={OTGW_ABOUT: "OpenTherm Gateway 4.2.5"}, ) as mock_pyotgw_connect, patch( - "pyotgw.pyotgw.disconnect", return_value=mock_coro(None) + "pyotgw.pyotgw.disconnect", return_value=None ) as mock_pyotgw_disconnect: result1 = await hass.config_entries.flow.async_configure( flow1["flow_id"], {CONF_NAME: "Test Entry 1", CONF_DEVICE: "/dev/ttyUSB0"} diff --git a/tests/components/owntracks/test_config_flow.py b/tests/components/owntracks/test_config_flow.py index 514a559ac1d..676e47523fa 100644 --- a/tests/components/owntracks/test_config_flow.py +++ b/tests/components/owntracks/test_config_flow.py @@ -1,5 +1,4 @@ """Tests for OwnTracks config flow.""" -from asynctest import Mock, patch import pytest from homeassistant import data_entry_flow @@ -9,7 +8,8 @@ from homeassistant.components.owntracks.const import DOMAIN from homeassistant.const import CONF_WEBHOOK_ID from homeassistant.setup import async_setup_component -from tests.common import MockConfigEntry, mock_coro +from tests.async_mock import Mock, patch +from tests.common import MockConfigEntry CONF_WEBHOOK_URL = "webhook_url" @@ -140,7 +140,7 @@ async def test_unload(hass): with patch( "homeassistant.config_entries.ConfigEntries.async_forward_entry_unload", - return_value=mock_coro(), + return_value=None, ) as mock_unload: assert await hass.config_entries.async_unload(entry.entry_id) @@ -157,7 +157,7 @@ async def test_with_cloud_sub(hass): "homeassistant.components.cloud.async_active_subscription", return_value=True ), patch( "homeassistant.components.cloud.async_create_cloudhook", - return_value=mock_coro("https://hooks.nabu.casa/ABCD"), + return_value="https://hooks.nabu.casa/ABCD", ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"}, data={} diff --git a/tests/components/owntracks/test_device_tracker.py b/tests/components/owntracks/test_device_tracker.py index bdd1199008c..d71f0fe0aee 100644 --- a/tests/components/owntracks/test_device_tracker.py +++ b/tests/components/owntracks/test_device_tracker.py @@ -1,13 +1,13 @@ """The tests for the Owntracks device tracker.""" import json -from asynctest import patch import pytest from homeassistant.components import owntracks from homeassistant.const import STATE_NOT_HOME from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import ( MockConfigEntry, async_fire_mqtt_message, diff --git a/tests/components/panasonic_viera/test_config_flow.py b/tests/components/panasonic_viera/test_config_flow.py index fd2738508ea..cc7c3f58e82 100644 --- a/tests/components/panasonic_viera/test_config_flow.py +++ b/tests/components/panasonic_viera/test_config_flow.py @@ -1,7 +1,6 @@ """Test the Panasonic Viera config flow.""" from unittest.mock import Mock -from asynctest import patch from panasonic_viera import TV_TYPE_ENCRYPTED, TV_TYPE_NONENCRYPTED, SOAPError import pytest @@ -20,6 +19,7 @@ from homeassistant.components.panasonic_viera.const import ( ) from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PIN, CONF_PORT +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/person/test_init.py b/tests/components/person/test_init.py index 76350619983..887f0d94fef 100644 --- a/tests/components/person/test_init.py +++ b/tests/components/person/test_init.py @@ -1,7 +1,6 @@ """The tests for the person component.""" import logging -from asynctest import patch import pytest from homeassistant.components import person @@ -24,6 +23,7 @@ from homeassistant.core import Context, CoreState, State from homeassistant.helpers import collection, entity_registry from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import assert_setup_component, mock_component, mock_restore_cache DEVICE_TRACKER = "device_tracker.test_tracker" diff --git a/tests/components/pi_hole/test_init.py b/tests/components/pi_hole/test_init.py index c2d9ec77f03..236e8eadde8 100644 --- a/tests/components/pi_hole/test_init.py +++ b/tests/components/pi_hole/test_init.py @@ -2,10 +2,9 @@ from unittest.mock import patch -from asynctest import CoroutineMock - from homeassistant.components import pi_hole +from tests.async_mock import AsyncMock from tests.common import async_setup_component ZERO_DATA = { @@ -25,7 +24,7 @@ ZERO_DATA = { async def test_setup_minimal_config(hass): """Tests component setup with minimal config.""" with patch("homeassistant.components.pi_hole.Hole") as _hole: - _hole.return_value.get_data = CoroutineMock(return_value=None) + _hole.return_value.get_data = AsyncMock(return_value=None) _hole.return_value.data = ZERO_DATA assert await async_setup_component( @@ -82,7 +81,7 @@ async def test_setup_minimal_config(hass): async def test_setup_name_config(hass): """Tests component setup with a custom name.""" with patch("homeassistant.components.pi_hole.Hole") as _hole: - _hole.return_value.get_data = CoroutineMock(return_value=None) + _hole.return_value.get_data = AsyncMock(return_value=None) _hole.return_value.data = ZERO_DATA assert await async_setup_component( @@ -102,9 +101,9 @@ async def test_setup_name_config(hass): async def test_disable_service_call(hass): """Test disable service call with no Pi-hole named.""" with patch("homeassistant.components.pi_hole.Hole") as _hole: - mock_disable = CoroutineMock(return_value=None) + mock_disable = AsyncMock(return_value=None) _hole.return_value.disable = mock_disable - _hole.return_value.get_data = CoroutineMock(return_value=None) + _hole.return_value.get_data = AsyncMock(return_value=None) _hole.return_value.data = ZERO_DATA assert await async_setup_component( @@ -135,9 +134,9 @@ async def test_disable_service_call(hass): async def test_enable_service_call(hass): """Test enable service call with no Pi-hole named.""" with patch("homeassistant.components.pi_hole.Hole") as _hole: - mock_enable = CoroutineMock(return_value=None) + mock_enable = AsyncMock(return_value=None) _hole.return_value.enable = mock_enable - _hole.return_value.get_data = CoroutineMock(return_value=None) + _hole.return_value.get_data = AsyncMock(return_value=None) _hole.return_value.data = ZERO_DATA assert await async_setup_component( diff --git a/tests/components/plex/test_config_flow.py b/tests/components/plex/test_config_flow.py index d839ccc674b..af065b55e50 100644 --- a/tests/components/plex/test_config_flow.py +++ b/tests/components/plex/test_config_flow.py @@ -1,7 +1,6 @@ """Tests for Plex config flow.""" import copy -from asynctest import patch import plexapi.exceptions import requests.exceptions @@ -26,6 +25,7 @@ from homeassistant.setup import async_setup_component from .const import DEFAULT_DATA, DEFAULT_OPTIONS, MOCK_SERVERS, MOCK_TOKEN from .mock_classes import MockPlexAccount, MockPlexServer +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/plex/test_init.py b/tests/components/plex/test_init.py index 09a2e8f6ada..e34476f1813 100644 --- a/tests/components/plex/test_init.py +++ b/tests/components/plex/test_init.py @@ -3,9 +3,7 @@ import copy from datetime import timedelta import ssl -from asynctest import ClockedTestCase, patch import plexapi -import pytest import requests from homeassistant.components.media_player import DOMAIN as MP_DOMAIN @@ -31,11 +29,8 @@ import homeassistant.util.dt as dt_util from .const import DEFAULT_DATA, DEFAULT_OPTIONS, MOCK_SERVERS, MOCK_TOKEN from .mock_classes import MockPlexAccount, MockPlexServer -from tests.common import ( - MockConfigEntry, - async_fire_time_changed, - async_test_home_assistant, -) +from tests.async_mock import patch +from tests.common import MockConfigEntry, async_fire_time_changed async def test_setup_with_config(hass): @@ -73,87 +68,86 @@ async def test_setup_with_config(hass): assert loaded_server.plex_server == mock_plex_server -@pytest.mark.skip -class TestClockedPlex(ClockedTestCase): - """Create clock-controlled asynctest class.""" +# class TestClockedPlex(ClockedTestCase): +# """Create clock-controlled tests.async_mock class.""" - @pytest.fixture(autouse=True) - def inject_fixture(self, caplog, hass_storage): - """Inject pytest fixtures as instance attributes.""" - self.caplog = caplog +# @pytest.fixture(autouse=True) +# def inject_fixture(self, caplog, hass_storage): +# """Inject pytest fixtures as instance attributes.""" +# self.caplog = caplog - async def setUp(self): - """Initialize this test class.""" - self.hass = await async_test_home_assistant(self.loop) +# async def setUp(self): +# """Initialize this test class.""" +# self.hass = await async_test_home_assistant(self.loop) - async def tearDown(self): - """Clean up the HomeAssistant instance.""" - await self.hass.async_stop() +# async def tearDown(self): +# """Clean up the HomeAssistant instance.""" +# await self.hass.async_stop() - async def test_setup_with_config_entry(self): - """Test setup component with config.""" - hass = self.hass +# async def test_setup_with_config_entry(self): +# """Test setup component with config.""" +# hass = self.hass - mock_plex_server = MockPlexServer() +# mock_plex_server = MockPlexServer() - entry = MockConfigEntry( - domain=const.DOMAIN, - data=DEFAULT_DATA, - options=DEFAULT_OPTIONS, - unique_id=DEFAULT_DATA["server_id"], - ) +# entry = MockConfigEntry( +# domain=const.DOMAIN, +# data=DEFAULT_DATA, +# options=DEFAULT_OPTIONS, +# unique_id=DEFAULT_DATA["server_id"], +# ) - with patch("plexapi.server.PlexServer", return_value=mock_plex_server), patch( - "homeassistant.components.plex.PlexWebsocket.listen" - ) as mock_listen: - entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(entry.entry_id) - await hass.async_block_till_done() +# with patch("plexapi.server.PlexServer", return_value=mock_plex_server), patch( +# "homeassistant.components.plex.PlexWebsocket.listen" +# ) as mock_listen: +# entry.add_to_hass(hass) +# assert await hass.config_entries.async_setup(entry.entry_id) +# await hass.async_block_till_done() - assert mock_listen.called +# assert mock_listen.called - assert len(hass.config_entries.async_entries(const.DOMAIN)) == 1 - assert entry.state == ENTRY_STATE_LOADED +# assert len(hass.config_entries.async_entries(const.DOMAIN)) == 1 +# assert entry.state == ENTRY_STATE_LOADED - server_id = mock_plex_server.machineIdentifier - loaded_server = hass.data[const.DOMAIN][const.SERVERS][server_id] +# server_id = mock_plex_server.machineIdentifier +# loaded_server = hass.data[const.DOMAIN][const.SERVERS][server_id] - assert loaded_server.plex_server == mock_plex_server +# assert loaded_server.plex_server == mock_plex_server - async_dispatcher_send( - hass, const.PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id) - ) - await hass.async_block_till_done() +# async_dispatcher_send( +# hass, const.PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id) +# ) +# await hass.async_block_till_done() - sensor = hass.states.get("sensor.plex_plex_server_1") - assert sensor.state == str(len(mock_plex_server.accounts)) +# sensor = hass.states.get("sensor.plex_plex_server_1") +# assert sensor.state == str(len(mock_plex_server.accounts)) - # Ensure existing entities refresh - await self.advance(const.DEBOUNCE_TIMEOUT) - async_dispatcher_send( - hass, const.PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id) - ) - await hass.async_block_till_done() +# # Ensure existing entities refresh +# await self.advance(const.DEBOUNCE_TIMEOUT) +# async_dispatcher_send( +# hass, const.PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id) +# ) +# await hass.async_block_till_done() - for test_exception in ( - plexapi.exceptions.BadRequest, - requests.exceptions.RequestException, - ): - with patch.object( - mock_plex_server, "clients", side_effect=test_exception - ) as patched_clients_bad_request: - await self.advance(const.DEBOUNCE_TIMEOUT) - async_dispatcher_send( - hass, const.PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id) - ) - await hass.async_block_till_done() +# for test_exception in ( +# plexapi.exceptions.BadRequest, +# requests.exceptions.RequestException, +# ): +# with patch.object( +# mock_plex_server, "clients", side_effect=test_exception +# ) as patched_clients_bad_request: +# await self.advance(const.DEBOUNCE_TIMEOUT) +# async_dispatcher_send( +# hass, const.PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id) +# ) +# await hass.async_block_till_done() - assert patched_clients_bad_request.called - assert ( - f"Could not connect to Plex server: {mock_plex_server.friendlyName}" - in self.caplog.text - ) - self.caplog.clear() +# assert patched_clients_bad_request.called +# assert ( +# f"Could not connect to Plex server: {mock_plex_server.friendlyName}" +# in self.caplog.text +# ) +# self.caplog.clear() async def test_set_config_entry_unique_id(hass): diff --git a/tests/components/plex/test_server.py b/tests/components/plex/test_server.py index b3cbd6c79d4..7cb34b4fcca 100644 --- a/tests/components/plex/test_server.py +++ b/tests/components/plex/test_server.py @@ -1,14 +1,10 @@ """Tests for Plex server.""" import copy -from asynctest import ClockedTestCase, patch -import pytest - from homeassistant.components.media_player import DOMAIN as MP_DOMAIN from homeassistant.components.plex.const import ( CONF_IGNORE_NEW_SHARED_USERS, CONF_MONITORED_USERS, - DEBOUNCE_TIMEOUT, DOMAIN, PLEX_UPDATE_PLATFORMS_SIGNAL, SERVERS, @@ -18,7 +14,8 @@ from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import DEFAULT_DATA, DEFAULT_OPTIONS from .mock_classes import MockPlexServer -from tests.common import MockConfigEntry, async_test_home_assistant +from tests.async_mock import patch +from tests.common import MockConfigEntry async def test_new_users_available(hass): @@ -108,107 +105,106 @@ async def test_new_ignored_users_available(hass, caplog): assert sensor.state == str(len(mock_plex_server.accounts)) -@pytest.mark.skip -class TestClockedPlex(ClockedTestCase): - """Create clock-controlled asynctest class.""" +# class TestClockedPlex(ClockedTestCase): +# """Create clock-controlled tests.async_mock class.""" - async def setUp(self): - """Initialize this test class.""" - self.hass = await async_test_home_assistant(self.loop) +# async def setUp(self): +# """Initialize this test class.""" +# self.hass = await async_test_home_assistant(self.loop) - async def tearDown(self): - """Clean up the HomeAssistant instance.""" - await self.hass.async_stop() +# async def tearDown(self): +# """Clean up the HomeAssistant instance.""" +# await self.hass.async_stop() - async def test_mark_sessions_idle(self): - """Test marking media_players as idle when sessions end.""" - hass = self.hass +# async def test_mark_sessions_idle(self): +# """Test marking media_players as idle when sessions end.""" +# hass = self.hass - entry = MockConfigEntry( - domain=DOMAIN, - data=DEFAULT_DATA, - options=DEFAULT_OPTIONS, - unique_id=DEFAULT_DATA["server_id"], - ) +# entry = MockConfigEntry( +# domain=DOMAIN, +# data=DEFAULT_DATA, +# options=DEFAULT_OPTIONS, +# unique_id=DEFAULT_DATA["server_id"], +# ) - mock_plex_server = MockPlexServer(config_entry=entry) +# mock_plex_server = MockPlexServer(config_entry=entry) - with patch("plexapi.server.PlexServer", return_value=mock_plex_server), patch( - "homeassistant.components.plex.PlexWebsocket.listen" - ): - entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(entry.entry_id) - await hass.async_block_till_done() +# with patch("plexapi.server.PlexServer", return_value=mock_plex_server), patch( +# "homeassistant.components.plex.PlexWebsocket.listen" +# ): +# entry.add_to_hass(hass) +# assert await hass.config_entries.async_setup(entry.entry_id) +# await hass.async_block_till_done() - server_id = mock_plex_server.machineIdentifier +# server_id = mock_plex_server.machineIdentifier - async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) - await hass.async_block_till_done() +# async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) +# await hass.async_block_till_done() - sensor = hass.states.get("sensor.plex_plex_server_1") - assert sensor.state == str(len(mock_plex_server.accounts)) +# sensor = hass.states.get("sensor.plex_plex_server_1") +# assert sensor.state == str(len(mock_plex_server.accounts)) - mock_plex_server.clear_clients() - mock_plex_server.clear_sessions() +# mock_plex_server.clear_clients() +# mock_plex_server.clear_sessions() - await self.advance(DEBOUNCE_TIMEOUT) - async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) - await hass.async_block_till_done() +# await self.advance(DEBOUNCE_TIMEOUT) +# async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) +# await hass.async_block_till_done() - sensor = hass.states.get("sensor.plex_plex_server_1") - assert sensor.state == "0" +# sensor = hass.states.get("sensor.plex_plex_server_1") +# assert sensor.state == "0" - async def test_debouncer(self): - """Test debouncer behavior.""" - hass = self.hass +# async def test_debouncer(self): +# """Test debouncer behavior.""" +# hass = self.hass - entry = MockConfigEntry( - domain=DOMAIN, - data=DEFAULT_DATA, - options=DEFAULT_OPTIONS, - unique_id=DEFAULT_DATA["server_id"], - ) +# entry = MockConfigEntry( +# domain=DOMAIN, +# data=DEFAULT_DATA, +# options=DEFAULT_OPTIONS, +# unique_id=DEFAULT_DATA["server_id"], +# ) - mock_plex_server = MockPlexServer(config_entry=entry) +# mock_plex_server = MockPlexServer(config_entry=entry) - with patch("plexapi.server.PlexServer", return_value=mock_plex_server), patch( - "homeassistant.components.plex.PlexWebsocket.listen" - ): - entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(entry.entry_id) - await hass.async_block_till_done() +# with patch("plexapi.server.PlexServer", return_value=mock_plex_server), patch( +# "homeassistant.components.plex.PlexWebsocket.listen" +# ): +# entry.add_to_hass(hass) +# assert await hass.config_entries.async_setup(entry.entry_id) +# await hass.async_block_till_done() - server_id = mock_plex_server.machineIdentifier +# server_id = mock_plex_server.machineIdentifier - with patch.object(mock_plex_server, "clients", return_value=[]), patch.object( - mock_plex_server, "sessions", return_value=[] - ) as mock_update: - # Called immediately - async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) - await hass.async_block_till_done() - assert mock_update.call_count == 1 +# with patch.object(mock_plex_server, "clients", return_value=[]), patch.object( +# mock_plex_server, "sessions", return_value=[] +# ) as mock_update: +# # Called immediately +# async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) +# await hass.async_block_till_done() +# assert mock_update.call_count == 1 - # Throttled - async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) - await hass.async_block_till_done() - assert mock_update.call_count == 1 +# # Throttled +# async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) +# await hass.async_block_till_done() +# assert mock_update.call_count == 1 - # Throttled - async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) - await hass.async_block_till_done() - assert mock_update.call_count == 1 +# # Throttled +# async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) +# await hass.async_block_till_done() +# assert mock_update.call_count == 1 - # Called from scheduler - await self.advance(DEBOUNCE_TIMEOUT) - await hass.async_block_till_done() - assert mock_update.call_count == 2 +# # Called from scheduler +# await self.advance(DEBOUNCE_TIMEOUT) +# await hass.async_block_till_done() +# assert mock_update.call_count == 2 - # Throttled - async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) - await hass.async_block_till_done() - assert mock_update.call_count == 2 +# # Throttled +# async_dispatcher_send(hass, PLEX_UPDATE_PLATFORMS_SIGNAL.format(server_id)) +# await hass.async_block_till_done() +# assert mock_update.call_count == 2 - # Called from scheduler - await self.advance(DEBOUNCE_TIMEOUT) - await hass.async_block_till_done() - assert mock_update.call_count == 3 +# # Called from scheduler +# await self.advance(DEBOUNCE_TIMEOUT) +# await hass.async_block_till_done() +# assert mock_update.call_count == 3 diff --git a/tests/components/point/test_config_flow.py b/tests/components/point/test_config_flow.py index c1c705e752d..1714dd5a352 100644 --- a/tests/components/point/test_config_flow.py +++ b/tests/components/point/test_config_flow.py @@ -1,21 +1,20 @@ """Tests for the Point config flow.""" import asyncio -from unittest.mock import Mock, patch import pytest from homeassistant import data_entry_flow from homeassistant.components.point import DOMAIN, config_flow -from tests.common import mock_coro +from tests.async_mock import AsyncMock, patch def init_config_flow(hass, side_effect=None): """Init a configuration flow.""" config_flow.register_flow_implementation(hass, DOMAIN, "id", "secret") flow = config_flow.PointFlowHandler() - flow._get_authorization_url = Mock( # pylint: disable=protected-access - return_value=mock_coro("https://example.com"), side_effect=side_effect + flow._get_authorization_url = AsyncMock( # pylint: disable=protected-access + return_value="https://example.com", side_effect=side_effect ) flow.hass = hass return flow diff --git a/tests/components/powerwall/mocks.py b/tests/components/powerwall/mocks.py index 8a559d1dd49..a384725daa8 100644 --- a/tests/components/powerwall/mocks.py +++ b/tests/components/powerwall/mocks.py @@ -3,7 +3,6 @@ import json import os -from asynctest import MagicMock, Mock from tesla_powerwall import ( DeviceType, GridStatus, @@ -17,6 +16,7 @@ from tesla_powerwall import ( from homeassistant.components.powerwall.const import DOMAIN from homeassistant.const import CONF_IP_ADDRESS +from tests.async_mock import MagicMock, Mock from tests.common import load_fixture diff --git a/tests/components/powerwall/test_binary_sensor.py b/tests/components/powerwall/test_binary_sensor.py index c8a081de573..fcca7fb34ab 100644 --- a/tests/components/powerwall/test_binary_sensor.py +++ b/tests/components/powerwall/test_binary_sensor.py @@ -1,13 +1,13 @@ """The binary sensor tests for the powerwall platform.""" -from asynctest import patch - from homeassistant.components.powerwall.const import DOMAIN from homeassistant.const import STATE_ON from homeassistant.setup import async_setup_component from .mocks import _mock_get_config, _mock_powerwall_with_fixtures +from tests.async_mock import patch + async def test_sensors(hass): """Test creation of the binary sensors.""" diff --git a/tests/components/powerwall/test_config_flow.py b/tests/components/powerwall/test_config_flow.py index 097346c5ac7..eaf53f0beef 100644 --- a/tests/components/powerwall/test_config_flow.py +++ b/tests/components/powerwall/test_config_flow.py @@ -1,6 +1,5 @@ """Test the Powerwall config flow.""" -from asynctest import patch from tesla_powerwall import APIChangedError, PowerwallUnreachableError from homeassistant import config_entries, setup @@ -9,6 +8,8 @@ from homeassistant.const import CONF_IP_ADDRESS from .mocks import _mock_powerwall_side_effect, _mock_powerwall_site_name +from tests.async_mock import patch + async def test_form_source_user(hass): """Test we get config flow setup form as a user.""" diff --git a/tests/components/powerwall/test_sensor.py b/tests/components/powerwall/test_sensor.py index c68d9f0279e..af2835ea679 100644 --- a/tests/components/powerwall/test_sensor.py +++ b/tests/components/powerwall/test_sensor.py @@ -1,13 +1,13 @@ """The sensor tests for the powerwall platform.""" -from asynctest import patch - from homeassistant.components.powerwall.const import DOMAIN from homeassistant.const import UNIT_PERCENTAGE from homeassistant.setup import async_setup_component from .mocks import _mock_get_config, _mock_powerwall_with_fixtures +from tests.async_mock import patch + async def test_sensors(hass): """Test creation of the sensors.""" diff --git a/tests/components/ps4/conftest.py b/tests/components/ps4/conftest.py index e945af3220d..42002404db2 100644 --- a/tests/components/ps4/conftest.py +++ b/tests/components/ps4/conftest.py @@ -1,7 +1,8 @@ """Test configuration for PS4.""" -from asynctest import patch import pytest +from tests.async_mock import patch + @pytest.fixture def patch_load_json(): diff --git a/tests/components/ps4/test_config_flow.py b/tests/components/ps4/test_config_flow.py index 2bad2d1e281..c5e0623de5b 100644 --- a/tests/components/ps4/test_config_flow.py +++ b/tests/components/ps4/test_config_flow.py @@ -1,5 +1,4 @@ """Define tests for the PlayStation 4 config flow.""" -from asynctest import patch from pyps4_2ndscreen.errors import CredentialTimeout import pytest @@ -21,6 +20,7 @@ from homeassistant.const import ( ) from homeassistant.util import location +from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" diff --git a/tests/components/ps4/test_init.py b/tests/components/ps4/test_init.py index 68179ad54c2..7f7eff33ebb 100644 --- a/tests/components/ps4/test_init.py +++ b/tests/components/ps4/test_init.py @@ -1,6 +1,4 @@ """Tests for the PS4 Integration.""" -from asynctest import MagicMock, patch - from homeassistant import config_entries, data_entry_flow from homeassistant.components import ps4 from homeassistant.components.media_player.const import ( @@ -29,6 +27,7 @@ from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import async_setup_component from homeassistant.util import location +from tests.async_mock import MagicMock, patch from tests.common import MockConfigEntry, mock_registry MOCK_HOST = "192.168.0.1" diff --git a/tests/components/ps4/test_media_player.py b/tests/components/ps4/test_media_player.py index b7725795f5c..8ff8dea71ce 100644 --- a/tests/components/ps4/test_media_player.py +++ b/tests/components/ps4/test_media_player.py @@ -1,5 +1,4 @@ """Tests for the PS4 media player platform.""" -from asynctest import MagicMock, patch from pyps4_2ndscreen.credential import get_ddp_message from homeassistant.components import ps4 @@ -34,6 +33,7 @@ from homeassistant.const import ( ) from homeassistant.setup import async_setup_component +from tests.async_mock import MagicMock, patch from tests.common import MockConfigEntry, mock_device_registry, mock_registry MOCK_CREDS = "123412341234abcd12341234abcd12341234abcd12341234abcd12341234abcd" diff --git a/tests/components/ptvsd/test_ptvsd.py b/tests/components/ptvsd/test_ptvsd.py index d4a2aa1ab94..9df686cfcbd 100644 --- a/tests/components/ptvsd/test_ptvsd.py +++ b/tests/components/ptvsd/test_ptvsd.py @@ -2,13 +2,14 @@ from unittest.mock import patch -from asynctest import CoroutineMock from pytest import mark from homeassistant.bootstrap import _async_set_up_integrations import homeassistant.components.ptvsd as ptvsd_component from homeassistant.setup import async_setup_component +from tests.async_mock import AsyncMock + @mark.skip("causes code cover to fail") async def test_ptvsd(hass): @@ -42,9 +43,7 @@ async def test_ptvsd_bootstrap(hass): """Test loading ptvsd component with wait.""" config = {ptvsd_component.DOMAIN: {ptvsd_component.CONF_WAIT: True}} - with patch( - "homeassistant.components.ptvsd.async_setup", CoroutineMock() - ) as setup_mock: + with patch("homeassistant.components.ptvsd.async_setup", AsyncMock()) as setup_mock: setup_mock.return_value = True await _async_set_up_integrations(hass, config) diff --git a/tests/components/qwikswitch/test_init.py b/tests/components/qwikswitch/test_init.py index b0be2dbc81c..6075174fa98 100644 --- a/tests/components/qwikswitch/test_init.py +++ b/tests/components/qwikswitch/test_init.py @@ -3,13 +3,13 @@ import asyncio import logging from aiohttp.client_exceptions import ClientError -from asynctest import Mock import pytest from yarl import URL from homeassistant.components.qwikswitch import DOMAIN as QWIKSWITCH from homeassistant.setup import async_setup_component +from tests.async_mock import Mock from tests.test_util.aiohttp import AiohttpClientMockResponse, MockLongPollSideEffect _LOGGER = logging.getLogger(__name__) diff --git a/tests/components/rachio/test_config_flow.py b/tests/components/rachio/test_config_flow.py index cadc346e403..7cc3f272e7a 100644 --- a/tests/components/rachio/test_config_flow.py +++ b/tests/components/rachio/test_config_flow.py @@ -1,7 +1,4 @@ """Test the Rachio config flow.""" -from asynctest import patch -from asynctest.mock import MagicMock - from homeassistant import config_entries, setup from homeassistant.components.rachio.const import ( CONF_CUSTOM_URL, @@ -10,6 +7,7 @@ from homeassistant.components.rachio.const import ( ) from homeassistant.const import CONF_API_KEY +from tests.async_mock import MagicMock, patch from tests.common import MockConfigEntry diff --git a/tests/components/rainmachine/test_config_flow.py b/tests/components/rainmachine/test_config_flow.py index 4351470cff5..04dc67bdbe8 100644 --- a/tests/components/rainmachine/test_config_flow.py +++ b/tests/components/rainmachine/test_config_flow.py @@ -1,5 +1,4 @@ """Define tests for the OpenUV config flow.""" -from asynctest import patch from regenmaschine.errors import RainMachineError from homeassistant import data_entry_flow @@ -13,7 +12,8 @@ from homeassistant.const import ( CONF_SSL, ) -from tests.common import MockConfigEntry, mock_coro +from tests.async_mock import patch +from tests.common import MockConfigEntry async def test_duplicate_error(hass): @@ -51,7 +51,7 @@ async def test_invalid_password(hass): with patch( "homeassistant.components.rainmachine.config_flow.login", - return_value=mock_coro(exception=RainMachineError), + side_effect=RainMachineError, ): result = await flow.async_step_user(user_input=conf) assert result["errors"] == {CONF_PASSWORD: "invalid_credentials"} @@ -84,8 +84,7 @@ async def test_step_import(hass): flow.context = {"source": SOURCE_USER} with patch( - "homeassistant.components.rainmachine.config_flow.login", - return_value=mock_coro(True), + "homeassistant.components.rainmachine.config_flow.login", return_value=True, ): result = await flow.async_step_import(import_config=conf) @@ -116,8 +115,7 @@ async def test_step_user(hass): flow.context = {"source": SOURCE_USER} with patch( - "homeassistant.components.rainmachine.config_flow.login", - return_value=mock_coro(True), + "homeassistant.components.rainmachine.config_flow.login", return_value=True, ): result = await flow.async_step_user(user_input=conf) diff --git a/tests/components/ring/test_config_flow.py b/tests/components/ring/test_config_flow.py index 421e8a26694..57723d1ede7 100644 --- a/tests/components/ring/test_config_flow.py +++ b/tests/components/ring/test_config_flow.py @@ -1,11 +1,9 @@ """Test the Ring config flow.""" -from asynctest import Mock, patch - from homeassistant import config_entries, setup from homeassistant.components.ring import DOMAIN from homeassistant.components.ring.config_flow import InvalidAuth -from tests.common import mock_coro +from tests.async_mock import Mock, patch async def test_form(hass): @@ -23,9 +21,9 @@ async def test_form(hass): fetch_token=Mock(return_value={"access_token": "mock-token"}) ), ), patch( - "homeassistant.components.ring.async_setup", return_value=mock_coro(True) + "homeassistant.components.ring.async_setup", return_value=True ) as mock_setup, patch( - "homeassistant.components.ring.async_setup_entry", return_value=mock_coro(True), + "homeassistant.components.ring.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], diff --git a/tests/components/rmvtransport/test_sensor.py b/tests/components/rmvtransport/test_sensor.py index 58c9192de7d..ece4142f8c7 100644 --- a/tests/components/rmvtransport/test_sensor.py +++ b/tests/components/rmvtransport/test_sensor.py @@ -1,10 +1,10 @@ """The tests for the rmvtransport platform.""" import datetime -from asynctest import patch - from homeassistant.setup import async_setup_component +from tests.async_mock import patch + VALID_CONFIG_MINIMAL = { "sensor": {"platform": "rmvtransport", "next_departure": [{"station": "3000010"}]} } diff --git a/tests/components/roku/test_config_flow.py b/tests/components/roku/test_config_flow.py index e6c725e9959..f59b36b6f30 100644 --- a/tests/components/roku/test_config_flow.py +++ b/tests/components/roku/test_config_flow.py @@ -1,7 +1,6 @@ """Test the Roku config flow.""" from socket import gaierror as SocketGIAError -from asynctest import patch from requests.exceptions import RequestException from requests_mock import Mocker from roku import RokuException @@ -22,6 +21,7 @@ from homeassistant.data_entry_flow import ( from homeassistant.helpers.typing import HomeAssistantType from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.components.roku import ( HOST, SSDP_LOCATION, diff --git a/tests/components/roku/test_init.py b/tests/components/roku/test_init.py index c597ebef6f7..fcbe9aa4b7d 100644 --- a/tests/components/roku/test_init.py +++ b/tests/components/roku/test_init.py @@ -1,7 +1,6 @@ """Tests for the Roku integration.""" from socket import gaierror as SocketGIAError -from asynctest import patch from requests.exceptions import RequestException from requests_mock import Mocker from roku import RokuException @@ -14,6 +13,7 @@ from homeassistant.config_entries import ( ) from homeassistant.helpers.typing import HomeAssistantType +from tests.async_mock import patch from tests.components.roku import setup_integration diff --git a/tests/components/roku/test_media_player.py b/tests/components/roku/test_media_player.py index 4965207a5b8..3b11844450e 100644 --- a/tests/components/roku/test_media_player.py +++ b/tests/components/roku/test_media_player.py @@ -1,7 +1,6 @@ """Tests for the Roku Media Player platform.""" from datetime import timedelta -from asynctest import PropertyMock, patch from requests.exceptions import ( ConnectionError as RequestsConnectionError, ReadTimeout as RequestsReadTimeout, @@ -46,6 +45,7 @@ from homeassistant.const import ( from homeassistant.helpers.typing import HomeAssistantType from homeassistant.util import dt as dt_util +from tests.async_mock import PropertyMock, patch from tests.common import async_fire_time_changed from tests.components.roku import UPNP_SERIAL, setup_integration diff --git a/tests/components/roomba/test_config_flow.py b/tests/components/roomba/test_config_flow.py index c9a0d8fde17..0941586f788 100644 --- a/tests/components/roomba/test_config_flow.py +++ b/tests/components/roomba/test_config_flow.py @@ -1,5 +1,4 @@ """Test the iRobot Roomba config flow.""" -from asynctest import MagicMock, PropertyMock, patch from roomba import RoombaConnectionError from homeassistant import config_entries, data_entry_flow, setup @@ -12,6 +11,7 @@ from homeassistant.components.roomba.const import ( ) from homeassistant.const import CONF_HOST, CONF_PASSWORD +from tests.async_mock import MagicMock, PropertyMock, patch from tests.common import MockConfigEntry VALID_CONFIG = {CONF_HOST: "1.2.3.4", CONF_BLID: "blid", CONF_PASSWORD: "password"} diff --git a/tests/components/samsungtv/test_config_flow.py b/tests/components/samsungtv/test_config_flow.py index 4e5a02588b1..2673ee56559 100644 --- a/tests/components/samsungtv/test_config_flow.py +++ b/tests/components/samsungtv/test_config_flow.py @@ -1,7 +1,4 @@ """Tests for Samsung TV config flow.""" -from unittest.mock import Mock, PropertyMock, call, patch - -from asynctest import mock import pytest from samsungctl.exceptions import AccessDenied, UnhandledResponse from samsungtvws.exceptions import ConnectionFailure @@ -21,6 +18,8 @@ from homeassistant.components.ssdp import ( ) from homeassistant.const import CONF_HOST, CONF_ID, CONF_METHOD, CONF_NAME, CONF_TOKEN +from tests.async_mock import DEFAULT as DEFAULT_MOCK, Mock, PropertyMock, call, patch + MOCK_USER_DATA = {CONF_HOST: "fake_host", CONF_NAME: "fake_name"} MOCK_SSDP_DATA = { ATTR_SSDP_LOCATION: "https://fake_host:12345/test", @@ -70,11 +69,11 @@ def remote_fixture(): ) as remote_class, patch( "homeassistant.components.samsungtv.config_flow.socket" ) as socket_class: - remote = mock.Mock() - remote.__enter__ = mock.Mock() - remote.__exit__ = mock.Mock() + remote = Mock() + remote.__enter__ = Mock() + remote.__exit__ = Mock() remote_class.return_value = remote - socket = mock.Mock() + socket = Mock() socket_class.return_value = socket socket_class.gethostbyname.return_value = "FAKE_IP_ADDRESS" yield remote @@ -88,12 +87,12 @@ def remotews_fixture(): ) as remotews_class, patch( "homeassistant.components.samsungtv.config_flow.socket" ) as socket_class: - remotews = mock.Mock() - remotews.__enter__ = mock.Mock() - remotews.__exit__ = mock.Mock() + remotews = Mock() + remotews.__enter__ = Mock() + remotews.__exit__ = Mock() remotews_class.return_value = remotews remotews_class().__enter__().token = "FAKE_TOKEN" - socket = mock.Mock() + socket = Mock() socket_class.return_value = socket socket_class.gethostbyname.return_value = "FAKE_IP_ADDRESS" yield remotews @@ -486,7 +485,7 @@ async def test_autodetect_websocket_ssl(hass, remote, remotews): "homeassistant.components.samsungtv.bridge.Remote", side_effect=OSError("Boom"), ), patch( "homeassistant.components.samsungtv.bridge.SamsungTVWS", - side_effect=[WebSocketProtocolException("Boom"), mock.DEFAULT], + side_effect=[WebSocketProtocolException("Boom"), DEFAULT_MOCK], ) as remotews: enter = Mock() type(enter).token = PropertyMock(return_value="123456789") diff --git a/tests/components/samsungtv/test_init.py b/tests/components/samsungtv/test_init.py index 232a04416d5..5ef47cb3106 100644 --- a/tests/components/samsungtv/test_init.py +++ b/tests/components/samsungtv/test_init.py @@ -1,6 +1,4 @@ """Tests for the Samsung TV Integration.""" -from asynctest import mock -from asynctest.mock import call, patch import pytest from homeassistant.components.media_player.const import DOMAIN, SUPPORT_TURN_ON @@ -18,6 +16,8 @@ from homeassistant.const import ( ) from homeassistant.setup import async_setup_component +from tests.async_mock import Mock, call, patch + ENTITY_ID = f"{DOMAIN}.fake_name" MOCK_CONFIG = { SAMSUNGTV_DOMAIN: [ @@ -49,9 +49,9 @@ def remote_fixture(): ) as socket1, patch( "homeassistant.components.samsungtv.socket" ) as socket2: - remote = mock.Mock() - remote.__enter__ = mock.Mock() - remote.__exit__ = mock.Mock() + remote = Mock() + remote.__enter__ = Mock() + remote.__exit__ = Mock() remote_class.return_value = remote socket1.gethostbyname.return_value = "FAKE_IP_ADDRESS" socket2.gethostbyname.return_value = "FAKE_IP_ADDRESS" diff --git a/tests/components/samsungtv/test_media_player.py b/tests/components/samsungtv/test_media_player.py index c549e57a06e..15ac13c64d5 100644 --- a/tests/components/samsungtv/test_media_player.py +++ b/tests/components/samsungtv/test_media_player.py @@ -3,8 +3,6 @@ import asyncio from datetime import timedelta import logging -from asynctest import mock -from asynctest.mock import call, patch import pytest from samsungctl import exceptions from samsungtvws.exceptions import ConnectionFailure @@ -54,6 +52,7 @@ from homeassistant.const import ( from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util +from tests.async_mock import DEFAULT as DEFAULT_MOCK, Mock, PropertyMock, call, patch from tests.common import MockConfigEntry, async_fire_time_changed ENTITY_ID = f"{DOMAIN}.fake" @@ -120,9 +119,9 @@ def remote_fixture(): ) as socket1, patch( "homeassistant.components.samsungtv.socket" ) as socket2: - remote = mock.Mock() - remote.__enter__ = mock.Mock() - remote.__exit__ = mock.Mock() + remote = Mock() + remote.__enter__ = Mock() + remote.__exit__ = Mock() remote_class.return_value = remote socket1.gethostbyname.return_value = "FAKE_IP_ADDRESS" socket2.gethostbyname.return_value = "FAKE_IP_ADDRESS" @@ -139,9 +138,9 @@ def remotews_fixture(): ) as socket1, patch( "homeassistant.components.samsungtv.socket" ) as socket2: - remote = mock.Mock() - remote.__enter__ = mock.Mock() - remote.__exit__ = mock.Mock() + remote = Mock() + remote.__enter__ = Mock() + remote.__exit__ = Mock() remote_class.return_value = remote remote_class().__enter__().token = "FAKE_TOKEN" socket1.gethostbyname.return_value = "FAKE_IP_ADDRESS" @@ -185,11 +184,11 @@ async def test_setup_without_turnon(hass, remote): async def test_setup_websocket(hass, remotews, mock_now): """Test setup of platform.""" with patch("homeassistant.components.samsungtv.bridge.SamsungTVWS") as remote_class: - enter = mock.Mock() - type(enter).token = mock.PropertyMock(return_value="987654321") - remote = mock.Mock() - remote.__enter__ = mock.Mock(return_value=enter) - remote.__exit__ = mock.Mock() + enter = Mock() + type(enter).token = PropertyMock(return_value="987654321") + remote = Mock() + remote.__enter__ = Mock(return_value=enter) + remote.__exit__ = Mock() remote_class.return_value = remote await setup_samsungtv(hass, MOCK_CONFIGWS) @@ -247,7 +246,7 @@ async def test_update_off(hass, remote, mock_now): with patch( "homeassistant.components.samsungtv.bridge.Remote", - side_effect=[OSError("Boom"), mock.DEFAULT], + side_effect=[OSError("Boom"), DEFAULT_MOCK], ): next_update = mock_now + timedelta(minutes=5) @@ -283,7 +282,7 @@ async def test_update_connection_failure(hass, remotews, mock_now): """Testing update tv connection failure exception.""" with patch( "homeassistant.components.samsungtv.bridge.Remote", - side_effect=[OSError("Boom"), mock.DEFAULT], + side_effect=[OSError("Boom"), DEFAULT_MOCK], ): await setup_samsungtv(hass, MOCK_CONFIGWS) @@ -309,7 +308,7 @@ async def test_update_unhandled_response(hass, remote, mock_now): with patch( "homeassistant.components.samsungtv.bridge.Remote", - side_effect=[exceptions.UnhandledResponse("Boom"), mock.DEFAULT], + side_effect=[exceptions.UnhandledResponse("Boom"), DEFAULT_MOCK], ): next_update = mock_now + timedelta(minutes=5) @@ -339,7 +338,7 @@ async def test_send_key(hass, remote): async def test_send_key_broken_pipe(hass, remote): """Testing broken pipe Exception.""" await setup_samsungtv(hass, MOCK_CONFIG) - remote.control = mock.Mock(side_effect=BrokenPipeError("Boom")) + remote.control = Mock(side_effect=BrokenPipeError("Boom")) assert await hass.services.async_call( DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID}, True ) @@ -350,8 +349,8 @@ async def test_send_key_broken_pipe(hass, remote): async def test_send_key_connection_closed_retry_succeed(hass, remote): """Test retry on connection closed.""" await setup_samsungtv(hass, MOCK_CONFIG) - remote.control = mock.Mock( - side_effect=[exceptions.ConnectionClosed("Boom"), mock.DEFAULT, mock.DEFAULT] + remote.control = Mock( + side_effect=[exceptions.ConnectionClosed("Boom"), DEFAULT_MOCK, DEFAULT_MOCK] ) assert await hass.services.async_call( DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID}, True @@ -371,7 +370,7 @@ async def test_send_key_connection_closed_retry_succeed(hass, remote): async def test_send_key_unhandled_response(hass, remote): """Testing unhandled response exception.""" await setup_samsungtv(hass, MOCK_CONFIG) - remote.control = mock.Mock(side_effect=exceptions.UnhandledResponse("Boom")) + remote.control = Mock(side_effect=exceptions.UnhandledResponse("Boom")) assert await hass.services.async_call( DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID}, True ) @@ -382,7 +381,7 @@ async def test_send_key_unhandled_response(hass, remote): async def test_send_key_websocketexception(hass, remote): """Testing unhandled response exception.""" await setup_samsungtv(hass, MOCK_CONFIG) - remote.control = mock.Mock(side_effect=WebSocketException("Boom")) + remote.control = Mock(side_effect=WebSocketException("Boom")) assert await hass.services.async_call( DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID}, True ) @@ -393,7 +392,7 @@ async def test_send_key_websocketexception(hass, remote): async def test_send_key_os_error(hass, remote): """Testing broken pipe Exception.""" await setup_samsungtv(hass, MOCK_CONFIG) - remote.control = mock.Mock(side_effect=OSError("Boom")) + remote.control = Mock(side_effect=OSError("Boom")) assert await hass.services.async_call( DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID}, True ) @@ -467,7 +466,7 @@ async def test_turn_off_websocket(hass, remotews): """Test for turn_off.""" with patch( "homeassistant.components.samsungtv.bridge.Remote", - side_effect=[OSError("Boom"), mock.DEFAULT], + side_effect=[OSError("Boom"), DEFAULT_MOCK], ): await setup_samsungtv(hass, MOCK_CONFIGWS) assert await hass.services.async_call( @@ -493,7 +492,7 @@ async def test_turn_off_os_error(hass, remote, caplog): """Test for turn_off with OSError.""" caplog.set_level(logging.DEBUG) await setup_samsungtv(hass, MOCK_CONFIG) - remote.close = mock.Mock(side_effect=OSError("BOOM")) + remote.close = Mock(side_effect=OSError("BOOM")) assert await hass.services.async_call( DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: ENTITY_ID}, True ) diff --git a/tests/components/sense/test_config_flow.py b/tests/components/sense/test_config_flow.py index fdce335b7cf..5a38090b5c9 100644 --- a/tests/components/sense/test_config_flow.py +++ b/tests/components/sense/test_config_flow.py @@ -1,10 +1,11 @@ """Test the Sense config flow.""" -from asynctest import patch from sense_energy import SenseAPITimeoutException, SenseAuthenticationException from homeassistant import config_entries, setup from homeassistant.components.sense.const import DOMAIN +from tests.async_mock import patch + async def test_form(hass): """Test we get the form.""" diff --git a/tests/components/sentry/test_config_flow.py b/tests/components/sentry/test_config_flow.py index 22c4367ddf2..25353751f91 100644 --- a/tests/components/sentry/test_config_flow.py +++ b/tests/components/sentry/test_config_flow.py @@ -1,11 +1,10 @@ """Test the sentry config flow.""" -from asynctest import patch from sentry_sdk.utils import BadDsn from homeassistant import config_entries, setup from homeassistant.components.sentry.const import DOMAIN -from tests.common import mock_coro +from tests.async_mock import patch async def test_form(hass): @@ -19,12 +18,11 @@ async def test_form(hass): with patch( "homeassistant.components.sentry.config_flow.validate_input", - return_value=mock_coro({"title": "Sentry"}), + return_value={"title": "Sentry"}, ), patch( - "homeassistant.components.sentry.async_setup", return_value=mock_coro(True) + "homeassistant.components.sentry.async_setup", return_value=True ) as mock_setup, patch( - "homeassistant.components.sentry.async_setup_entry", - return_value=mock_coro(True), + "homeassistant.components.sentry.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {"dsn": "http://public@sentry.local/1"}, diff --git a/tests/components/shell_command/test_init.py b/tests/components/shell_command/test_init.py index 156741d8c9b..8743ab27bd7 100644 --- a/tests/components/shell_command/test_init.py +++ b/tests/components/shell_command/test_init.py @@ -5,15 +5,13 @@ import tempfile from typing import Tuple import unittest -from asynctest import Mock, patch - from homeassistant.components import shell_command from homeassistant.setup import setup_component +from tests.async_mock import Mock, patch from tests.common import get_test_home_assistant -@asyncio.coroutine def mock_process_creator(error: bool = False) -> asyncio.coroutine: """Mock a coroutine that creates a process when yielded.""" diff --git a/tests/components/shopping_list/conftest.py b/tests/components/shopping_list/conftest.py index f63363e2f63..8307a6845b1 100644 --- a/tests/components/shopping_list/conftest.py +++ b/tests/components/shopping_list/conftest.py @@ -1,9 +1,9 @@ """Shopping list test helpers.""" -from asynctest import patch import pytest from homeassistant.components.shopping_list import intent as sl_intent +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/simplisafe/test_config_flow.py b/tests/components/simplisafe/test_config_flow.py index f53636fc440..5dc0fd5698b 100644 --- a/tests/components/simplisafe/test_config_flow.py +++ b/tests/components/simplisafe/test_config_flow.py @@ -2,7 +2,6 @@ import json from unittest.mock import MagicMock, PropertyMock, mock_open -from asynctest import patch from simplipy.errors import SimplipyError from homeassistant import data_entry_flow @@ -10,6 +9,7 @@ from homeassistant.components.simplisafe import DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_CODE, CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/smartthings/conftest.py b/tests/components/smartthings/conftest.py index e05917c17d8..a47b06ee637 100644 --- a/tests/components/smartthings/conftest.py +++ b/tests/components/smartthings/conftest.py @@ -2,7 +2,6 @@ import secrets from uuid import uuid4 -from asynctest import Mock, patch from pysmartthings import ( CLASSIFICATION_AUTOMATION, AppEntity, @@ -42,6 +41,7 @@ from homeassistant.config_entries import CONN_CLASS_CLOUD_PUSH, SOURCE_USER, Con from homeassistant.const import CONF_ACCESS_TOKEN, CONF_WEBHOOK_ID from homeassistant.setup import async_setup_component +from tests.async_mock import Mock, patch from tests.common import MockConfigEntry COMPONENT_PREFIX = "homeassistant.components.smartthings." diff --git a/tests/components/smartthings/test_config_flow.py b/tests/components/smartthings/test_config_flow.py index 81dbab917a3..ca964b9d1da 100644 --- a/tests/components/smartthings/test_config_flow.py +++ b/tests/components/smartthings/test_config_flow.py @@ -2,7 +2,6 @@ from uuid import uuid4 from aiohttp import ClientResponseError -from asynctest import Mock, patch from pysmartthings import APIResponseError from pysmartthings.installedapp import format_install_url @@ -23,7 +22,8 @@ from homeassistant.const import ( HTTP_UNAUTHORIZED, ) -from tests.common import MockConfigEntry, mock_coro +from tests.async_mock import AsyncMock, Mock, patch +from tests.common import MockConfigEntry async def test_import_shows_user_step(hass): @@ -342,8 +342,8 @@ async def test_entry_created_with_cloudhook( installed_app_id = str(uuid4()) refresh_token = str(uuid4()) smartthings_mock.apps.return_value = [] - smartthings_mock.create_app.return_value = (app, app_oauth_client) - smartthings_mock.locations.return_value = [location] + smartthings_mock.create_app = AsyncMock(return_value=(app, app_oauth_client)) + smartthings_mock.locations = AsyncMock(return_value=[location]) request = Mock() request.installed_app_id = installed_app_id request.auth_token = token @@ -351,11 +351,11 @@ async def test_entry_created_with_cloudhook( request.refresh_token = refresh_token with patch.object( - hass.components.cloud, "async_active_subscription", return_value=True + hass.components.cloud, "async_active_subscription", Mock(return_value=True) ), patch.object( hass.components.cloud, "async_create_cloudhook", - return_value=mock_coro("http://cloud.test"), + AsyncMock(return_value="http://cloud.test"), ) as mock_create_cloudhook: await smartapp.setup_smartapp_endpoint(hass) diff --git a/tests/components/smartthings/test_init.py b/tests/components/smartthings/test_init.py index 78142ae3fc4..0fdbf5c255a 100644 --- a/tests/components/smartthings/test_init.py +++ b/tests/components/smartthings/test_init.py @@ -2,7 +2,6 @@ from uuid import uuid4 from aiohttp import ClientConnectionError, ClientResponseError -from asynctest import Mock, patch from pysmartthings import InstalledAppStatus, OAuthToken import pytest @@ -22,6 +21,7 @@ from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.setup import async_setup_component +from tests.async_mock import Mock, patch from tests.common import MockConfigEntry diff --git a/tests/components/smartthings/test_smartapp.py b/tests/components/smartthings/test_smartapp.py index efc4844cef2..458e5f8ce27 100644 --- a/tests/components/smartthings/test_smartapp.py +++ b/tests/components/smartthings/test_smartapp.py @@ -1,7 +1,6 @@ """Tests for the smartapp module.""" from uuid import uuid4 -from asynctest import CoroutineMock, Mock, patch from pysmartthings import AppEntity, Capability from homeassistant.components.smartthings import smartapp @@ -11,6 +10,7 @@ from homeassistant.components.smartthings.const import ( DOMAIN, ) +from tests.async_mock import AsyncMock, Mock, patch from tests.common import MockConfigEntry @@ -76,11 +76,11 @@ async def test_smartapp_uninstall(hass, config_entry): async def test_smartapp_webhook(hass): """Test the smartapp webhook calls the manager.""" manager = Mock() - manager.handle_request = CoroutineMock(return_value={}) + manager.handle_request = AsyncMock(return_value={}) hass.data[DOMAIN][DATA_MANAGER] = manager request = Mock() request.headers = [] - request.json = CoroutineMock(return_value={}) + request.json = AsyncMock(return_value={}) result = await smartapp.smartapp_webhook(hass, "", request) assert result.body == b"{}" diff --git a/tests/components/smhi/test_config_flow.py b/tests/components/smhi/test_config_flow.py index 6065c323b91..56a0745c1b3 100644 --- a/tests/components/smhi/test_config_flow.py +++ b/tests/components/smhi/test_config_flow.py @@ -1,11 +1,10 @@ """Tests for SMHI config flow.""" -from asynctest import Mock, patch from smhi.smhi_lib import Smhi as SmhiApi, SmhiForecastException from homeassistant.components.smhi import config_flow from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE -from tests.common import mock_coro +from tests.async_mock import Mock, patch # pylint: disable=protected-access @@ -14,7 +13,7 @@ async def test_homeassistant_location_exists() -> None: hass = Mock() flow = config_flow.SmhiFlowHandler() flow.hass = hass - with patch.object(flow, "_check_location", return_value=mock_coro(True)): + with patch.object(flow, "_check_location", return_value=True): # Test exists hass.config.location_name = "Home" hass.config.latitude = 17.8419 @@ -99,7 +98,7 @@ async def test_flow_with_home_location(hass) -> None: flow = config_flow.SmhiFlowHandler() flow.hass = hass - with patch.object(flow, "_check_location", return_value=mock_coro(True)): + with patch.object(flow, "_check_location", return_value=True): hass.config.location_name = "Home" hass.config.latitude = 17.8419 hass.config.longitude = 59.3262 @@ -121,9 +120,9 @@ async def test_flow_show_form() -> None: # Test show form when Home Assistant config exists and # home is already configured, then new config is allowed with patch.object( - flow, "_show_config_form", return_value=mock_coro() + flow, "_show_config_form", return_value=None ) as config_form, patch.object( - flow, "_homeassistant_location_exists", return_value=mock_coro(True) + flow, "_homeassistant_location_exists", return_value=True ), patch.object( config_flow, "smhi_locations", @@ -135,9 +134,9 @@ async def test_flow_show_form() -> None: # Test show form when Home Assistant config not and # home is not configured with patch.object( - flow, "_show_config_form", return_value=mock_coro() + flow, "_show_config_form", return_value=None ) as config_form, patch.object( - flow, "_homeassistant_location_exists", return_value=mock_coro(False) + flow, "_homeassistant_location_exists", return_value=False ), patch.object( config_flow, "smhi_locations", @@ -160,7 +159,7 @@ async def test_flow_show_form_name_exists() -> None: # Test show form when Home Assistant config exists and # home is already configured, then new config is allowed with patch.object( - flow, "_show_config_form", return_value=mock_coro() + flow, "_show_config_form", return_value=None ) as config_form, patch.object( flow, "_name_in_configuration_exists", return_value=True ), patch.object( @@ -168,7 +167,7 @@ async def test_flow_show_form_name_exists() -> None: "smhi_locations", return_value={"test": "something", "name_exist": "config"}, ), patch.object( - flow, "_check_location", return_value=mock_coro(True) + flow, "_check_location", return_value=True ): await flow.async_step_user(user_input=test_data) @@ -190,17 +189,17 @@ async def test_flow_entry_created_from_user_input() -> None: # Test that entry created when user_input name not exists with patch.object( - flow, "_show_config_form", return_value=mock_coro() + flow, "_show_config_form", return_value=None ) as config_form, patch.object( flow, "_name_in_configuration_exists", return_value=False ), patch.object( - flow, "_homeassistant_location_exists", return_value=mock_coro(False) + flow, "_homeassistant_location_exists", return_value=False ), patch.object( config_flow, "smhi_locations", return_value={"test": "something", "name_exist": "config"}, ), patch.object( - flow, "_check_location", return_value=mock_coro(True) + flow, "_check_location", return_value=True ): result = await flow.async_step_user(user_input=test_data) @@ -223,20 +222,18 @@ async def test_flow_entry_created_user_input_faulty() -> None: test_data = {"name": "home", CONF_LONGITUDE: "0", CONF_LATITUDE: "0"} # Test that entry created when user_input name not exists - with patch.object( - flow, "_check_location", return_value=mock_coro(True) - ), patch.object( - flow, "_show_config_form", return_value=mock_coro() + with patch.object(flow, "_check_location", return_value=True), patch.object( + flow, "_show_config_form", return_value=None ) as config_form, patch.object( flow, "_name_in_configuration_exists", return_value=False ), patch.object( - flow, "_homeassistant_location_exists", return_value=mock_coro(False) + flow, "_homeassistant_location_exists", return_value=False ), patch.object( config_flow, "smhi_locations", return_value={"test": "something", "name_exist": "config"}, ), patch.object( - flow, "_check_location", return_value=mock_coro(False) + flow, "_check_location", return_value=False ): await flow.async_step_user(user_input=test_data) @@ -253,7 +250,7 @@ async def test_check_location_correct() -> None: with patch.object( config_flow.aiohttp_client, "async_get_clientsession" - ), patch.object(SmhiApi, "async_get_forecast", return_value=mock_coro()): + ), patch.object(SmhiApi, "async_get_forecast", return_value=None): assert await flow._check_location("58", "17") is True diff --git a/tests/components/smhi/test_weather.py b/tests/components/smhi/test_weather.py index 357b670a38a..6f5fdfd2333 100644 --- a/tests/components/smhi/test_weather.py +++ b/tests/components/smhi/test_weather.py @@ -3,7 +3,7 @@ import asyncio from datetime import datetime import logging -from asynctest import Mock, patch +from smhi.smhi_lib import APIURL_TEMPLATE, SmhiForecastException from homeassistant.components.smhi import weather as weather_smhi from homeassistant.components.smhi.const import ATTR_SMHI_CLOUDINESS @@ -25,6 +25,7 @@ from homeassistant.components.weather import ( from homeassistant.const import TEMP_CELSIUS from homeassistant.core import HomeAssistant +from tests.async_mock import AsyncMock, Mock, patch from tests.common import MockConfigEntry, load_fixture _LOGGER = logging.getLogger(__name__) @@ -40,8 +41,6 @@ async def test_setup_hass(hass: HomeAssistant, aioclient_mock) -> None: "async_forward_entry_setup". The actual result are tested with the entity state rather than "per function" unity tests """ - from smhi.smhi_lib import APIURL_TEMPLATE - uri = APIURL_TEMPLATE.format(TEST_CONFIG["longitude"], TEST_CONFIG["latitude"]) api_response = load_fixture("smhi.json") aioclient_mock.get(uri, text=api_response) @@ -150,7 +149,6 @@ def test_properties_unknown_symbol() -> None: # pylint: disable=protected-access async def test_refresh_weather_forecast_exceeds_retries(hass) -> None: """Test the refresh weather forecast function.""" - from smhi.smhi_lib import SmhiForecastException with patch.object( hass.helpers.event, "async_call_later" @@ -192,7 +190,6 @@ async def test_refresh_weather_forecast_timeout(hass) -> None: async def test_refresh_weather_forecast_exception() -> None: """Test any exception.""" - from smhi.smhi_lib import SmhiForecastException hass = Mock() weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022") @@ -200,17 +197,9 @@ async def test_refresh_weather_forecast_exception() -> None: with patch.object( hass.helpers.event, "async_call_later" - ) as call_later, patch.object(weather_smhi, "async_timeout"), patch.object( - weather_smhi.SmhiWeather, "retry_update" - ), patch.object( - weather_smhi.SmhiWeather, - "get_weather_forecast", - side_effect=SmhiForecastException(), + ) as call_later, patch.object( + weather, "get_weather_forecast", side_effect=SmhiForecastException(), ): - - hass.async_add_job = Mock() - call_later = hass.helpers.event.async_call_later - await weather.async_update() assert len(call_later.mock_calls) == 1 # Assert we are going to wait RETRY_TIMEOUT seconds @@ -223,8 +212,8 @@ async def test_retry_update(): weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022") weather.hass = hass - with patch.object(weather_smhi.SmhiWeather, "async_update") as update: - await weather.retry_update() + with patch.object(weather, "async_update", AsyncMock()) as update: + await weather.retry_update(None) assert len(update.mock_calls) == 1 diff --git a/tests/components/solarlog/test_config_flow.py b/tests/components/solarlog/test_config_flow.py index 4d8c11074db..1474b8e13e7 100644 --- a/tests/components/solarlog/test_config_flow.py +++ b/tests/components/solarlog/test_config_flow.py @@ -1,5 +1,4 @@ """Test the solarlog config flow.""" -from asynctest import patch import pytest from homeassistant import config_entries, data_entry_flow, setup @@ -7,7 +6,8 @@ from homeassistant.components.solarlog import config_flow from homeassistant.components.solarlog.const import DEFAULT_HOST, DOMAIN from homeassistant.const import CONF_HOST, CONF_NAME -from tests.common import MockConfigEntry, mock_coro +from tests.async_mock import patch +from tests.common import MockConfigEntry NAME = "Solarlog test 1 2 3" HOST = "http://1.1.1.1" @@ -24,12 +24,11 @@ async def test_form(hass): with patch( "homeassistant.components.solarlog.config_flow.SolarLogConfigFlow._test_connection", - return_value=mock_coro({"title": "solarlog test 1 2 3"}), + return_value={"title": "solarlog test 1 2 3"}, ), patch( - "homeassistant.components.solarlog.async_setup", return_value=mock_coro(True) + "homeassistant.components.solarlog.async_setup", return_value=True ) as mock_setup, patch( - "homeassistant.components.solarlog.async_setup_entry", - return_value=mock_coro(True), + "homeassistant.components.solarlog.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {"host": HOST, "name": NAME} @@ -48,7 +47,7 @@ def mock_controller(): """Mock a successful _host_in_configuration_exists.""" with patch( "homeassistant.components.solarlog.config_flow.SolarLogConfigFlow._test_connection", - side_effect=lambda *_: mock_coro(True), + return_value=True, ): yield diff --git a/tests/components/sonos/conftest.py b/tests/components/sonos/conftest.py index 246d1eb1627..20c1eb10320 100644 --- a/tests/components/sonos/conftest.py +++ b/tests/components/sonos/conftest.py @@ -1,11 +1,11 @@ """Configuration for Sonos tests.""" -from asynctest.mock import Mock, patch as patch import pytest from homeassistant.components.media_player import DOMAIN as MP_DOMAIN from homeassistant.components.sonos import DOMAIN from homeassistant.const import CONF_HOSTS +from tests.async_mock import Mock, patch as patch from tests.common import MockConfigEntry diff --git a/tests/components/soundtouch/test_media_player.py b/tests/components/soundtouch/test_media_player.py index ea580656b24..bc3cc1bc977 100644 --- a/tests/components/soundtouch/test_media_player.py +++ b/tests/components/soundtouch/test_media_player.py @@ -1,7 +1,6 @@ """Test the Soundtouch component.""" from unittest.mock import call -from asynctest import patch from libsoundtouch.device import ( Config, Preset, @@ -28,6 +27,8 @@ from homeassistant.const import STATE_OFF, STATE_PAUSED, STATE_PLAYING from homeassistant.helpers.discovery import async_load_platform from homeassistant.setup import async_setup_component +from tests.async_mock import patch + # pylint: disable=super-init-not-called diff --git a/tests/components/stream/test_init.py b/tests/components/stream/test_init.py index 0661a5a9738..12fa8e8a4d6 100644 --- a/tests/components/stream/test_init.py +++ b/tests/components/stream/test_init.py @@ -14,7 +14,7 @@ from homeassistant.const import CONF_FILENAME from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import async_setup_component -from tests.common import mock_coro +from tests.async_mock import AsyncMock async def test_record_service_invalid_file(hass): @@ -76,7 +76,7 @@ async def test_record_service_lookback(hass): hls_mock = MagicMock() hls_mock.num_segments = 3 hls_mock.target_duration = 2 - hls_mock.recv.return_value = mock_coro() + hls_mock.recv = AsyncMock(return_value=None) stream_mock.return_value.outputs = {"hls": hls_mock} # Call Service diff --git a/tests/components/switcher_kis/conftest.py b/tests/components/switcher_kis/conftest.py index 2b0150cae67..37d61d6ca19 100644 --- a/tests/components/switcher_kis/conftest.py +++ b/tests/components/switcher_kis/conftest.py @@ -4,7 +4,6 @@ from asyncio import Queue from datetime import datetime from typing import Any, Generator, Optional -from asynctest import CoroutineMock, patch from pytest import fixture from .consts import ( @@ -20,6 +19,8 @@ from .consts import ( DUMMY_REMAINING_TIME, ) +from tests.async_mock import AsyncMock, patch + @patch("aioswitcher.devices.SwitcherV2Device") class MockSwitcherV2Device: @@ -100,7 +101,7 @@ def mock_bridge_fixture() -> Generator[None, Any, None]: await queue.put(MockSwitcherV2Device()) return await queue.get() - mock_bridge = CoroutineMock() + mock_bridge = AsyncMock() patchers = [ patch( @@ -163,9 +164,9 @@ def mock_failed_bridge_fixture() -> Generator[None, Any, None]: @fixture(name="mock_api") -def mock_api_fixture() -> Generator[CoroutineMock, Any, None]: +def mock_api_fixture() -> Generator[AsyncMock, Any, None]: """Fixture for mocking aioswitcher.api.SwitcherV2Api.""" - mock_api = CoroutineMock() + mock_api = AsyncMock() patchers = [ patch( diff --git a/tests/components/tado/test_config_flow.py b/tests/components/tado/test_config_flow.py index 0c75eadfb0e..2e42a2bc1fb 100644 --- a/tests/components/tado/test_config_flow.py +++ b/tests/components/tado/test_config_flow.py @@ -1,11 +1,11 @@ """Test the Tado config flow.""" -from asynctest import MagicMock, patch import requests from homeassistant import config_entries, setup from homeassistant.components.tado.const import DOMAIN from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from tests.async_mock import MagicMock, patch from tests.common import MockConfigEntry diff --git a/tests/components/tesla/test_config_flow.py b/tests/components/tesla/test_config_flow.py index 24cdb375fde..a59daee9ac6 100644 --- a/tests/components/tesla/test_config_flow.py +++ b/tests/components/tesla/test_config_flow.py @@ -1,5 +1,4 @@ """Test the Tesla config flow.""" -from asynctest import patch from teslajsonpy import TeslaException from homeassistant import config_entries, data_entry_flow, setup @@ -19,7 +18,8 @@ from homeassistant.const import ( HTTP_NOT_FOUND, ) -from tests.common import MockConfigEntry, mock_coro +from tests.async_mock import patch +from tests.common import MockConfigEntry async def test_form(hass): @@ -33,11 +33,11 @@ async def test_form(hass): with patch( "homeassistant.components.tesla.config_flow.TeslaAPI.connect", - return_value=mock_coro(("test-refresh-token", "test-access-token")), + return_value=("test-refresh-token", "test-access-token"), ), patch( - "homeassistant.components.tesla.async_setup", return_value=mock_coro(True) + "homeassistant.components.tesla.async_setup", return_value=True ) as mock_setup, patch( - "homeassistant.components.tesla.async_setup_entry", return_value=mock_coro(True) + "homeassistant.components.tesla.async_setup_entry", return_value=True ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PASSWORD: "test", CONF_USERNAME: "test@email.com"} @@ -102,7 +102,7 @@ async def test_form_repeat_identifier(hass): ) with patch( "homeassistant.components.tesla.config_flow.TeslaAPI.connect", - return_value=mock_coro(("test-refresh-token", "test-access-token")), + return_value=("test-refresh-token", "test-access-token"), ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], @@ -118,7 +118,7 @@ async def test_import(hass): with patch( "homeassistant.components.tesla.config_flow.TeslaAPI.connect", - return_value=mock_coro(("test-refresh-token", "test-access-token")), + return_value=("test-refresh-token", "test-access-token"), ): result = await hass.config_entries.flow.async_init( DOMAIN, diff --git a/tests/components/tradfri/conftest.py b/tests/components/tradfri/conftest.py index bb1a0e7cc64..891dd1377fe 100644 --- a/tests/components/tradfri/conftest.py +++ b/tests/components/tradfri/conftest.py @@ -1,7 +1,8 @@ """Common tradfri test fixtures.""" -from asynctest import patch import pytest +from tests.async_mock import patch + @pytest.fixture def mock_gateway_info(): diff --git a/tests/components/tradfri/test_config_flow.py b/tests/components/tradfri/test_config_flow.py index 45e18be83d3..43e33706bf6 100644 --- a/tests/components/tradfri/test_config_flow.py +++ b/tests/components/tradfri/test_config_flow.py @@ -1,10 +1,10 @@ """Test the Tradfri config flow.""" -from asynctest import patch import pytest from homeassistant import data_entry_flow from homeassistant.components.tradfri import config_flow +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/tradfri/test_init.py b/tests/components/tradfri/test_init.py index bdb45ee4306..2845137244b 100644 --- a/tests/components/tradfri/test_init.py +++ b/tests/components/tradfri/test_init.py @@ -1,8 +1,7 @@ """Tests for Tradfri setup.""" -from asynctest import patch - from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/uk_transport/test_sensor.py b/tests/components/uk_transport/test_sensor.py index 4979efc22dc..b8eddb9c785 100644 --- a/tests/components/uk_transport/test_sensor.py +++ b/tests/components/uk_transport/test_sensor.py @@ -2,7 +2,6 @@ import re import unittest -from asynctest import patch import requests_mock from homeassistant.components.uk_transport.sensor import ( @@ -20,6 +19,7 @@ from homeassistant.components.uk_transport.sensor import ( from homeassistant.setup import setup_component from homeassistant.util.dt import now +from tests.async_mock import patch from tests.common import get_test_home_assistant, load_fixture BUS_ATCOCODE = "340000368SHE" diff --git a/tests/components/unifi/conftest.py b/tests/components/unifi/conftest.py index 189b80c1932..8ce7cef0345 100644 --- a/tests/components/unifi/conftest.py +++ b/tests/components/unifi/conftest.py @@ -1,7 +1,8 @@ """Fixtures for UniFi methods.""" -from asynctest import patch import pytest +from tests.async_mock import patch + @pytest.fixture(autouse=True) def mock_discovery(): diff --git a/tests/components/unifi/test_config_flow.py b/tests/components/unifi/test_config_flow.py index bad191e1600..ae738ba8a64 100644 --- a/tests/components/unifi/test_config_flow.py +++ b/tests/components/unifi/test_config_flow.py @@ -1,6 +1,5 @@ """Test UniFi config flow.""" import aiounifi -from asynctest import patch from homeassistant import data_entry_flow from homeassistant.components.unifi.const import ( @@ -27,6 +26,7 @@ from homeassistant.const import ( from .test_controller import setup_unifi_integration +from tests.async_mock import patch from tests.common import MockConfigEntry CLIENTS = [{"mac": "00:00:00:00:00:01"}] diff --git a/tests/components/unifi/test_controller.py b/tests/components/unifi/test_controller.py index 824ffbffc41..9bf956e8063 100644 --- a/tests/components/unifi/test_controller.py +++ b/tests/components/unifi/test_controller.py @@ -4,7 +4,6 @@ from copy import deepcopy from datetime import timedelta import aiounifi -from asynctest import patch import pytest from homeassistant.components.device_tracker import DOMAIN as TRACKER_DOMAIN @@ -35,6 +34,7 @@ from homeassistant.const import ( ) from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import MockConfigEntry CONTROLLER_HOST = { diff --git a/tests/components/unifi/test_device_tracker.py b/tests/components/unifi/test_device_tracker.py index df7c49a1bf7..5f40f098d39 100644 --- a/tests/components/unifi/test_device_tracker.py +++ b/tests/components/unifi/test_device_tracker.py @@ -4,7 +4,6 @@ from datetime import timedelta from aiounifi.controller import MESSAGE_CLIENT_REMOVED, SIGNAL_CONNECTION_STATE from aiounifi.websocket import SIGNAL_DATA, STATE_DISCONNECTED, STATE_RUNNING -from asynctest import patch from homeassistant import config_entries from homeassistant.components.device_tracker import DOMAIN as TRACKER_DOMAIN @@ -24,6 +23,8 @@ import homeassistant.util.dt as dt_util from .test_controller import ENTRY_CONFIG, setup_unifi_integration +from tests.async_mock import patch + CLIENT_1 = { "essid": "ssid", "hostname": "client_1", diff --git a/tests/components/unifi/test_init.py b/tests/components/unifi/test_init.py index db6c1e30748..80e3e07fa17 100644 --- a/tests/components/unifi/test_init.py +++ b/tests/components/unifi/test_init.py @@ -7,6 +7,7 @@ from homeassistant.setup import async_setup_component from .test_controller import setup_unifi_integration +from tests.async_mock import AsyncMock from tests.common import MockConfigEntry, mock_coro @@ -25,7 +26,7 @@ async def test_successful_config_entry(hass): async def test_controller_fail_setup(hass): """Test that a failed setup still stores controller.""" with patch("homeassistant.components.unifi.UniFiController") as mock_controller: - mock_controller.return_value.async_setup.return_value = mock_coro(False) + mock_controller.return_value.async_setup = AsyncMock(return_value=False) await setup_unifi_integration(hass) assert hass.data[UNIFI_DOMAIN] == {} @@ -55,7 +56,7 @@ async def test_controller_no_mac(hass): "homeassistant.helpers.device_registry.async_get_registry", return_value=mock_coro(mock_registry), ): - mock_controller.return_value.async_setup.return_value = mock_coro(True) + mock_controller.return_value.async_setup = AsyncMock(return_value=True) mock_controller.return_value.mac = None assert await unifi.async_setup_entry(hass, entry) is True diff --git a/tests/components/unifi_direct/test_device_tracker.py b/tests/components/unifi_direct/test_device_tracker.py index 692231d4cad..be58efa415a 100644 --- a/tests/components/unifi_direct/test_device_tracker.py +++ b/tests/components/unifi_direct/test_device_tracker.py @@ -2,7 +2,6 @@ from datetime import timedelta import os -from asynctest import mock, patch import pytest import voluptuous as vol @@ -23,6 +22,7 @@ from homeassistant.components.unifi_direct.device_tracker import ( from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PLATFORM, CONF_USERNAME from homeassistant.setup import async_setup_component +from tests.async_mock import MagicMock, call, patch from tests.common import assert_setup_component, load_fixture, mock_component scanner_path = "homeassistant.components.unifi_direct.device_tracker.UnifiDeviceScanner" @@ -38,7 +38,7 @@ def setup_comp(hass): os.remove(yaml_devices) -@patch(scanner_path, return_value=mock.MagicMock(spec=UnifiDeviceScanner)) +@patch(scanner_path, return_value=MagicMock(spec=UnifiDeviceScanner)) async def test_get_scanner(unifi_mock, hass): """Test creating an Unifi direct scanner with a password.""" conf_dict = { @@ -57,7 +57,7 @@ async def test_get_scanner(unifi_mock, hass): assert await async_setup_component(hass, DOMAIN, conf_dict) conf_dict[DOMAIN][CONF_PORT] = 22 - assert unifi_mock.call_args == mock.call(conf_dict[DOMAIN]) + assert unifi_mock.call_args == call(conf_dict[DOMAIN]) @patch("pexpect.pxssh.pxssh") diff --git a/tests/components/updater/test_init.py b/tests/components/updater/test_init.py index e583f4e0114..95875828c71 100644 --- a/tests/components/updater/test_init.py +++ b/tests/components/updater/test_init.py @@ -1,14 +1,12 @@ """The tests for the Updater component.""" -from unittest.mock import Mock - -from asynctest import patch import pytest from homeassistant.components import updater from homeassistant.helpers.update_coordinator import UpdateFailed from homeassistant.setup import async_setup_component -from tests.common import MockDependency, mock_component, mock_coro +from tests.async_mock import patch +from tests.common import MockDependency, mock_component NEW_VERSION = "10000.0" MOCK_VERSION = "10.0" @@ -75,7 +73,7 @@ async def test_same_version_shows_entity_false( ): """Test if sensor is false if no new version is available.""" mock_get_uuid.return_value = MOCK_HUUID - mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, "")) + mock_get_newest_version.return_value = (MOCK_VERSION, "") assert await async_setup_component(hass, updater.DOMAIN, {updater.DOMAIN: {}}) @@ -92,7 +90,7 @@ async def test_same_version_shows_entity_false( async def test_disable_reporting(hass, mock_get_uuid, mock_get_newest_version): """Test we do not gather analytics when disable reporting is active.""" mock_get_uuid.return_value = MOCK_HUUID - mock_get_newest_version.return_value = mock_coro((MOCK_VERSION, "")) + mock_get_newest_version.return_value = (MOCK_VERSION, "") assert await async_setup_component( hass, updater.DOMAIN, {updater.DOMAIN: {"reporting": False}} @@ -123,7 +121,7 @@ async def test_get_newest_version_analytics_when_huuid(hass, aioclient_mock): with patch( "homeassistant.helpers.system_info.async_get_system_info", - Mock(return_value=mock_coro({"fake": "bla"})), + return_value={"fake": "bla"}, ): res = await updater.get_newest_version(hass, MOCK_HUUID, False) assert res == (MOCK_RESPONSE["version"], MOCK_RESPONSE["release-notes"]) @@ -135,7 +133,7 @@ async def test_error_fetching_new_version_bad_json(hass, aioclient_mock): with patch( "homeassistant.helpers.system_info.async_get_system_info", - Mock(return_value=mock_coro({"fake": "bla"})), + return_value={"fake": "bla"}, ), pytest.raises(UpdateFailed): await updater.get_newest_version(hass, MOCK_HUUID, False) @@ -152,7 +150,7 @@ async def test_error_fetching_new_version_invalid_response(hass, aioclient_mock) with patch( "homeassistant.helpers.system_info.async_get_system_info", - Mock(return_value=mock_coro({"fake": "bla"})), + return_value={"fake": "bla"}, ), pytest.raises(UpdateFailed): await updater.get_newest_version(hass, MOCK_HUUID, False) diff --git a/tests/components/upnp/test_init.py b/tests/components/upnp/test_init.py index 464ccc90675..7c43c24cdc3 100644 --- a/tests/components/upnp/test_init.py +++ b/tests/components/upnp/test_init.py @@ -2,13 +2,12 @@ from ipaddress import IPv4Address -from asynctest import patch - from homeassistant.components import upnp from homeassistant.components.upnp.device import Device from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.setup import async_setup_component +from tests.async_mock import patch from tests.common import MockConfigEntry, mock_coro @@ -86,8 +85,8 @@ async def test_async_setup_entry_default(hass): {"udn": udn, "ssdp_description": "http://192.168.1.1/desc.xml"} ] - create_device.return_value = mock_coro(return_value=mock_device) - async_discover.return_value = mock_coro(return_value=discovery_infos) + create_device.return_value = mock_device + async_discover.return_value = discovery_infos assert await upnp.async_setup_entry(hass, entry) is True @@ -128,8 +127,8 @@ async def test_async_setup_entry_port_mapping(hass): {"udn": udn, "ssdp_description": "http://192.168.1.1/desc.xml"} ] - create_device.return_value = mock_coro(return_value=mock_device) - async_discover.return_value = mock_coro(return_value=discovery_infos) + create_device.return_value = mock_device + async_discover.return_value = discovery_infos assert await upnp.async_setup_entry(hass, entry) is True diff --git a/tests/components/vera/test_init.py b/tests/components/vera/test_init.py index a6208726451..f1e13a5f208 100644 --- a/tests/components/vera/test_init.py +++ b/tests/components/vera/test_init.py @@ -1,5 +1,4 @@ """Vera tests.""" -from asynctest import MagicMock import pyvera as pv from requests.exceptions import RequestException @@ -9,6 +8,7 @@ from homeassistant.core import HomeAssistant from .common import ComponentFactory, new_simple_controller_config +from tests.async_mock import MagicMock from tests.common import MockConfigEntry diff --git a/tests/components/vilfo/test_config_flow.py b/tests/components/vilfo/test_config_flow.py index 9176a9a1970..d9e8a2ffd24 100644 --- a/tests/components/vilfo/test_config_flow.py +++ b/tests/components/vilfo/test_config_flow.py @@ -1,12 +1,11 @@ """Test the Vilfo Router config flow.""" -from asynctest.mock import patch import vilfo from homeassistant import config_entries, data_entry_flow, setup from homeassistant.components.vilfo.const import DOMAIN from homeassistant.const import CONF_ACCESS_TOKEN, CONF_HOST, CONF_ID, CONF_MAC -from tests.common import mock_coro +from tests.async_mock import patch async def test_form(hass): @@ -22,7 +21,7 @@ async def test_form(hass): with patch("vilfo.Client.ping", return_value=None), patch( "vilfo.Client.get_board_information", return_value=None ), patch("vilfo.Client.resolve_mac_address", return_value=mock_mac), patch( - "homeassistant.components.vilfo.async_setup", return_value=mock_coro(True) + "homeassistant.components.vilfo.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.vilfo.async_setup_entry" ) as mock_setup_entry: diff --git a/tests/components/vizio/conftest.py b/tests/components/vizio/conftest.py index e630f201e12..f7448a71c31 100644 --- a/tests/components/vizio/conftest.py +++ b/tests/components/vizio/conftest.py @@ -1,5 +1,4 @@ """Configure py.test.""" -from asynctest import patch import pytest from pyvizio.const import DEVICE_CLASS_SPEAKER, MAX_VOLUME @@ -21,6 +20,8 @@ from .const import ( MockStartPairingResponse, ) +from tests.async_mock import patch + class MockInput: """Mock Vizio device input.""" diff --git a/tests/components/vizio/test_media_player.py b/tests/components/vizio/test_media_player.py index 1f6abf10563..aaf802af7ec 100644 --- a/tests/components/vizio/test_media_player.py +++ b/tests/components/vizio/test_media_player.py @@ -5,7 +5,6 @@ import logging from typing import Any, Dict, List, Optional from unittest.mock import call -from asynctest import patch import pytest from pytest import raises from pyvizio.api.apps import AppConfig @@ -74,6 +73,7 @@ from .const import ( VOLUME_STEP, ) +from tests.async_mock import patch from tests.common import MockConfigEntry, async_fire_time_changed _LOGGER = logging.getLogger(__name__) diff --git a/tests/components/webostv/test_media_player.py b/tests/components/webostv/test_media_player.py index 9ba35a510dd..cc889eca064 100644 --- a/tests/components/webostv/test_media_player.py +++ b/tests/components/webostv/test_media_player.py @@ -27,7 +27,7 @@ from homeassistant.setup import async_setup_component if sys.version_info >= (3, 8, 0): from unittest.mock import patch else: - from asynctest import patch + from tests.async_mock import patch NAME = "fake" diff --git a/tests/components/websocket_api/test_http.py b/tests/components/websocket_api/test_http.py index 9082337ccc8..e76cbe0dbdc 100644 --- a/tests/components/websocket_api/test_http.py +++ b/tests/components/websocket_api/test_http.py @@ -2,12 +2,12 @@ from datetime import timedelta from aiohttp import WSMsgType -from asynctest import patch import pytest from homeassistant.components.websocket_api import const, http from homeassistant.util.dt import utcnow +from tests.async_mock import patch from tests.common import async_fire_time_changed diff --git a/tests/components/withings/test_common.py b/tests/components/withings/test_common.py index 65ff65ebbd8..f0f3a160332 100644 --- a/tests/components/withings/test_common.py +++ b/tests/components/withings/test_common.py @@ -2,7 +2,6 @@ from datetime import timedelta from unittest.mock import patch -from asynctest import MagicMock import pytest from withings_api import WithingsApi from withings_api.common import TimeoutException, UnauthorizedException @@ -14,6 +13,8 @@ from homeassistant.components.withings.common import ( from homeassistant.exceptions import PlatformNotReady from homeassistant.util import dt +from tests.async_mock import MagicMock + @pytest.fixture(name="withings_api") def withings_api_fixture() -> WithingsApi: diff --git a/tests/components/withings/test_init.py b/tests/components/withings/test_init.py index f6f36ba8eff..5bb3e8534c3 100644 --- a/tests/components/withings/test_init.py +++ b/tests/components/withings/test_init.py @@ -2,7 +2,6 @@ import re import time -from asynctest import MagicMock import requests_mock import voluptuous as vol from withings_api import AbstractWithingsApi @@ -32,6 +31,8 @@ from .common import ( setup_hass, ) +from tests.async_mock import MagicMock + def config_schema_validate(withings_config) -> None: """Assert a schema config succeeds.""" diff --git a/tests/components/wled/test_light.py b/tests/components/wled/test_light.py index 0009677cf18..f2cc5514a2e 100644 --- a/tests/components/wled/test_light.py +++ b/tests/components/wled/test_light.py @@ -1,6 +1,5 @@ """Tests for the WLED light platform.""" import aiohttp -from asynctest.mock import patch from homeassistant.components.light import ( ATTR_BRIGHTNESS, @@ -32,6 +31,7 @@ from homeassistant.const import ( ) from homeassistant.core import HomeAssistant +from tests.async_mock import patch from tests.components.wled import init_integration from tests.test_util.aiohttp import AiohttpClientMocker diff --git a/tests/components/wled/test_sensor.py b/tests/components/wled/test_sensor.py index d77bd99b97c..66fedfdd274 100644 --- a/tests/components/wled/test_sensor.py +++ b/tests/components/wled/test_sensor.py @@ -1,7 +1,6 @@ """Tests for the WLED sensor platform.""" from datetime import datetime -from asynctest import patch import pytest from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN @@ -21,6 +20,7 @@ from homeassistant.const import ( from homeassistant.core import HomeAssistant from homeassistant.util import dt as dt_util +from tests.async_mock import patch from tests.components.wled import init_integration from tests.test_util.aiohttp import AiohttpClientMocker diff --git a/tests/components/wled/test_switch.py b/tests/components/wled/test_switch.py index d140953b948..7d411984cff 100644 --- a/tests/components/wled/test_switch.py +++ b/tests/components/wled/test_switch.py @@ -1,6 +1,5 @@ """Tests for the WLED switch platform.""" import aiohttp -from asynctest.mock import patch from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.components.wled.const import ( @@ -20,6 +19,7 @@ from homeassistant.const import ( ) from homeassistant.core import HomeAssistant +from tests.async_mock import patch from tests.components.wled import init_integration from tests.test_util.aiohttp import AiohttpClientMocker diff --git a/tests/components/wwlln/test_config_flow.py b/tests/components/wwlln/test_config_flow.py index e9e32ae75e1..b5d34f542e3 100644 --- a/tests/components/wwlln/test_config_flow.py +++ b/tests/components/wwlln/test_config_flow.py @@ -1,6 +1,4 @@ """Define tests for the WWLLN config flow.""" -from asynctest import patch - from homeassistant import data_entry_flow from homeassistant.components.wwlln import ( CONF_WINDOW, @@ -11,6 +9,7 @@ from homeassistant.components.wwlln import ( from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_RADIUS +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/xiaomi/test_device_tracker.py b/tests/components/xiaomi/test_device_tracker.py index 5d65aee7616..1760b3274a4 100644 --- a/tests/components/xiaomi/test_device_tracker.py +++ b/tests/components/xiaomi/test_device_tracker.py @@ -1,7 +1,6 @@ """The tests for the Xiaomi router device tracker platform.""" import logging -from asynctest import mock, patch import requests from homeassistant.components.device_tracker import DOMAIN @@ -9,6 +8,8 @@ import homeassistant.components.xiaomi.device_tracker as xiaomi from homeassistant.components.xiaomi.device_tracker import get_scanner from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PLATFORM, CONF_USERNAME +from tests.async_mock import MagicMock, call, patch + _LOGGER = logging.getLogger(__name__) INVALID_USERNAME = "bob" @@ -144,7 +145,7 @@ def mocked_requests(*args, **kwargs): @patch( "homeassistant.components.xiaomi.device_tracker.XiaomiDeviceScanner", - return_value=mock.MagicMock(), + return_value=MagicMock(), ) async def test_config(xiaomi_mock, hass): """Testing minimal configuration.""" @@ -159,7 +160,7 @@ async def test_config(xiaomi_mock, hass): } xiaomi.get_scanner(hass, config) assert xiaomi_mock.call_count == 1 - assert xiaomi_mock.call_args == mock.call(config[DOMAIN]) + assert xiaomi_mock.call_args == call(config[DOMAIN]) call_arg = xiaomi_mock.call_args[0][0] assert call_arg["username"] == "admin" assert call_arg["password"] == "passwordTest" @@ -169,7 +170,7 @@ async def test_config(xiaomi_mock, hass): @patch( "homeassistant.components.xiaomi.device_tracker.XiaomiDeviceScanner", - return_value=mock.MagicMock(), + return_value=MagicMock(), ) async def test_config_full(xiaomi_mock, hass): """Testing full configuration.""" @@ -185,7 +186,7 @@ async def test_config_full(xiaomi_mock, hass): } xiaomi.get_scanner(hass, config) assert xiaomi_mock.call_count == 1 - assert xiaomi_mock.call_args == mock.call(config[DOMAIN]) + assert xiaomi_mock.call_args == call(config[DOMAIN]) call_arg = xiaomi_mock.call_args[0][0] assert call_arg["username"] == "alternativeAdminName" assert call_arg["password"] == "passwordTest" diff --git a/tests/components/xiaomi_miio/test_config_flow.py b/tests/components/xiaomi_miio/test_config_flow.py index 2c1411ded68..023deb93c81 100644 --- a/tests/components/xiaomi_miio/test_config_flow.py +++ b/tests/components/xiaomi_miio/test_config_flow.py @@ -1,13 +1,14 @@ """Test the Xiaomi Miio config flow.""" from unittest.mock import Mock -from asynctest import patch from miio import DeviceException from homeassistant import config_entries from homeassistant.components.xiaomi_miio import config_flow, const from homeassistant.const import CONF_HOST, CONF_NAME, CONF_TOKEN +from tests.async_mock import patch + TEST_HOST = "1.2.3.4" TEST_TOKEN = "12345678901234567890123456789012" TEST_NAME = "Test_Gateway" diff --git a/tests/components/zeroconf/test_init.py b/tests/components/zeroconf/test_init.py index 27824623d23..a8e22e74bc4 100644 --- a/tests/components/zeroconf/test_init.py +++ b/tests/components/zeroconf/test_init.py @@ -1,5 +1,4 @@ """Test Zeroconf component setup process.""" -from asynctest import patch import pytest from zeroconf import ServiceInfo, ServiceStateChange @@ -7,6 +6,8 @@ from homeassistant.components import zeroconf from homeassistant.generated import zeroconf as zc_gen from homeassistant.setup import async_setup_component +from tests.async_mock import patch + NON_UTF8_VALUE = b"ABCDEF\x8a" NON_ASCII_KEY = b"non-ascii-key\x8a" PROPERTIES = { diff --git a/tests/components/zha/common.py b/tests/components/zha/common.py index 2542037a2bf..9b139317825 100644 --- a/tests/components/zha/common.py +++ b/tests/components/zha/common.py @@ -2,7 +2,6 @@ import time from unittest.mock import Mock -from asynctest import CoroutineMock from zigpy.device import Device as zigpy_dev from zigpy.endpoint import Endpoint as zigpy_ep import zigpy.profiles.zha @@ -15,6 +14,8 @@ import zigpy.zdo.types import homeassistant.components.zha.core.const as zha_const from homeassistant.util import slugify +from tests.async_mock import AsyncMock + class FakeEndpoint: """Fake endpoint for moking zigpy.""" @@ -32,7 +33,7 @@ class FakeEndpoint: self.model = model self.profile_id = zigpy.profiles.zha.PROFILE_ID self.device_type = None - self.request = CoroutineMock() + self.request = AsyncMock() def add_input_cluster(self, cluster_id): """Add an input cluster.""" @@ -64,16 +65,16 @@ FakeEndpoint.add_to_group = zigpy_ep.add_to_group def patch_cluster(cluster): """Patch a cluster for testing.""" - cluster.bind = CoroutineMock(return_value=[0]) - cluster.configure_reporting = CoroutineMock(return_value=[0]) + cluster.bind = AsyncMock(return_value=[0]) + cluster.configure_reporting = AsyncMock(return_value=[0]) cluster.deserialize = Mock() cluster.handle_cluster_request = Mock() - cluster.read_attributes = CoroutineMock(return_value=[{}, {}]) + cluster.read_attributes = AsyncMock(return_value=[{}, {}]) cluster.read_attributes_raw = Mock() - cluster.unbind = CoroutineMock(return_value=[0]) - cluster.write_attributes = CoroutineMock(return_value=[0]) + cluster.unbind = AsyncMock(return_value=[0]) + cluster.write_attributes = AsyncMock(return_value=[0]) if cluster.cluster_id == 4: - cluster.add = CoroutineMock(return_value=[0]) + cluster.add = AsyncMock(return_value=[0]) class FakeDevice: @@ -96,7 +97,7 @@ class FakeDevice: self.manufacturer = manufacturer self.model = model self.node_desc = zigpy.zdo.types.NodeDescriptor() - self.remove_from_group = CoroutineMock() + self.remove_from_group = AsyncMock() if node_desc is None: node_desc = b"\x02@\x807\x10\x7fd\x00\x00*d\x00\x00" self.node_desc = zigpy.zdo.types.NodeDescriptor.deserialize(node_desc)[0] diff --git a/tests/components/zha/conftest.py b/tests/components/zha/conftest.py index b83db53533c..e737f990163 100644 --- a/tests/components/zha/conftest.py +++ b/tests/components/zha/conftest.py @@ -1,7 +1,6 @@ """Test configuration for the ZHA component.""" from unittest import mock -import asynctest import pytest import zigpy from zigpy.application import ControllerApplication @@ -15,6 +14,7 @@ from homeassistant.setup import async_setup_component from .common import FakeDevice, FakeEndpoint, get_zha_gateway +import tests.async_mock from tests.common import MockConfigEntry FIXTURE_GRP_ID = 0x1001 @@ -25,8 +25,8 @@ FIXTURE_GRP_NAME = "fixture group" def zigpy_app_controller(): """Zigpy ApplicationController fixture.""" app = mock.MagicMock(spec_set=ControllerApplication) - app.startup = asynctest.CoroutineMock() - app.shutdown = asynctest.CoroutineMock() + app.startup = tests.async_mock.AsyncMock() + app.shutdown = tests.async_mock.AsyncMock() groups = zigpy.group.Groups(app) groups.add_group(FIXTURE_GRP_ID, FIXTURE_GRP_NAME, suppress_event=True) app.configure_mock(groups=groups) @@ -41,7 +41,7 @@ def zigpy_app_controller(): def zigpy_radio(): """Zigpy radio mock.""" radio = mock.MagicMock() - radio.connect = asynctest.CoroutineMock() + radio.connect = tests.async_mock.AsyncMock() return radio @@ -93,8 +93,8 @@ def channel(): ch.name = name ch.generic_id = f"channel_0x{cluster_id:04x}" ch.id = f"{endpoint_id}:0x{cluster_id:04x}" - ch.async_configure = asynctest.CoroutineMock() - ch.async_initialize = asynctest.CoroutineMock() + ch.async_configure = tests.async_mock.AsyncMock() + ch.async_initialize = tests.async_mock.AsyncMock() return ch return channel diff --git a/tests/components/zha/test_channels.py b/tests/components/zha/test_channels.py index 1196cdc3b40..471e44f8409 100644 --- a/tests/components/zha/test_channels.py +++ b/tests/components/zha/test_channels.py @@ -2,7 +2,6 @@ import asyncio from unittest import mock -import asynctest import pytest import zigpy.types as t import zigpy.zcl.clusters @@ -14,6 +13,8 @@ import homeassistant.components.zha.core.registries as registries from .common import get_zha_gateway, make_zcl_header +import tests.async_mock + @pytest.fixture def ieee(): @@ -379,12 +380,12 @@ async def test_ep_channels_configure(channel): ch_1 = channel(zha_const.CHANNEL_ON_OFF, 6) ch_2 = channel(zha_const.CHANNEL_LEVEL, 8) ch_3 = channel(zha_const.CHANNEL_COLOR, 768) - ch_3.async_configure = asynctest.CoroutineMock(side_effect=asyncio.TimeoutError) - ch_3.async_initialize = asynctest.CoroutineMock(side_effect=asyncio.TimeoutError) + ch_3.async_configure = tests.async_mock.AsyncMock(side_effect=asyncio.TimeoutError) + ch_3.async_initialize = tests.async_mock.AsyncMock(side_effect=asyncio.TimeoutError) ch_4 = channel(zha_const.CHANNEL_ON_OFF, 6) ch_5 = channel(zha_const.CHANNEL_LEVEL, 8) - ch_5.async_configure = asynctest.CoroutineMock(side_effect=asyncio.TimeoutError) - ch_5.async_initialize = asynctest.CoroutineMock(side_effect=asyncio.TimeoutError) + ch_5.async_configure = tests.async_mock.AsyncMock(side_effect=asyncio.TimeoutError) + ch_5.async_initialize = tests.async_mock.AsyncMock(side_effect=asyncio.TimeoutError) channels = mock.MagicMock(spec_set=zha_channels.Channels) type(channels).semaphore = mock.PropertyMock(return_value=asyncio.Semaphore(3)) @@ -420,8 +421,8 @@ async def test_poll_control_configure(poll_control_ch): async def test_poll_control_checkin_response(poll_control_ch): """Test poll control channel checkin response.""" - rsp_mock = asynctest.CoroutineMock() - set_interval_mock = asynctest.CoroutineMock() + rsp_mock = tests.async_mock.AsyncMock() + set_interval_mock = tests.async_mock.AsyncMock() cluster = poll_control_ch.cluster patch_1 = mock.patch.object(cluster, "checkin_response", rsp_mock) patch_2 = mock.patch.object(cluster, "set_long_poll_interval", set_interval_mock) @@ -442,7 +443,7 @@ async def test_poll_control_checkin_response(poll_control_ch): async def test_poll_control_cluster_command(hass, poll_control_device): """Test poll control channel response to cluster command.""" - checkin_mock = asynctest.CoroutineMock() + checkin_mock = tests.async_mock.AsyncMock() poll_control_ch = poll_control_device.channels.pools[0].all_channels["1:0x0020"] cluster = poll_control_ch.cluster diff --git a/tests/components/zha/test_config_flow.py b/tests/components/zha/test_config_flow.py index 7e0b89f8d70..91d2ef75aa5 100644 --- a/tests/components/zha/test_config_flow.py +++ b/tests/components/zha/test_config_flow.py @@ -1,12 +1,11 @@ """Tests for ZHA config flow.""" from unittest import mock -import asynctest - from homeassistant.components.zha import config_flow from homeassistant.components.zha.core.const import CONTROLLER, DOMAIN, ZHA_GW_RADIO import homeassistant.components.zha.core.registries +import tests.async_mock from tests.common import MockConfigEntry @@ -15,7 +14,7 @@ async def test_user_flow(hass): flow = config_flow.ZhaFlowHandler() flow.hass = hass - with asynctest.patch( + with tests.async_mock.patch( "homeassistant.components.zha.config_flow.check_zigpy_connection", return_value=False, ): @@ -25,7 +24,7 @@ async def test_user_flow(hass): assert result["errors"] == {"base": "cannot_connect"} - with asynctest.patch( + with tests.async_mock.patch( "homeassistant.components.zha.config_flow.check_zigpy_connection", return_value=True, ): @@ -79,18 +78,18 @@ async def test_import_flow_existing_config_entry(hass): async def test_check_zigpy_connection(): """Test config flow validator.""" - mock_radio = asynctest.MagicMock() - mock_radio.connect = asynctest.CoroutineMock() - radio_cls = asynctest.MagicMock(return_value=mock_radio) + mock_radio = tests.async_mock.MagicMock() + mock_radio.connect = tests.async_mock.AsyncMock() + radio_cls = tests.async_mock.MagicMock(return_value=mock_radio) - bad_radio = asynctest.MagicMock() - bad_radio.connect = asynctest.CoroutineMock(side_effect=Exception) - bad_radio_cls = asynctest.MagicMock(return_value=bad_radio) + bad_radio = tests.async_mock.MagicMock() + bad_radio.connect = tests.async_mock.AsyncMock(side_effect=Exception) + bad_radio_cls = tests.async_mock.MagicMock(return_value=bad_radio) - mock_ctrl = asynctest.MagicMock() - mock_ctrl.startup = asynctest.CoroutineMock() - mock_ctrl.shutdown = asynctest.CoroutineMock() - ctrl_cls = asynctest.MagicMock(return_value=mock_ctrl) + mock_ctrl = tests.async_mock.MagicMock() + mock_ctrl.startup = tests.async_mock.AsyncMock() + mock_ctrl.shutdown = tests.async_mock.AsyncMock() + ctrl_cls = tests.async_mock.MagicMock(return_value=mock_ctrl) new_radios = { mock.sentinel.radio: {ZHA_GW_RADIO: radio_cls, CONTROLLER: ctrl_cls}, mock.sentinel.bad_radio: {ZHA_GW_RADIO: bad_radio_cls, CONTROLLER: ctrl_cls}, diff --git a/tests/components/zha/test_cover.py b/tests/components/zha/test_cover.py index 188ddf69a23..b4c72fd82d4 100644 --- a/tests/components/zha/test_cover.py +++ b/tests/components/zha/test_cover.py @@ -1,7 +1,4 @@ """Test zha cover.""" -from unittest.mock import MagicMock, call, patch - -import asynctest import pytest import zigpy.types import zigpy.zcl.clusters.closures as closures @@ -17,6 +14,7 @@ from .common import ( send_attributes_report, ) +from tests.async_mock import MagicMock, call, patch from tests.common import mock_coro @@ -34,7 +32,7 @@ def zigpy_cover_device(zigpy_device_mock): return zigpy_device_mock(endpoints) -@asynctest.patch( +@patch( "homeassistant.components.zha.core.channels.closures.WindowCovering.async_initialize" ) async def test_cover(m1, hass, zha_device_joined_restored, zigpy_cover_device): diff --git a/tests/components/zha/test_device.py b/tests/components/zha/test_device.py index c92f574825d..6e528299911 100644 --- a/tests/components/zha/test_device.py +++ b/tests/components/zha/test_device.py @@ -3,7 +3,6 @@ from datetime import timedelta import time from unittest import mock -import asynctest import pytest import zigpy.zcl.clusters.general as general @@ -13,6 +12,7 @@ import homeassistant.util.dt as dt_util from .common import async_enable_traffic, make_zcl_header +from tests.async_mock import patch from tests.common import async_fire_time_changed @@ -90,7 +90,7 @@ def _send_time_changed(hass, seconds): async_fire_time_changed(hass, now) -@asynctest.patch( +@patch( "homeassistant.components.zha.core.channels.general.BasicChannel.async_initialize", new=mock.MagicMock(), ) @@ -144,7 +144,7 @@ async def test_check_available_success( assert zha_device.available is True -@asynctest.patch( +@patch( "homeassistant.components.zha.core.channels.general.BasicChannel.async_initialize", new=mock.MagicMock(), ) @@ -187,7 +187,7 @@ async def test_check_available_unsuccessful( assert zha_device.available is False -@asynctest.patch( +@patch( "homeassistant.components.zha.core.channels.general.BasicChannel.async_initialize", new=mock.MagicMock(), ) diff --git a/tests/components/zha/test_discover.py b/tests/components/zha/test_discover.py index 8b1ce502a78..4b95040dd08 100644 --- a/tests/components/zha/test_discover.py +++ b/tests/components/zha/test_discover.py @@ -3,7 +3,6 @@ import re from unittest import mock -import asynctest import pytest import zigpy.quirks import zigpy.types @@ -30,6 +29,8 @@ import homeassistant.helpers.entity_registry from .common import get_zha_gateway from .zha_devices_list import DEVICES +from tests.async_mock import AsyncMock, patch + NO_TAIL_ID = re.compile("_\\d$") @@ -51,11 +52,9 @@ def channels_mock(zha_device_mock): return _mock -@asynctest.patch( +@patch( "zigpy.zcl.clusters.general.Identify.request", - new=asynctest.CoroutineMock( - return_value=[mock.sentinel.data, zcl_f.Status.SUCCESS] - ), + new=AsyncMock(return_value=[mock.sentinel.data, zcl_f.Status.SUCCESS]), ) @pytest.mark.parametrize("device", DEVICES) async def test_devices( diff --git a/tests/components/zha/test_light.py b/tests/components/zha/test_light.py index 03c29283c20..915ace7c7f2 100644 --- a/tests/components/zha/test_light.py +++ b/tests/components/zha/test_light.py @@ -2,7 +2,6 @@ from datetime import timedelta from unittest.mock import MagicMock, call, sentinel -from asynctest import CoroutineMock, patch import pytest import zigpy.profiles.zha as zha import zigpy.types @@ -24,6 +23,7 @@ from .common import ( send_attributes_report, ) +from tests.async_mock import AsyncMock, patch from tests.common import async_fire_time_changed ON = 1 @@ -206,19 +206,19 @@ async def test_light_refresh(hass, zigpy_device_mock, zha_device_joined_restored @patch( "zigpy.zcl.clusters.lighting.Color.request", - new=CoroutineMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]), + new=AsyncMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]), ) @patch( "zigpy.zcl.clusters.general.Identify.request", - new=CoroutineMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]), + new=AsyncMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]), ) @patch( "zigpy.zcl.clusters.general.LevelControl.request", - new=CoroutineMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]), + new=AsyncMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]), ) @patch( "zigpy.zcl.clusters.general.OnOff.request", - new=CoroutineMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]), + new=AsyncMock(return_value=[sentinel.data, zcl_f.Status.SUCCESS]), ) @pytest.mark.parametrize( "device, reporting", diff --git a/tests/components/zone/test_init.py b/tests/components/zone/test_init.py index bf92a6aa12a..994bd5e6dda 100644 --- a/tests/components/zone/test_init.py +++ b/tests/components/zone/test_init.py @@ -1,5 +1,4 @@ """Test zone component.""" -from asynctest import patch import pytest from homeassistant import setup @@ -16,6 +15,7 @@ from homeassistant.core import Context from homeassistant.exceptions import Unauthorized from homeassistant.helpers import entity_registry +from tests.async_mock import patch from tests.common import MockConfigEntry diff --git a/tests/components/zwave/test_init.py b/tests/components/zwave/test_init.py index e14162d5788..b71758469d0 100644 --- a/tests/components/zwave/test_init.py +++ b/tests/components/zwave/test_init.py @@ -23,12 +23,8 @@ from homeassistant.helpers.device_registry import async_get_registry as get_dev_ from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.setup import setup_component -from tests.common import ( - async_fire_time_changed, - get_test_home_assistant, - mock_coro, - mock_registry, -) +from tests.async_mock import AsyncMock +from tests.common import async_fire_time_changed, get_test_home_assistant, mock_registry from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue @@ -873,7 +869,7 @@ class TestZWaveDeviceEntityValues(unittest.TestCase): @patch.object(zwave, "discovery") def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" - discovery.async_load_platform.return_value = mock_coro() + discovery.async_load_platform = AsyncMock(return_value=None) mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() @@ -935,7 +931,7 @@ class TestZWaveDeviceEntityValues(unittest.TestCase): @patch.object(zwave, "discovery") def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" - discovery.async_load_platform.return_value = mock_coro() + discovery.async_load_platform = AsyncMock(return_value=None) mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() @@ -1003,7 +999,7 @@ class TestZWaveDeviceEntityValues(unittest.TestCase): @patch.object(zwave, "discovery") def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" - discovery.async_load_platform.return_value = mock_coro() + discovery.async_load_platform = AsyncMock(return_value=None) mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() diff --git a/tests/conftest.py b/tests/conftest.py index ccc16c8ef82..c7885c6125e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -2,7 +2,6 @@ import functools import logging -from asynctest import patch import pytest import requests_mock as _requests_mock @@ -19,6 +18,8 @@ from homeassistant.exceptions import ServiceNotFound from homeassistant.setup import async_setup_component from homeassistant.util import location +from tests.async_mock import patch + pytest.register_assert_rewrite("tests.common") from tests.common import ( # noqa: E402, isort:skip diff --git a/tests/helpers/test_area_registry.py b/tests/helpers/test_area_registry.py index 87e4b4c4d03..f6a75fe3c30 100644 --- a/tests/helpers/test_area_registry.py +++ b/tests/helpers/test_area_registry.py @@ -1,12 +1,12 @@ """Tests for the Area Registry.""" import asyncio -import asynctest import pytest from homeassistant.core import callback from homeassistant.helpers import area_registry +import tests.async_mock from tests.common import flush_store, mock_area_registry @@ -166,7 +166,7 @@ async def test_loading_area_from_storage(hass, hass_storage): async def test_loading_race_condition(hass): """Test only one storage load called when concurrent loading occurred .""" - with asynctest.patch( + with tests.async_mock.patch( "homeassistant.helpers.area_registry.AreaRegistry.async_load" ) as mock_load: results = await asyncio.gather( diff --git a/tests/helpers/test_config_entry_flow.py b/tests/helpers/test_config_entry_flow.py index 868ff082ec3..1331cf615d1 100644 --- a/tests/helpers/test_config_entry_flow.py +++ b/tests/helpers/test_config_entry_flow.py @@ -1,10 +1,10 @@ """Tests for the Config Entry Flow helper.""" -from asynctest import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow, setup from homeassistant.helpers import config_entry_flow +from tests.async_mock import Mock, patch from tests.common import ( MockConfigEntry, MockModule, diff --git a/tests/helpers/test_debounce.py b/tests/helpers/test_debounce.py index d51eb22c90d..d84b6fd7da7 100644 --- a/tests/helpers/test_debounce.py +++ b/tests/helpers/test_debounce.py @@ -1,8 +1,8 @@ """Tests for debounce.""" -from asynctest import CoroutineMock - from homeassistant.helpers import debounce +from tests.async_mock import AsyncMock + async def test_immediate_works(hass): """Test immediate works.""" @@ -12,7 +12,7 @@ async def test_immediate_works(hass): None, cooldown=0.01, immediate=True, - function=CoroutineMock(side_effect=lambda: calls.append(None)), + function=AsyncMock(side_effect=lambda: calls.append(None)), ) # Call when nothing happening @@ -57,7 +57,7 @@ async def test_not_immediate_works(hass): None, cooldown=0.01, immediate=False, - function=CoroutineMock(side_effect=lambda: calls.append(None)), + function=AsyncMock(side_effect=lambda: calls.append(None)), ) # Call when nothing happening diff --git a/tests/helpers/test_device_registry.py b/tests/helpers/test_device_registry.py index d5f762fc701..f81d20ecd66 100644 --- a/tests/helpers/test_device_registry.py +++ b/tests/helpers/test_device_registry.py @@ -2,12 +2,12 @@ import asyncio from unittest.mock import patch -import asynctest import pytest from homeassistant.core import callback from homeassistant.helpers import device_registry +import tests.async_mock from tests.common import flush_store, mock_device_registry @@ -474,7 +474,7 @@ async def test_update_remove_config_entries(hass, registry, update_events): async def test_loading_race_condition(hass): """Test only one storage load called when concurrent loading occurred .""" - with asynctest.patch( + with tests.async_mock.patch( "homeassistant.helpers.device_registry.DeviceRegistry.async_load" ) as mock_load: results = await asyncio.gather( diff --git a/tests/helpers/test_entity_component.py b/tests/helpers/test_entity_component.py index 1c5224d89c3..625f21d9d9f 100644 --- a/tests/helpers/test_entity_component.py +++ b/tests/helpers/test_entity_component.py @@ -3,9 +3,7 @@ from collections import OrderedDict from datetime import timedelta import logging -from unittest.mock import Mock, patch -import asynctest import pytest import voluptuous as vol @@ -17,13 +15,13 @@ from homeassistant.helpers.entity_component import EntityComponent from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util +from tests.async_mock import AsyncMock, Mock, patch from tests.common import ( MockConfigEntry, MockEntity, MockModule, MockPlatform, async_fire_time_changed, - mock_coro, mock_entity_platform, mock_integration, ) @@ -82,13 +80,8 @@ async def test_setup_recovers_when_setup_raises(hass): assert platform2_setup.called -@asynctest.patch( - "homeassistant.helpers.entity_component.EntityComponent.async_setup_platform", - return_value=mock_coro(), -) -@asynctest.patch( - "homeassistant.setup.async_setup_component", return_value=mock_coro(True) -) +@patch("homeassistant.helpers.entity_component.EntityComponent.async_setup_platform",) +@patch("homeassistant.setup.async_setup_component", return_value=True) async def test_setup_does_discovery(mock_setup_component, mock_setup, hass): """Test setup for discovery.""" component = EntityComponent(_LOGGER, DOMAIN, hass) @@ -105,7 +98,7 @@ async def test_setup_does_discovery(mock_setup_component, mock_setup, hass): assert ("platform_test", {}, {"msg": "discovery_info"}) == mock_setup.call_args[0] -@asynctest.patch("homeassistant.helpers.entity_platform.async_track_time_interval") +@patch("homeassistant.helpers.entity_platform.async_track_time_interval") async def test_set_scan_interval_via_config(mock_track, hass): """Test the setting of the scan interval via configuration.""" @@ -295,7 +288,7 @@ async def test_setup_dependencies_platform(hass): async def test_setup_entry(hass): """Test setup entry calls async_setup_entry on platform.""" - mock_setup_entry = Mock(return_value=mock_coro(True)) + mock_setup_entry = AsyncMock(return_value=True) mock_entity_platform( hass, "test_domain.entry_domain", @@ -326,7 +319,7 @@ async def test_setup_entry_platform_not_exist(hass): async def test_setup_entry_fails_duplicate(hass): """Test we don't allow setting up a config entry twice.""" - mock_setup_entry = Mock(return_value=mock_coro(True)) + mock_setup_entry = AsyncMock(return_value=True) mock_entity_platform( hass, "test_domain.entry_domain", @@ -344,7 +337,7 @@ async def test_setup_entry_fails_duplicate(hass): async def test_unload_entry_resets_platform(hass): """Test unloading an entry removes all entities.""" - mock_setup_entry = Mock(return_value=mock_coro(True)) + mock_setup_entry = AsyncMock(return_value=True) mock_entity_platform( hass, "test_domain.entry_domain", @@ -380,7 +373,7 @@ async def test_update_entity(hass): component = EntityComponent(_LOGGER, DOMAIN, hass) entity = MockEntity() entity.async_write_ha_state = Mock() - entity.async_update_ha_state = Mock(return_value=mock_coro()) + entity.async_update_ha_state = AsyncMock(return_value=None) await component.async_add_entities([entity]) # Called as part of async_add_entities diff --git a/tests/helpers/test_entity_platform.py b/tests/helpers/test_entity_platform.py index df247d82d5c..3f03dfece11 100644 --- a/tests/helpers/test_entity_platform.py +++ b/tests/helpers/test_entity_platform.py @@ -2,9 +2,7 @@ import asyncio from datetime import timedelta import logging -from unittest.mock import MagicMock, Mock, patch -import asynctest import pytest from homeassistant.const import UNIT_PERCENTAGE @@ -18,6 +16,7 @@ from homeassistant.helpers.entity_component import ( ) import homeassistant.util.dt as dt_util +from tests.async_mock import Mock, patch from tests.common import ( MockConfigEntry, MockEntity, @@ -136,7 +135,7 @@ async def test_update_state_adds_entities_with_update_before_add_false(hass): assert not ent.update.called -@asynctest.patch("homeassistant.helpers.entity_platform.async_track_time_interval") +@patch("homeassistant.helpers.entity_platform.async_track_time_interval") async def test_set_scan_interval_via_platform(mock_track, hass): """Test the setting of the scan interval via platform.""" @@ -183,7 +182,7 @@ async def test_platform_warn_slow_setup(hass): component = EntityComponent(_LOGGER, DOMAIN, hass) - with patch.object(hass.loop, "call_later", MagicMock()) as mock_call: + with patch.object(hass.loop, "call_later") as mock_call: await component.async_setup({DOMAIN: {"platform": "platform"}}) assert mock_call.called diff --git a/tests/helpers/test_entity_registry.py b/tests/helpers/test_entity_registry.py index cda2f1245fb..b2bfd1f48ff 100644 --- a/tests/helpers/test_entity_registry.py +++ b/tests/helpers/test_entity_registry.py @@ -2,13 +2,13 @@ import asyncio from unittest.mock import patch -import asynctest import pytest from homeassistant.const import EVENT_HOMEASSISTANT_START, STATE_UNAVAILABLE from homeassistant.core import CoreState, callback, valid_entity_id from homeassistant.helpers import entity_registry +import tests.async_mock from tests.common import MockConfigEntry, flush_store, mock_registry YAML__OPEN_PATH = "homeassistant.util.yaml.loader.open" @@ -401,7 +401,7 @@ async def test_loading_invalid_entity_id(hass, hass_storage): async def test_loading_race_condition(hass): """Test only one storage load called when concurrent loading occurred .""" - with asynctest.patch( + with tests.async_mock.patch( "homeassistant.helpers.entity_registry.EntityRegistry.async_load" ) as mock_load: results = await asyncio.gather( diff --git a/tests/helpers/test_restore_state.py b/tests/helpers/test_restore_state.py index da2acee6625..7866662266d 100644 --- a/tests/helpers/test_restore_state.py +++ b/tests/helpers/test_restore_state.py @@ -1,8 +1,6 @@ """The tests for the Restore component.""" from datetime import datetime -from asynctest import patch - from homeassistant.const import EVENT_HOMEASSISTANT_START from homeassistant.core import CoreState, State from homeassistant.exceptions import HomeAssistantError @@ -16,7 +14,7 @@ from homeassistant.helpers.restore_state import ( ) from homeassistant.util import dt as dt_util -from tests.common import mock_coro +from tests.async_mock import patch async def test_caching_data(hass): @@ -193,7 +191,7 @@ async def test_dump_error(hass): with patch( "homeassistant.helpers.restore_state.Store.async_save", - return_value=mock_coro(exception=HomeAssistantError), + side_effect=HomeAssistantError, ) as mock_write_data, patch.object(hass.states, "async_all", return_value=states): await data.async_dump_states() @@ -208,7 +206,7 @@ async def test_load_error(hass): with patch( "homeassistant.helpers.storage.Store.async_load", - return_value=mock_coro(exception=HomeAssistantError), + side_effect=HomeAssistantError, ): state = await entity.async_get_last_state() diff --git a/tests/helpers/test_script.py b/tests/helpers/test_script.py index 9d7e7751c10..c00dadc27e8 100644 --- a/tests/helpers/test_script.py +++ b/tests/helpers/test_script.py @@ -6,7 +6,6 @@ from datetime import timedelta import logging from unittest import mock -import asynctest import pytest import voluptuous as vol @@ -19,6 +18,7 @@ from homeassistant.helpers import config_validation as cv, script from homeassistant.helpers.event import async_call_later import homeassistant.util.dt as dt_util +from tests.async_mock import patch from tests.common import ( async_capture_events, async_fire_time_changed, @@ -776,7 +776,7 @@ async def test_condition_basic(hass, script_mode): @pytest.mark.parametrize("script_mode", _BASIC_SCRIPT_MODES) -@asynctest.patch("homeassistant.helpers.script.condition.async_from_config") +@patch("homeassistant.helpers.script.condition.async_from_config") async def test_condition_created_once(async_from_config, hass, script_mode): """Test that the conditions do not get created multiple times.""" sequence = cv.SCRIPT_SCHEMA( diff --git a/tests/helpers/test_service.py b/tests/helpers/test_service.py index 8819684e8d6..e87fd2646dd 100644 --- a/tests/helpers/test_service.py +++ b/tests/helpers/test_service.py @@ -3,7 +3,6 @@ from collections import OrderedDict from copy import deepcopy import unittest -from asynctest import CoroutineMock, Mock, patch import pytest import voluptuous as vol @@ -27,6 +26,7 @@ from homeassistant.helpers import ( import homeassistant.helpers.config_validation as cv from homeassistant.setup import async_setup_component +from tests.async_mock import AsyncMock, Mock, patch from tests.common import ( MockEntity, get_test_home_assistant, @@ -39,7 +39,9 @@ from tests.common import ( @pytest.fixture def mock_handle_entity_call(): """Mock service platform call.""" - with patch("homeassistant.helpers.service._handle_entity_call") as mock_call: + with patch( + "homeassistant.helpers.service._handle_entity_call", return_value=None, + ) as mock_call: yield mock_call @@ -306,7 +308,7 @@ async def test_async_get_all_descriptions(hass): async def test_call_with_required_features(hass, mock_entities): """Test service calls invoked only if entity has required feautres.""" - test_service_mock = CoroutineMock(return_value=None) + test_service_mock = AsyncMock(return_value=None) await service.entity_service_call( hass, [Mock(entities=mock_entities)], @@ -321,7 +323,7 @@ async def test_call_with_required_features(hass, mock_entities): async def test_call_with_sync_func(hass, mock_entities): """Test invoking sync service calls.""" - test_service_mock = Mock() + test_service_mock = Mock(return_value=None) await service.entity_service_call( hass, [Mock(entities=mock_entities)], @@ -333,7 +335,7 @@ async def test_call_with_sync_func(hass, mock_entities): async def test_call_with_sync_attr(hass, mock_entities): """Test invoking sync service calls.""" - mock_method = mock_entities["light.kitchen"].sync_method = Mock() + mock_method = mock_entities["light.kitchen"].sync_method = Mock(return_value=None) await service.entity_service_call( hass, [Mock(entities=mock_entities)], diff --git a/tests/helpers/test_storage.py b/tests/helpers/test_storage.py index 1966430113c..6325294033f 100644 --- a/tests/helpers/test_storage.py +++ b/tests/helpers/test_storage.py @@ -3,7 +3,6 @@ import asyncio from datetime import timedelta import json -from asynctest import Mock, patch import pytest from homeassistant.const import ( @@ -14,6 +13,7 @@ from homeassistant.core import CoreState from homeassistant.helpers import storage from homeassistant.util import dt +from tests.async_mock import Mock, patch from tests.common import async_fire_time_changed MOCK_VERSION = 1 diff --git a/tests/helpers/test_translation.py b/tests/helpers/test_translation.py index 3957d2c19ee..8596b9dd7f3 100644 --- a/tests/helpers/test_translation.py +++ b/tests/helpers/test_translation.py @@ -3,14 +3,15 @@ import asyncio from os import path import pathlib -from asynctest import Mock, patch import pytest from homeassistant.const import EVENT_COMPONENT_LOADED from homeassistant.generated import config_flows from homeassistant.helpers import translation from homeassistant.loader import async_get_integration -from homeassistant.setup import async_setup_component +from homeassistant.setup import async_setup_component, setup_component + +from tests.async_mock import Mock, patch @pytest.fixture @@ -142,11 +143,11 @@ async def test_get_translations_loads_config_flows(hass, mock_config_flows): integration = Mock(file_path=pathlib.Path(__file__)) integration.name = "Component 1" - with patch.object( - translation, "component_translation_path", return_value="bla.json" - ), patch.object( - translation, - "load_translations_files", + with patch( + "homeassistant.helpers.translation.component_translation_path", + return_value="bla.json", + ), patch( + "homeassistant.helpers.translation.load_translations_files", return_value={"component1": {"hello": "world"}}, ), patch( "homeassistant.helpers.translation.async_get_integration", @@ -169,16 +170,18 @@ async def test_get_translations_while_loading_components(hass): integration.name = "Component 1" hass.config.components.add("component1") - async def mock_load_translation_files(files): + def mock_load_translation_files(files): """Mock load translation files.""" # Mimic race condition by loading a component during setup - await async_setup_component(hass, "persistent_notification", {}) + setup_component(hass, "persistent_notification", {}) return {"component1": {"hello": "world"}} - with patch.object( - translation, "component_translation_path", return_value="bla.json" - ), patch.object( - translation, "load_translations_files", side_effect=mock_load_translation_files, + with patch( + "homeassistant.helpers.translation.component_translation_path", + return_value="bla.json", + ), patch( + "homeassistant.helpers.translation.load_translations_files", + mock_load_translation_files, ), patch( "homeassistant.helpers.translation.async_get_integration", return_value=integration, @@ -229,9 +232,8 @@ async def test_translation_merging(hass, caplog): result["sensor.season"] = {"state": "bad data"} return result - with patch.object( - translation, - "load_translations_files", + with patch( + "homeassistant.helpers.translation.load_translations_files", side_effect=mock_load_translations_files, ): translations = await translation.async_get_translations(hass, "en", "state") diff --git a/tests/helpers/test_update_coordinator.py b/tests/helpers/test_update_coordinator.py index 897367619ed..8d4f6934d78 100644 --- a/tests/helpers/test_update_coordinator.py +++ b/tests/helpers/test_update_coordinator.py @@ -4,12 +4,12 @@ from datetime import timedelta import logging import aiohttp -from asynctest import CoroutineMock, Mock import pytest from homeassistant.helpers import update_coordinator from homeassistant.util.dt import utcnow +from tests.async_mock import AsyncMock, Mock from tests.common import async_fire_time_changed LOGGER = logging.getLogger(__name__) @@ -89,7 +89,7 @@ async def test_request_refresh(crd): ) async def test_refresh_known_errors(err_msg, crd, caplog): """Test raising known errors.""" - crd.update_method = CoroutineMock(side_effect=err_msg[0]) + crd.update_method = AsyncMock(side_effect=err_msg[0]) await crd.async_refresh() @@ -102,7 +102,7 @@ async def test_refresh_fail_unknown(crd, caplog): """Test raising unknown error.""" await crd.async_refresh() - crd.update_method = CoroutineMock(side_effect=ValueError) + crd.update_method = AsyncMock(side_effect=ValueError) await crd.async_refresh() diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py index 72f26ae33ad..a639b16893b 100644 --- a/tests/test_bootstrap.py +++ b/tests/test_bootstrap.py @@ -4,7 +4,6 @@ import logging import os from unittest.mock import Mock -from asynctest import patch import pytest from homeassistant import bootstrap @@ -12,6 +11,7 @@ import homeassistant.config as config_util from homeassistant.exceptions import HomeAssistantError import homeassistant.util.dt as dt_util +from tests.async_mock import patch from tests.common import ( MockConfigEntry, MockModule, diff --git a/tests/test_config.py b/tests/test_config.py index b92ea0e890b..5d9fa7d8da1 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -4,10 +4,7 @@ from collections import OrderedDict import copy import os from unittest import mock -from unittest.mock import Mock -import asynctest -from asynctest import CoroutineMock, patch import pytest import voluptuous as vol from voluptuous import Invalid, MultipleInvalid @@ -37,6 +34,7 @@ from homeassistant.loader import async_get_integration from homeassistant.util import dt as dt_util from homeassistant.util.yaml import SECRET_YAML +from tests.async_mock import AsyncMock, Mock, patch from tests.common import get_test_config_dir, patch_yaml_files CONFIG_DIR = get_test_config_dir() @@ -98,7 +96,7 @@ async def test_ensure_config_exists_creates_config(hass): If not creates a new config file. """ - with mock.patch("builtins.print") as mock_print: + with patch("builtins.print") as mock_print: await config_util.async_ensure_config_exists(hass) assert os.path.isfile(YAML_PATH) @@ -168,7 +166,7 @@ async def test_create_default_config_returns_none_if_write_error(hass): Non existing folder returns None. """ hass.config.config_dir = os.path.join(CONFIG_DIR, "non_existing_dir/") - with mock.patch("builtins.print") as mock_print: + with patch("builtins.print") as mock_print: assert await config_util.async_create_default_config(hass) is False assert mock_print.called @@ -245,15 +243,15 @@ async def test_entity_customization(hass): assert state.attributes["hidden"] -@mock.patch("homeassistant.config.shutil") -@mock.patch("homeassistant.config.os") -@mock.patch("homeassistant.config.is_docker_env", return_value=False) +@patch("homeassistant.config.shutil") +@patch("homeassistant.config.os") +@patch("homeassistant.config.is_docker_env", return_value=False) def test_remove_lib_on_upgrade(mock_docker, mock_os, mock_shutil, hass): """Test removal of library on upgrade from before 0.50.""" ha_version = "0.49.0" mock_os.path.isdir = mock.Mock(return_value=True) mock_open = mock.mock_open() - with mock.patch("homeassistant.config.open", mock_open, create=True): + with patch("homeassistant.config.open", mock_open, create=True): opened_file = mock_open.return_value # pylint: disable=no-member opened_file.readline.return_value = ha_version @@ -267,15 +265,15 @@ def test_remove_lib_on_upgrade(mock_docker, mock_os, mock_shutil, hass): assert mock_shutil.rmtree.call_args == mock.call(hass_path) -@mock.patch("homeassistant.config.shutil") -@mock.patch("homeassistant.config.os") -@mock.patch("homeassistant.config.is_docker_env", return_value=True) +@patch("homeassistant.config.shutil") +@patch("homeassistant.config.os") +@patch("homeassistant.config.is_docker_env", return_value=True) def test_remove_lib_on_upgrade_94(mock_docker, mock_os, mock_shutil, hass): """Test removal of library on upgrade from before 0.94 and in Docker.""" ha_version = "0.93.0.dev0" mock_os.path.isdir = mock.Mock(return_value=True) mock_open = mock.mock_open() - with mock.patch("homeassistant.config.open", mock_open, create=True): + with patch("homeassistant.config.open", mock_open, create=True): opened_file = mock_open.return_value # pylint: disable=no-member opened_file.readline.return_value = ha_version @@ -294,9 +292,9 @@ def test_process_config_upgrade(hass): ha_version = "0.92.0" mock_open = mock.mock_open() - with mock.patch( - "homeassistant.config.open", mock_open, create=True - ), mock.patch.object(config_util, "__version__", "0.91.0"): + with patch("homeassistant.config.open", mock_open, create=True), patch.object( + config_util, "__version__", "0.91.0" + ): opened_file = mock_open.return_value # pylint: disable=no-member opened_file.readline.return_value = ha_version @@ -312,7 +310,7 @@ def test_config_upgrade_same_version(hass): ha_version = __version__ mock_open = mock.mock_open() - with mock.patch("homeassistant.config.open", mock_open, create=True): + with patch("homeassistant.config.open", mock_open, create=True): opened_file = mock_open.return_value # pylint: disable=no-member opened_file.readline.return_value = ha_version @@ -326,7 +324,7 @@ def test_config_upgrade_no_file(hass): """Test update of version on upgrade, with no version file.""" mock_open = mock.mock_open() mock_open.side_effect = [FileNotFoundError(), mock.DEFAULT, mock.DEFAULT] - with mock.patch("homeassistant.config.open", mock_open, create=True): + with patch("homeassistant.config.open", mock_open, create=True): opened_file = mock_open.return_value # pylint: disable=no-member config_util.process_ha_config_upgrade(hass) @@ -505,14 +503,14 @@ async def test_loading_configuration_from_packages(hass): ) -@asynctest.mock.patch("homeassistant.helpers.check_config.async_check_ha_config_file") +@patch("homeassistant.helpers.check_config.async_check_ha_config_file") async def test_check_ha_config_file_correct(mock_check, hass): """Check that restart propagates to stop.""" mock_check.return_value = check_config.HomeAssistantConfig() assert await config_util.async_check_ha_config_file(hass) is None -@asynctest.mock.patch("homeassistant.helpers.check_config.async_check_ha_config_file") +@patch("homeassistant.helpers.check_config.async_check_ha_config_file") async def test_check_ha_config_file_wrong(mock_check, hass): """Check that restart with a bad config doesn't propagate to stop.""" mock_check.return_value = check_config.HomeAssistantConfig() @@ -521,9 +519,7 @@ async def test_check_ha_config_file_wrong(mock_check, hass): assert await config_util.async_check_ha_config_file(hass) == "bad" -@asynctest.mock.patch( - "homeassistant.config.os.path.isfile", mock.Mock(return_value=True) -) +@patch("homeassistant.config.os.path.isfile", mock.Mock(return_value=True)) async def test_async_hass_config_yaml_merge(merge_log_err, hass): """Test merge during async config reload.""" config = { @@ -549,7 +545,7 @@ async def test_async_hass_config_yaml_merge(merge_log_err, hass): @pytest.fixture def merge_log_err(hass): """Patch _merge_log_error from packages.""" - with mock.patch("homeassistant.config._LOGGER.error") as logerr: + with patch("homeassistant.config._LOGGER.error") as logerr: yield logerr @@ -907,7 +903,7 @@ async def test_component_config_exceptions(hass, caplog): domain="test_domain", get_platform=Mock( return_value=Mock( - async_validate_config=CoroutineMock( + async_validate_config=AsyncMock( side_effect=ValueError("broken") ) ) diff --git a/tests/test_config_entries.py b/tests/test_config_entries.py index 6d5c735b882..592bc1d4656 100644 --- a/tests/test_config_entries.py +++ b/tests/test_config_entries.py @@ -2,7 +2,6 @@ import asyncio from datetime import timedelta -from asynctest import CoroutineMock, MagicMock, patch import pytest from homeassistant import config_entries, data_entry_flow, loader @@ -11,6 +10,7 @@ from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.setup import async_setup_component from homeassistant.util import dt +from tests.async_mock import AsyncMock, patch from tests.common import ( MockConfigEntry, MockEntity, @@ -54,8 +54,8 @@ async def test_call_setup_entry(hass): entry = MockConfigEntry(domain="comp") entry.add_to_hass(hass) - mock_setup_entry = MagicMock(return_value=mock_coro(True)) - mock_migrate_entry = MagicMock(return_value=mock_coro(True)) + mock_setup_entry = AsyncMock(return_value=True) + mock_migrate_entry = AsyncMock(return_value=True) mock_integration( hass, @@ -80,8 +80,8 @@ async def test_call_async_migrate_entry(hass): entry.version = 2 entry.add_to_hass(hass) - mock_migrate_entry = MagicMock(return_value=mock_coro(True)) - mock_setup_entry = MagicMock(return_value=mock_coro(True)) + mock_migrate_entry = AsyncMock(return_value=True) + mock_setup_entry = AsyncMock(return_value=True) mock_integration( hass, @@ -106,8 +106,8 @@ async def test_call_async_migrate_entry_failure_false(hass): entry.version = 2 entry.add_to_hass(hass) - mock_migrate_entry = MagicMock(return_value=mock_coro(False)) - mock_setup_entry = MagicMock(return_value=mock_coro(True)) + mock_migrate_entry = AsyncMock(return_value=False) + mock_setup_entry = AsyncMock(return_value=True) mock_integration( hass, @@ -132,8 +132,8 @@ async def test_call_async_migrate_entry_failure_exception(hass): entry.version = 2 entry.add_to_hass(hass) - mock_migrate_entry = MagicMock(return_value=mock_coro(exception=Exception)) - mock_setup_entry = MagicMock(return_value=mock_coro(True)) + mock_migrate_entry = AsyncMock(side_effect=Exception) + mock_setup_entry = AsyncMock(return_value=True) mock_integration( hass, @@ -158,8 +158,8 @@ async def test_call_async_migrate_entry_failure_not_bool(hass): entry.version = 2 entry.add_to_hass(hass) - mock_migrate_entry = MagicMock(return_value=mock_coro()) - mock_setup_entry = MagicMock(return_value=mock_coro(True)) + mock_migrate_entry = AsyncMock(return_value=None) + mock_setup_entry = AsyncMock(return_value=True) mock_integration( hass, @@ -184,7 +184,7 @@ async def test_call_async_migrate_entry_failure_not_supported(hass): entry.version = 2 entry.add_to_hass(hass) - mock_setup_entry = MagicMock(return_value=mock_coro(True)) + mock_setup_entry = AsyncMock(return_value=True) mock_integration(hass, MockModule("comp", async_setup_entry=mock_setup_entry)) mock_entity_platform(hass, "config_flow.comp", None) @@ -211,7 +211,7 @@ async def test_remove_entry(hass, manager): assert result return result - mock_remove_entry = MagicMock(side_effect=lambda *args, **kwargs: mock_coro()) + mock_remove_entry = AsyncMock(return_value=None) entity = MockEntity(unique_id="1234", name="Test Entity") @@ -283,9 +283,9 @@ async def test_remove_entry(hass, manager): async def test_remove_entry_handles_callback_error(hass, manager): """Test that exceptions in the remove callback are handled.""" - mock_setup_entry = MagicMock(return_value=mock_coro(True)) - mock_unload_entry = MagicMock(return_value=mock_coro(True)) - mock_remove_entry = MagicMock(side_effect=lambda *args, **kwargs: mock_coro()) + mock_setup_entry = AsyncMock(return_value=True) + mock_unload_entry = AsyncMock(return_value=True) + mock_remove_entry = AsyncMock(return_value=None) mock_integration( hass, MockModule( @@ -343,7 +343,7 @@ async def test_remove_entry_raises(hass, manager): async def test_remove_entry_if_not_loaded(hass, manager): """Test that we can remove an entry that is not loaded.""" - mock_unload_entry = MagicMock(return_value=mock_coro(True)) + mock_unload_entry = AsyncMock(return_value=True) mock_integration(hass, MockModule("comp", async_unload_entry=mock_unload_entry)) @@ -367,7 +367,7 @@ async def test_remove_entry_if_not_loaded(hass, manager): async def test_add_entry_calls_setup_entry(hass, manager): """Test we call setup_config_entry.""" - mock_setup_entry = MagicMock(return_value=mock_coro(True)) + mock_setup_entry = AsyncMock(return_value=True) mock_integration(hass, MockModule("comp", async_setup_entry=mock_setup_entry)) mock_entity_platform(hass, "config_flow.comp", None) @@ -486,12 +486,12 @@ async def test_forward_entry_sets_up_component(hass): """Test we setup the component entry is forwarded to.""" entry = MockConfigEntry(domain="original") - mock_original_setup_entry = MagicMock(return_value=mock_coro(True)) + mock_original_setup_entry = AsyncMock(return_value=True) mock_integration( hass, MockModule("original", async_setup_entry=mock_original_setup_entry) ) - mock_forwarded_setup_entry = MagicMock(return_value=mock_coro(True)) + mock_forwarded_setup_entry = AsyncMock(return_value=True) mock_integration( hass, MockModule("forwarded", async_setup_entry=mock_forwarded_setup_entry) ) @@ -505,8 +505,8 @@ async def test_forward_entry_does_not_setup_entry_if_setup_fails(hass): """Test we do not set up entry if component setup fails.""" entry = MockConfigEntry(domain="original") - mock_setup = MagicMock(return_value=mock_coro(False)) - mock_setup_entry = MagicMock() + mock_setup = AsyncMock(return_value=False) + mock_setup_entry = AsyncMock() mock_integration( hass, MockModule( @@ -643,7 +643,7 @@ async def test_setup_raise_not_ready(hass, caplog): """Test a setup raising not ready.""" entry = MockConfigEntry(domain="test") - mock_setup_entry = MagicMock(side_effect=ConfigEntryNotReady) + mock_setup_entry = AsyncMock(side_effect=ConfigEntryNotReady) mock_integration(hass, MockModule("test", async_setup_entry=mock_setup_entry)) mock_entity_platform(hass, "config_flow.test", None) @@ -659,7 +659,7 @@ async def test_setup_raise_not_ready(hass, caplog): assert entry.state == config_entries.ENTRY_STATE_SETUP_RETRY mock_setup_entry.side_effect = None - mock_setup_entry.return_value = mock_coro(True) + mock_setup_entry.return_value = True await p_setup(None) assert entry.state == config_entries.ENTRY_STATE_LOADED @@ -669,7 +669,7 @@ async def test_setup_retrying_during_unload(hass): """Test if we unload an entry that is in retry mode.""" entry = MockConfigEntry(domain="test") - mock_setup_entry = MagicMock(side_effect=ConfigEntryNotReady) + mock_setup_entry = AsyncMock(side_effect=ConfigEntryNotReady) mock_integration(hass, MockModule("test", async_setup_entry=mock_setup_entry)) mock_entity_platform(hass, "config_flow.test", None) @@ -721,8 +721,8 @@ async def test_entry_setup_succeed(hass, manager): entry = MockConfigEntry(domain="comp", state=config_entries.ENTRY_STATE_NOT_LOADED) entry.add_to_hass(hass) - mock_setup = MagicMock(return_value=mock_coro(True)) - mock_setup_entry = MagicMock(return_value=mock_coro(True)) + mock_setup = AsyncMock(return_value=True) + mock_setup_entry = AsyncMock(return_value=True) mock_integration( hass, @@ -751,8 +751,8 @@ async def test_entry_setup_invalid_state(hass, manager, state): entry = MockConfigEntry(domain="comp", state=state) entry.add_to_hass(hass) - mock_setup = MagicMock(return_value=mock_coro(True)) - mock_setup_entry = MagicMock(return_value=mock_coro(True)) + mock_setup = AsyncMock(return_value=True) + mock_setup_entry = AsyncMock(return_value=True) mock_integration( hass, @@ -772,7 +772,7 @@ async def test_entry_unload_succeed(hass, manager): entry = MockConfigEntry(domain="comp", state=config_entries.ENTRY_STATE_LOADED) entry.add_to_hass(hass) - async_unload_entry = MagicMock(return_value=mock_coro(True)) + async_unload_entry = AsyncMock(return_value=True) mock_integration(hass, MockModule("comp", async_unload_entry=async_unload_entry)) @@ -794,7 +794,7 @@ async def test_entry_unload_failed_to_load(hass, manager, state): entry = MockConfigEntry(domain="comp", state=state) entry.add_to_hass(hass) - async_unload_entry = MagicMock(return_value=mock_coro(True)) + async_unload_entry = AsyncMock(return_value=True) mock_integration(hass, MockModule("comp", async_unload_entry=async_unload_entry)) @@ -815,7 +815,7 @@ async def test_entry_unload_invalid_state(hass, manager, state): entry = MockConfigEntry(domain="comp", state=state) entry.add_to_hass(hass) - async_unload_entry = MagicMock(return_value=mock_coro(True)) + async_unload_entry = AsyncMock(return_value=True) mock_integration(hass, MockModule("comp", async_unload_entry=async_unload_entry)) @@ -831,9 +831,9 @@ async def test_entry_reload_succeed(hass, manager): entry = MockConfigEntry(domain="comp", state=config_entries.ENTRY_STATE_LOADED) entry.add_to_hass(hass) - async_setup = MagicMock(return_value=mock_coro(True)) - async_setup_entry = MagicMock(return_value=mock_coro(True)) - async_unload_entry = MagicMock(return_value=mock_coro(True)) + async_setup = AsyncMock(return_value=True) + async_setup_entry = AsyncMock(return_value=True) + async_unload_entry = AsyncMock(return_value=True) mock_integration( hass, @@ -866,9 +866,9 @@ async def test_entry_reload_not_loaded(hass, manager, state): entry = MockConfigEntry(domain="comp", state=state) entry.add_to_hass(hass) - async_setup = MagicMock(return_value=mock_coro(True)) - async_setup_entry = MagicMock(return_value=mock_coro(True)) - async_unload_entry = MagicMock(return_value=mock_coro(True)) + async_setup = AsyncMock(return_value=True) + async_setup_entry = AsyncMock(return_value=True) + async_unload_entry = AsyncMock(return_value=True) mock_integration( hass, @@ -900,9 +900,9 @@ async def test_entry_reload_error(hass, manager, state): entry = MockConfigEntry(domain="comp", state=state) entry.add_to_hass(hass) - async_setup = MagicMock(return_value=mock_coro(True)) - async_setup_entry = MagicMock(return_value=mock_coro(True)) - async_unload_entry = MagicMock(return_value=mock_coro(True)) + async_setup = AsyncMock(return_value=True) + async_setup_entry = AsyncMock(return_value=True) + async_unload_entry = AsyncMock(return_value=True) mock_integration( hass, @@ -968,8 +968,8 @@ async def test_reload_entry_entity_registry_works(hass): domain="comp", state=config_entries.ENTRY_STATE_LOADED ) config_entry.add_to_hass(hass) - mock_setup_entry = MagicMock(return_value=mock_coro(True)) - mock_unload_entry = MagicMock(return_value=mock_coro(True)) + mock_setup_entry = AsyncMock(return_value=True) + mock_unload_entry = AsyncMock(return_value=True) mock_integration( hass, MockModule( @@ -1016,7 +1016,7 @@ async def test_reload_entry_entity_registry_works(hass): async def test_unqiue_id_persisted(hass, manager): """Test that a unique ID is stored in the config entry.""" - mock_setup_entry = MagicMock(return_value=mock_coro(True)) + mock_setup_entry = AsyncMock(return_value=True) mock_integration(hass, MockModule("comp", async_setup_entry=mock_setup_entry)) mock_entity_platform(hass, "config_flow.comp", None) @@ -1052,9 +1052,9 @@ async def test_unique_id_existing_entry(hass, manager): unique_id="mock-unique-id", ).add_to_hass(hass) - async_setup_entry = MagicMock(side_effect=lambda _, _2: mock_coro(True)) - async_unload_entry = MagicMock(side_effect=lambda _, _2: mock_coro(True)) - async_remove_entry = MagicMock(side_effect=lambda _, _2: mock_coro(True)) + async_setup_entry = AsyncMock(return_value=True) + async_unload_entry = AsyncMock(return_value=True) + async_remove_entry = AsyncMock(return_value=True) mock_integration( hass, @@ -1205,8 +1205,7 @@ async def test_unique_id_in_progress(hass, manager): async def test_finish_flow_aborts_progress(hass, manager): """Test that when finishing a flow, we abort other flows in progress with unique ID.""" mock_integration( - hass, - MockModule("comp", async_setup_entry=MagicMock(return_value=mock_coro(True))), + hass, MockModule("comp", async_setup_entry=AsyncMock(return_value=True)), ) mock_entity_platform(hass, "config_flow.comp", None) @@ -1243,7 +1242,7 @@ async def test_finish_flow_aborts_progress(hass, manager): async def test_unique_id_ignore(hass, manager): """Test that we can ignore flows that are in progress and have a unique ID.""" - async_setup_entry = MagicMock(return_value=mock_coro(False)) + async_setup_entry = AsyncMock(return_value=False) mock_integration(hass, MockModule("comp", async_setup_entry=async_setup_entry)) mock_entity_platform(hass, "config_flow.comp", None) @@ -1285,7 +1284,7 @@ async def test_unique_id_ignore(hass, manager): async def test_unignore_step_form(hass, manager): """Test that we can ignore flows that are in progress and have a unique ID, then rediscover them.""" - async_setup_entry = MagicMock(return_value=mock_coro(True)) + async_setup_entry = AsyncMock(return_value=True) mock_integration(hass, MockModule("comp", async_setup_entry=async_setup_entry)) mock_entity_platform(hass, "config_flow.comp", None) @@ -1329,7 +1328,7 @@ async def test_unignore_step_form(hass, manager): async def test_unignore_create_entry(hass, manager): """Test that we can ignore flows that are in progress and have a unique ID, then rediscover them.""" - async_setup_entry = MagicMock(return_value=mock_coro(True)) + async_setup_entry = AsyncMock(return_value=True) mock_integration(hass, MockModule("comp", async_setup_entry=async_setup_entry)) mock_entity_platform(hass, "config_flow.comp", None) @@ -1376,7 +1375,7 @@ async def test_unignore_create_entry(hass, manager): async def test_unignore_default_impl(hass, manager): """Test that resdicovery is a no-op by default.""" - async_setup_entry = MagicMock(return_value=mock_coro(True)) + async_setup_entry = AsyncMock(return_value=True) mock_integration(hass, MockModule("comp", async_setup_entry=async_setup_entry)) mock_entity_platform(hass, "config_flow.comp", None) @@ -1407,7 +1406,7 @@ async def test_unignore_default_impl(hass, manager): async def test_partial_flows_hidden(hass, manager): """Test that flows that don't have a cur_step and haven't finished initing are hidden.""" - async_setup_entry = MagicMock(return_value=mock_coro(True)) + async_setup_entry = AsyncMock(return_value=True) mock_integration(hass, MockModule("comp", async_setup_entry=async_setup_entry)) mock_entity_platform(hass, "config_flow.comp", None) await async_setup_component(hass, "persistent_notification", {}) @@ -1476,7 +1475,7 @@ async def test_async_setup_init_entry(hass): ) return True - async_setup_entry = CoroutineMock(return_value=True) + async_setup_entry = AsyncMock(return_value=True) mock_integration( hass, MockModule( diff --git a/tests/test_core.py b/tests/test_core.py index 8b4a2ae9f84..3221bfcd39d 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -7,7 +7,6 @@ import logging import os from tempfile import TemporaryDirectory import unittest -from unittest.mock import MagicMock, patch import pytest import pytz @@ -35,6 +34,7 @@ from homeassistant.exceptions import InvalidEntityFormatError, InvalidStateError import homeassistant.util.dt as dt_util from homeassistant.util.unit_system import METRIC_SYSTEM +from tests.async_mock import MagicMock, patch from tests.common import async_mock_service, get_test_home_assistant PST = pytz.timezone("America/Los_Angeles") diff --git a/tests/test_loader.py b/tests/test_loader.py index 745bb9c8c2c..eb99cb3a8ea 100644 --- a/tests/test_loader.py +++ b/tests/test_loader.py @@ -1,11 +1,11 @@ """Test to verify that we can load components.""" -from asynctest.mock import ANY, patch import pytest from homeassistant.components import http, hue from homeassistant.components.hue import light as hue_light import homeassistant.loader as loader +from tests.async_mock import ANY, patch from tests.common import MockModule, async_mock_service, mock_integration diff --git a/tests/test_requirements.py b/tests/test_requirements.py index e95db4e533d..f98485e8006 100644 --- a/tests/test_requirements.py +++ b/tests/test_requirements.py @@ -1,7 +1,6 @@ """Test requirements module.""" import os from pathlib import Path -from unittest.mock import call, patch import pytest @@ -15,12 +14,8 @@ from homeassistant.requirements import ( async_process_requirements, ) -from tests.common import ( - MockModule, - get_test_home_assistant, - mock_coro, - mock_integration, -) +from tests.async_mock import call, patch +from tests.common import MockModule, mock_integration def env_without_wheel_links(): @@ -30,58 +25,42 @@ def env_without_wheel_links(): return env -class TestRequirements: - """Test the requirements module.""" - - hass = None - backup_cache = None - - # pylint: disable=invalid-name, no-self-use - def setup_method(self, method): - """Set up the test.""" - self.hass = get_test_home_assistant() - - def teardown_method(self, method): - """Clean up.""" - self.hass.stop() - - @patch("os.path.dirname") - @patch("homeassistant.util.package.is_virtual_env", return_value=True) - @patch("homeassistant.util.package.is_docker_env", return_value=False) - @patch("homeassistant.util.package.install_package", return_value=True) - @patch.dict(os.environ, env_without_wheel_links(), clear=True) - def test_requirement_installed_in_venv( - self, mock_install, mock_denv, mock_venv, mock_dirname +async def test_requirement_installed_in_venv(hass): + """Test requirement installed in virtual environment.""" + with patch("os.path.dirname", return_value="ha_package_path"), patch( + "homeassistant.util.package.is_virtual_env", return_value=True + ), patch("homeassistant.util.package.is_docker_env", return_value=False), patch( + "homeassistant.util.package.install_package", return_value=True + ) as mock_install, patch.dict( + os.environ, env_without_wheel_links(), clear=True ): - """Test requirement installed in virtual environment.""" - mock_dirname.return_value = "ha_package_path" - self.hass.config.skip_pip = False - mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) - assert setup.setup_component(self.hass, "comp", {}) - assert "comp" in self.hass.config.components + hass.config.skip_pip = False + mock_integration(hass, MockModule("comp", requirements=["package==0.0.1"])) + assert await setup.async_setup_component(hass, "comp", {}) + assert "comp" in hass.config.components assert mock_install.call_args == call( "package==0.0.1", constraints=os.path.join("ha_package_path", CONSTRAINT_FILE), no_cache_dir=False, ) - @patch("os.path.dirname") - @patch("homeassistant.util.package.is_virtual_env", return_value=False) - @patch("homeassistant.util.package.is_docker_env", return_value=False) - @patch("homeassistant.util.package.install_package", return_value=True) - @patch.dict(os.environ, env_without_wheel_links(), clear=True) - def test_requirement_installed_in_deps( - self, mock_install, mock_denv, mock_venv, mock_dirname + +async def test_requirement_installed_in_deps(hass): + """Test requirement installed in deps directory.""" + with patch("os.path.dirname", return_value="ha_package_path"), patch( + "homeassistant.util.package.is_virtual_env", return_value=False + ), patch("homeassistant.util.package.is_docker_env", return_value=False), patch( + "homeassistant.util.package.install_package", return_value=True + ) as mock_install, patch.dict( + os.environ, env_without_wheel_links(), clear=True ): - """Test requirement installed in deps directory.""" - mock_dirname.return_value = "ha_package_path" - self.hass.config.skip_pip = False - mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) - assert setup.setup_component(self.hass, "comp", {}) - assert "comp" in self.hass.config.components + hass.config.skip_pip = False + mock_integration(hass, MockModule("comp", requirements=["package==0.0.1"])) + assert await setup.async_setup_component(hass, "comp", {}) + assert "comp" in hass.config.components assert mock_install.call_args == call( "package==0.0.1", - target=self.hass.config.path("deps"), + target=hass.config.path("deps"), constraints=os.path.join("ha_package_path", CONSTRAINT_FILE), no_cache_dir=False, ) @@ -239,7 +218,6 @@ async def test_discovery_requirements_ssdp(hass): ) with patch( "homeassistant.requirements.async_process_requirements", - side_effect=lambda _, _2, _3: mock_coro(), ) as mock_process: await async_get_integration_with_requirements(hass, "ssdp_comp") @@ -262,7 +240,6 @@ async def test_discovery_requirements_zeroconf(hass, partial_manifest): with patch( "homeassistant.requirements.async_process_requirements", - side_effect=lambda _, _2, _3: mock_coro(), ) as mock_process: await async_get_integration_with_requirements(hass, "comp") diff --git a/tests/test_setup.py b/tests/test_setup.py index a5e53861ef0..4197fe7370a 100644 --- a/tests/test_setup.py +++ b/tests/test_setup.py @@ -5,7 +5,6 @@ import logging import os import threading -from asynctest import Mock, patch import pytest import voluptuous as vol @@ -20,6 +19,7 @@ from homeassistant.helpers.config_validation import ( ) import homeassistant.util.dt as dt_util +from tests.async_mock import Mock, patch from tests.common import ( MockConfigEntry, MockModule, diff --git a/tests/util/test_location.py b/tests/util/test_location.py index 968c6257f37..403e24121ad 100644 --- a/tests/util/test_location.py +++ b/tests/util/test_location.py @@ -1,10 +1,10 @@ """Test Home Assistant location util methods.""" import aiohttp -from asynctest import Mock, patch import pytest import homeassistant.util.location as location_util +from tests.async_mock import Mock, patch from tests.common import load_fixture # Paris diff --git a/tests/util/test_package.py b/tests/util/test_package.py index f7cce0e298f..c9f5183249e 100644 --- a/tests/util/test_package.py +++ b/tests/util/test_package.py @@ -5,12 +5,13 @@ import os from subprocess import PIPE import sys -from asynctest import MagicMock, call, patch import pkg_resources import pytest import homeassistant.util.package as package +from tests.async_mock import MagicMock, call, patch + RESOURCE_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "resources") ) @@ -70,13 +71,11 @@ def mock_venv(): yield mock -@asyncio.coroutine def mock_async_subprocess(): """Return an async Popen mock.""" async_popen = MagicMock() - @asyncio.coroutine - def communicate(input=None): + async def communicate(input=None): """Communicate mock.""" stdout = bytes("/deps_dir/lib_dir", "utf-8") return (stdout, None)