response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Mock reolink connection.
def reolink_connect( reolink_connect_class: MagicMock, ) -> Generator[MagicMock, None, None]: """Mock reolink connection.""" return reolink_connect_class.return_value
Mock reolink entry setup.
def reolink_platforms(mock_get_source_ip: None) -> Generator[None, None, None]: """Mock reolink entry setup.""" with patch("homeassistant.components.reolink.PLATFORMS", return_value=[]): yield
Add the reolink mock config entry to hass.
def config_entry(hass: HomeAssistant) -> MockConfigEntry: """Add the reolink mock config entry to hass.""" config_entry = MockConfigEntry( domain=const.DOMAIN, unique_id=format_mac(TEST_MAC), data={ CONF_HOST: TEST_HOST, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_PORT: TEST_PORT, const.CONF_USE_HTTPS: TEST_USE_HTTPS, }, options={ CONF_PROTOCOL: DEFAULT_PROTOCOL, }, title=TEST_NVR_NAME, ) config_entry.add_to_hass(hass) return config_entry
Fixture providing different successful HTTP response code.
def http_success_code(request: pytest.FixtureRequest) -> HTTPStatus: """Fixture providing different successful HTTP response code.""" return request.param
Create rfxtrx config entry data.
def create_rfx_test_cfg( device="abcd", automatic_add=False, protocols=None, devices=None, host=None, port=None, ): """Create rfxtrx config entry data.""" return { "device": device, "host": host, "port": port, "automatic_add": automatic_add, "protocols": protocols, "debug": False, "devices": devices or {}, }
Fixture that cleans up threads from integration.
def rfxtrx_fixture(hass, connect_mock): """Fixture that cleans up threads from integration.""" rfx = Mock(spec=Connect) def _init(transport, event_callback=None, modes=None): rfx.event_callback = event_callback rfx.transport = transport return rfx connect_mock.side_effect = _init async def _signal_event(packet_id): event = rfxtrx.get_rfx_object(packet_id) await hass.async_add_executor_job( rfx.event_callback, event, ) await hass.async_block_till_done() await hass.async_block_till_done() return event rfx.signal = _signal_event return rfx
Mock of a serial port.
def com_port(): """Mock of a serial port.""" port = serial.tools.list_ports_common.ListPortInfo("/dev/ttyUSB1234") port.serial_number = "1234" port.manufacturer = "Virtual serial port" port.device = "/dev/ttyUSB1234" port.description = "Some serial port" return port
Test serial by id conversion if there's no /dev/serial/by-id.
def test_get_serial_by_id_no_dir() -> None: """Test serial by id conversion if there's no /dev/serial/by-id.""" p1 = patch("os.path.isdir", MagicMock(return_value=False)) p2 = patch("os.scandir") with p1 as is_dir_mock, p2 as scan_mock: res = config_flow.get_serial_by_id(sentinel.path) assert res is sentinel.path assert is_dir_mock.call_count == 1 assert scan_mock.call_count == 0
Test serial by id conversion.
def test_get_serial_by_id() -> None: """Test serial by id conversion.""" p1 = patch("os.path.isdir", MagicMock(return_value=True)) p2 = patch("os.scandir") def _realpath(path): if path is sentinel.matched_link: return sentinel.path return sentinel.serial_link_path p3 = patch("os.path.realpath", side_effect=_realpath) with p1 as is_dir_mock, p2 as scan_mock, p3: res = config_flow.get_serial_by_id(sentinel.path) assert res is sentinel.path assert is_dir_mock.call_count == 1 assert scan_mock.call_count == 1 entry1 = MagicMock(spec_set=os.DirEntry) entry1.is_symlink.return_value = True entry1.path = sentinel.some_path entry2 = MagicMock(spec_set=os.DirEntry) entry2.is_symlink.return_value = False entry2.path = sentinel.other_path entry3 = MagicMock(spec_set=os.DirEntry) entry3.is_symlink.return_value = True entry3.path = sentinel.matched_link scan_mock.return_value = [entry1, entry2, entry3] res = config_flow.get_serial_by_id(sentinel.path) assert res is sentinel.matched_link assert is_dir_mock.call_count == 2 assert scan_mock.call_count == 2
Only set up the required platform and required base platforms to speed up tests.
def required_platforms_only(): """Only set up the required platform and required base platforms to speed up tests.""" with patch( "homeassistant.components.rfxtrx.PLATFORMS", (Platform.EVENT,), ): yield
Define a Ridwell account.
def account_fixture(): """Define a Ridwell account.""" return Mock( account_id=TEST_ACCOUNT_ID, address={ "street1": "123 Main Street", "city": "New York", "state": "New York", "postal_code": "10001", }, async_get_pickup_events=AsyncMock( return_value=[ RidwellPickupEvent( None, "event_123", date(2022, 1, 24), [RidwellPickup("Plastic Film", "offer_123", 1, "product_123", 1)], EventState.INITIALIZED, ) ] ), )
Define an aioridwell client.
def client_fixture(account): """Define an aioridwell client.""" return Mock( async_authenticate=AsyncMock(), async_get_accounts=AsyncMock(return_value={TEST_ACCOUNT_ID: account}), get_dashboard_url=Mock(return_value=TEST_DASHBOARD_URL), user_id=TEST_USER_ID, )
Define a config entry fixture.
def config_entry_fixture(hass, config): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=config[CONF_USERNAME], data=config, entry_id="11554ec901379b9cc8f5a6c1d11ce978", ) entry.add_to_hass(hass) return entry
Define a config entry data fixture.
def config_fixture(hass): """Define a config entry data fixture.""" return { CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, }
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.ring.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock ring_doorbell.Auth.
def mock_ring_auth(): """Mock ring_doorbell.Auth.""" with patch( "homeassistant.components.ring.config_flow.Auth", autospec=True ) as mock_ring_auth: mock_ring_auth.return_value.fetch_token.return_value = { "access_token": "mock-token" } yield mock_ring_auth.return_value
Mock ConfigEntry.
def mock_config_entry() -> MockConfigEntry: """Mock ConfigEntry.""" return MockConfigEntry( title="Ring", domain=DOMAIN, data={ CONF_USERNAME: "[email protected]", "token": {"access_token": "mock-token"}, }, unique_id="[email protected]", )
Fixture to provide a requests mocker.
def requests_mock_fixture(): """Fixture to provide a requests mocker.""" with requests_mock.mock() as mock: # Note all devices have an id of 987652, but a different device_id. # the device_id is used as our unique_id, but the id is what is sent # to the APIs, which is why every mock uses that id. # Mocks the response for authenticating mock.post( "https://oauth.ring.com/oauth/token", text=load_fixture("oauth.json", "ring"), ) # Mocks the response for getting the login session mock.post( "https://api.ring.com/clients_api/session", text=load_fixture("session.json", "ring"), ) # Mocks the response for getting all the devices mock.get( "https://api.ring.com/clients_api/ring_devices", text=load_fixture("devices.json", "ring"), ) mock.get( "https://api.ring.com/clients_api/dings/active", text=load_fixture("ding_active.json", "ring"), ) # Mocks the response for getting the history of a device mock.get( re.compile( r"https:\/\/api\.ring\.com\/clients_api\/doorbots\/\d+\/history" ), text=load_fixture("doorbot_history.json", "ring"), ) # Mocks the response for getting the health of a device mock.get( re.compile(r"https:\/\/api\.ring\.com\/clients_api\/doorbots\/\d+\/health"), text=load_fixture("doorboot_health_attrs.json", "ring"), ) # Mocks the response for getting a chimes health mock.get( re.compile(r"https:\/\/api\.ring\.com\/clients_api\/chimes\/\d+\/health"), text=load_fixture("chime_health_attrs.json", "ring"), ) mock.get( re.compile( r"https:\/\/api\.ring\.com\/clients_api\/dings\/\d+\/share/play" ), status_code=200, json={"url": "http://127.0.0.1/foo"}, ) mock.get( "https://api.ring.com/groups/v1/locations/mock-location-id/groups", text=load_fixture("groups.json", "ring"), ) # Mocks the response for getting the history of the intercom mock.get( "https://api.ring.com/clients_api/doorbots/185036587/history", text=load_fixture("intercom_history.json", "ring"), ) # Mocks the response for setting properties in settings (i.e. motion_detection) mock.patch( re.compile( r"https:\/\/api\.ring\.com\/devices\/v1\/devices\/\d+\/settings" ), text="ok", ) # Mocks the open door command for intercom devices mock.put( "https://api.ring.com/commands/v1/devices/185036587/device_rpc", status_code=200, text="{}", ) # Mocks the response for getting the history of the intercom mock.get( "https://api.ring.com/clients_api/doorbots/185036587/history", text=load_fixture("intercom_history.json", "ring"), ) yield mock
Fixture to mock alarm with two zones.
def two_zone_cloud(): """Fixture to mock alarm with two zones.""" zone_mocks = {0: zone_mock(), 1: zone_mock()} alarm_mock = MagicMock() with ( patch.object(zone_mocks[0], "id", new_callable=PropertyMock(return_value=0)), patch.object( zone_mocks[0], "name", new_callable=PropertyMock(return_value="Zone 0") ), patch.object( zone_mocks[0], "bypassed", new_callable=PropertyMock(return_value=False) ), patch.object(zone_mocks[1], "id", new_callable=PropertyMock(return_value=1)), patch.object( zone_mocks[1], "name", new_callable=PropertyMock(return_value="Zone 1") ), patch.object( zone_mocks[1], "bypassed", new_callable=PropertyMock(return_value=False) ), patch.object( alarm_mock, "zones", new_callable=PropertyMock(return_value=zone_mocks), ), patch( "homeassistant.components.risco.RiscoCloud.get_state", return_value=alarm_mock, ), ): yield zone_mocks
Fixture to mock alarm with two zones.
def two_zone_local(): """Fixture to mock alarm with two zones.""" zone_mocks = {0: zone_mock(), 1: zone_mock()} system = system_mock() with ( patch.object(zone_mocks[0], "id", new_callable=PropertyMock(return_value=0)), patch.object( zone_mocks[0], "name", new_callable=PropertyMock(return_value="Zone 0") ), patch.object( zone_mocks[0], "alarmed", new_callable=PropertyMock(return_value=False) ), patch.object( zone_mocks[0], "bypassed", new_callable=PropertyMock(return_value=False) ), patch.object( zone_mocks[0], "armed", new_callable=PropertyMock(return_value=False) ), patch.object(zone_mocks[1], "id", new_callable=PropertyMock(return_value=1)), patch.object( zone_mocks[1], "name", new_callable=PropertyMock(return_value="Zone 1") ), patch.object( zone_mocks[1], "alarmed", new_callable=PropertyMock(return_value=False) ), patch.object( zone_mocks[1], "bypassed", new_callable=PropertyMock(return_value=False) ), patch.object( zone_mocks[1], "armed", new_callable=PropertyMock(return_value=False) ), patch.object( system, "name", new_callable=PropertyMock(return_value=TEST_SITE_NAME) ), patch( "homeassistant.components.risco.RiscoLocal.partitions", new_callable=PropertyMock(return_value={}), ), patch( "homeassistant.components.risco.RiscoLocal.zones", new_callable=PropertyMock(return_value=zone_mocks), ), patch( "homeassistant.components.risco.RiscoLocal.system", new_callable=PropertyMock(return_value=system), ), ): yield zone_mocks
Fixture for default (empty) options.
def options(): """Fixture for default (empty) options.""" return {}
Fixture for default (empty) events.
def events(): """Fixture for default (empty) events.""" return []
Fixture for a cloud config entry.
def cloud_config_entry(hass, options): """Fixture for a cloud config entry.""" config_entry = MockConfigEntry( domain=DOMAIN, data=TEST_CLOUD_CONFIG, options=options, unique_id=TEST_CLOUD_CONFIG[CONF_USERNAME], ) config_entry.add_to_hass(hass) return config_entry
Fixture to simulate error on login.
def login_with_error(exception): """Fixture to simulate error on login.""" with patch( "homeassistant.components.risco.RiscoCloud.login", side_effect=exception, ): yield
Fixture for a local config entry.
def local_config_entry(hass, options): """Fixture for a local config entry.""" config_entry = MockConfigEntry( domain=DOMAIN, data=TEST_LOCAL_CONFIG, options=options ) config_entry.add_to_hass(hass) return config_entry
Fixture to simulate error on connect.
def connect_with_error(exception): """Fixture to simulate error on connect.""" with patch( "homeassistant.components.risco.RiscoLocal.connect", side_effect=exception, ): yield
Fixture to mock alarm with two partitions.
def two_part_cloud_alarm(): """Fixture to mock alarm with two partitions.""" partition_mocks = {0: _partition_mock(), 1: _partition_mock()} alarm_mock = MagicMock() with ( patch.object( partition_mocks[0], "id", new_callable=PropertyMock(return_value=0) ), patch.object( partition_mocks[1], "id", new_callable=PropertyMock(return_value=1) ), patch.object( alarm_mock, "partitions", new_callable=PropertyMock(return_value=partition_mocks), ), patch( "homeassistant.components.risco.RiscoCloud.get_state", return_value=alarm_mock, ), ): yield partition_mocks
Fixture to mock alarm with two partitions.
def two_part_local_alarm(): """Fixture to mock alarm with two partitions.""" partition_mocks = {0: _partition_mock(), 1: _partition_mock()} with ( patch.object( partition_mocks[0], "id", new_callable=PropertyMock(return_value=0) ), patch.object( partition_mocks[0], "name", new_callable=PropertyMock(return_value="Name 0") ), patch.object( partition_mocks[1], "id", new_callable=PropertyMock(return_value=1) ), patch.object( partition_mocks[1], "name", new_callable=PropertyMock(return_value="Name 1") ), patch( "homeassistant.components.risco.RiscoLocal.zones", new_callable=PropertyMock(return_value={}), ), patch( "homeassistant.components.risco.RiscoLocal.partitions", new_callable=PropertyMock(return_value=partition_mocks), ), ): yield partition_mocks
Create a mock for add_partition_handler.
def mock_partition_handler(): """Create a mock for add_partition_handler.""" with patch( "homeassistant.components.risco.RiscoLocal.add_partition_handler" ) as mock: yield mock
Create a mock for add_zone_handler.
def mock_zone_handler(): """Create a mock for add_zone_handler.""" with patch("homeassistant.components.risco.RiscoLocal.add_zone_handler") as mock: yield mock
Create a mock for add_system_handler.
def mock_system_handler(): """Create a mock for add_system_handler.""" with patch("homeassistant.components.risco.RiscoLocal.add_system_handler") as mock: yield mock
Fixture to mock a system with no zones or partitions.
def system_only_local(): """Fixture to mock a system with no zones or partitions.""" system = system_mock() with ( patch.object( system, "name", new_callable=PropertyMock(return_value=TEST_SITE_NAME) ), patch( "homeassistant.components.risco.RiscoLocal.zones", new_callable=PropertyMock(return_value={}), ), patch( "homeassistant.components.risco.RiscoLocal.partitions", new_callable=PropertyMock(return_value={}), ), patch( "homeassistant.components.risco.RiscoLocal.system", new_callable=PropertyMock(return_value=system), ), ): yield system
Create a mock for async_save.
def save_mock(): """Create a mock for async_save.""" with patch( "homeassistant.components.risco.Store.async_save", ) as save_mock: yield save_mock
Create a mock for add_zone_handler.
def mock_zone_handler(): """Create a mock for add_zone_handler.""" with patch("homeassistant.components.risco.RiscoLocal.add_zone_handler") as mock: yield mock
Return a mocked zone.
def zone_mock(): """Return a mocked zone.""" return MagicMock( triggered=False, bypassed=False, bypass=AsyncMock(return_value=True) )
Return a mocked system.
def system_mock(): """Return a mocked system.""" return MagicMock( low_battery_trouble=False, ac_trouble=False, monitoring_station_1_trouble=False, monitoring_station_2_trouble=False, monitoring_station_3_trouble=False, phone_line_trouble=False, clock_trouble=False, box_tamper=False, programming_mode=False, )
Return a mock Config Entry for the Rituals Perfume Genie integration.
def mock_config_entry(unique_id: str, entry_id: str = "an_entry_id") -> MockConfigEntry: """Return a mock Config Entry for the Rituals Perfume Genie integration.""" return MockConfigEntry( domain=DOMAIN, title="[email protected]", unique_id=unique_id, data={ACCOUNT_HASH: "an_account_hash"}, entry_id=entry_id, )
Return a mock Diffuser initialized with the given data.
def mock_diffuser( hublot: str, available: bool = True, battery_percentage: int | Exception = 100, charging: bool | Exception = True, fill: str = "90-100%", has_battery: bool = True, has_cartridge: bool = True, is_on: bool = True, name: str = "Genie", perfume: str = "Ritual of Sakura", perfume_amount: int = 2, room_size_square_meter: int = 60, version: str = "4.0", wifi_percentage: int = 75, ) -> MagicMock: """Return a mock Diffuser initialized with the given data.""" diffuser_mock = MagicMock() diffuser_mock.available = available diffuser_mock.battery_percentage = battery_percentage diffuser_mock.charging = charging diffuser_mock.fill = fill diffuser_mock.has_battery = has_battery diffuser_mock.has_cartridge = has_cartridge diffuser_mock.hublot = hublot diffuser_mock.is_on = is_on diffuser_mock.name = name diffuser_mock.perfume = perfume diffuser_mock.perfume_amount = perfume_amount diffuser_mock.room_size_square_meter = room_size_square_meter diffuser_mock.set_perfume_amount = AsyncMock() diffuser_mock.set_room_size_square_meter = AsyncMock() diffuser_mock.turn_off = AsyncMock() diffuser_mock.turn_on = AsyncMock() diffuser_mock.update_data = AsyncMock() diffuser_mock.version = version diffuser_mock.wifi_percentage = wifi_percentage diffuser_mock.data = load_json_object_fixture("data.json", DOMAIN) return diffuser_mock
Create and return a mock version 1 Diffuser with battery and a cartridge.
def mock_diffuser_v1_battery_cartridge() -> MagicMock: """Create and return a mock version 1 Diffuser with battery and a cartridge.""" return mock_diffuser(hublot="lot123v1")
Create and return a mock version 2 Diffuser without battery and cartridge.
def mock_diffuser_v2_no_battery_no_cartridge() -> MagicMock: """Create and return a mock version 2 Diffuser without battery and cartridge.""" return mock_diffuser( hublot="lot123v2", battery_percentage=Exception(), charging=Exception(), has_battery=False, has_cartridge=False, name="Genie V2", perfume="No Cartridge", version="5.0", )
Mock rmvtransport departures loading.
def get_departures_mock(): """Mock rmvtransport departures loading.""" return { "station": "Frankfurt (Main) Hauptbahnhof", "stationId": "3000010", "filter": "11111111111", "journeys": [ { "product": "Tram", "number": 12, "trainId": "1123456", "direction": "Frankfurt (Main) Hugo-Junkers-Straße/Schleife", "departure_time": datetime.datetime(2018, 8, 6, 14, 21), "minutes": 7, "delay": 3, "stops": [ "Frankfurt (Main) Willy-Brandt-Platz", "Frankfurt (Main) Römer/Paulskirche", "Frankfurt (Main) Börneplatz", "Frankfurt (Main) Konstablerwache", "Frankfurt (Main) Bornheim Mitte", "Frankfurt (Main) Saalburg-/Wittelsbacherallee", "Frankfurt (Main) Eissporthalle/Festplatz", "Frankfurt (Main) Hugo-Junkers-Straße/Schleife", ], "info": None, "info_long": None, "icon": "https://products/32_pic.png", }, { "product": "Bus", "number": 21, "trainId": "1234567", "direction": "Frankfurt (Main) Hugo-Junkers-Straße/Schleife", "departure_time": datetime.datetime(2018, 8, 6, 14, 22), "minutes": 8, "delay": 1, "stops": [ "Frankfurt (Main) Weser-/Münchener Straße", "Frankfurt (Main) Hugo-Junkers-Straße/Schleife", ], "info": None, "info_long": None, "icon": "https://products/32_pic.png", }, { "product": "Bus", "number": 12, "trainId": "1234568", "direction": "Frankfurt (Main) Hugo-Junkers-Straße/Schleife", "departure_time": datetime.datetime(2018, 8, 6, 14, 25), "minutes": 11, "delay": 1, "stops": ["Frankfurt (Main) Stadion"], "info": None, "info_long": None, "icon": "https://products/32_pic.png", }, { "product": "Bus", "number": 21, "trainId": "1234569", "direction": "Frankfurt (Main) Hugo-Junkers-Straße/Schleife", "departure_time": datetime.datetime(2018, 8, 6, 14, 25), "minutes": 11, "delay": 1, "stops": [], "info": None, "info_long": None, "icon": "https://products/32_pic.png", }, { "product": "Bus", "number": 12, "trainId": "1234570", "direction": "Frankfurt (Main) Hugo-Junkers-Straße/Schleife", "departure_time": datetime.datetime(2018, 8, 6, 14, 25), "minutes": 11, "delay": 1, "stops": [], "info": None, "info_long": None, "icon": "https://products/32_pic.png", }, { "product": "Bus", "number": 21, "trainId": "1234571", "direction": "Frankfurt (Main) Hugo-Junkers-Straße/Schleife", "departure_time": datetime.datetime(2018, 8, 6, 14, 25), "minutes": 11, "delay": 1, "stops": [], "info": None, "info_long": None, "icon": "https://products/32_pic.png", }, ], }
Mock no departures in results.
def get_no_departures_mock(): """Mock no departures in results.""" return { "station": "Frankfurt (Main) Hauptbahnhof", "stationId": "3000010", "filter": "11111111111", "journeys": [], }
Skip calls to the API.
def bypass_api_fixture() -> None: """Skip calls to the API.""" with ( patch("homeassistant.components.roborock.RoborockMqttClientV1.async_connect"), patch("homeassistant.components.roborock.RoborockMqttClientV1._send_command"), patch( "homeassistant.components.roborock.RoborockApiClient.get_home_data", return_value=HOME_DATA, ), patch( "homeassistant.components.roborock.RoborockMqttClientV1.get_networking", return_value=NETWORK_INFO, ), patch( "homeassistant.components.roborock.coordinator.RoborockLocalClientV1.get_prop", return_value=PROP, ), patch( "homeassistant.components.roborock.coordinator.RoborockMqttClientV1.get_multi_maps_list", return_value=MULTI_MAP_LIST, ), patch( "homeassistant.components.roborock.coordinator.RoborockLocalClientV1.get_multi_maps_list", return_value=MULTI_MAP_LIST, ), patch( "homeassistant.components.roborock.image.RoborockMapDataParser.parse", return_value=MAP_DATA, ), patch( "homeassistant.components.roborock.coordinator.RoborockLocalClientV1.send_message" ), patch("homeassistant.components.roborock.RoborockMqttClientV1._wait_response"), patch( "homeassistant.components.roborock.coordinator.RoborockLocalClientV1._wait_response" ), patch( "roborock.version_1_apis.AttributeCache.async_value", ), patch( "roborock.version_1_apis.AttributeCache.value", ), patch( "homeassistant.components.roborock.image.MAP_SLEEP", 0, ), patch( "homeassistant.components.roborock.coordinator.RoborockLocalClientV1.get_room_mapping", return_value=[ RoomMapping(16, "2362048"), RoomMapping(17, "2362044"), RoomMapping(18, "2362041"), ], ), patch( "homeassistant.components.roborock.coordinator.RoborockMqttClientV1.get_room_mapping", return_value=[ RoomMapping(16, "2362048"), RoomMapping(17, "2362044"), RoomMapping(18, "2362041"), ], ), ): yield
Create a Roborock Entry that has not been setup.
def mock_roborock_entry(hass: HomeAssistant) -> MockConfigEntry: """Create a Roborock Entry that has not been setup.""" mock_entry = MockConfigEntry( domain=DOMAIN, title=USER_EMAIL, data={ CONF_USERNAME: USER_EMAIL, CONF_USER_DATA: USER_DATA.as_dict(), CONF_BASE_URL: BASE_URL, }, ) mock_entry.add_to_hass(hass) return mock_entry
Get the URL to the application icon.
def app_icon_url(*args, **kwargs): """Get the URL to the application icon.""" app_id = args[0] return f"http://192.168.1.160:8060/query/icon/{app_id}"
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="Roku", domain=DOMAIN, data={CONF_HOST: "192.168.1.160"}, unique_id="1GU48T017973", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[None, None, None]: """Mock setting up a config entry.""" with patch("homeassistant.components.roku.async_setup_entry", return_value=True): yield
Return a mocked Roku client.
def mock_roku_config_flow( mock_device: RokuDevice, ) -> Generator[None, MagicMock, None]: """Return a mocked Roku client.""" with patch( "homeassistant.components.roku.config_flow.Roku", autospec=True ) as roku_mock: client = roku_mock.return_value client.app_icon_url.side_effect = app_icon_url client.update.return_value = mock_device yield client
Return a mocked Roku client.
def mock_roku( request: pytest.FixtureRequest, mock_device: RokuDevice ) -> Generator[None, MagicMock, None]: """Return a mocked Roku client.""" with patch( "homeassistant.components.roku.coordinator.Roku", autospec=True ) as roku_mock: client = roku_mock.return_value client.app_icon_url.side_effect = app_icon_url client.update.return_value = mock_device yield client
Fixture that prevents sleep.
def roomba_no_wake_time(): """Fixture that prevents sleep.""" with patch.object(config_flow, "ROOMBA_WAKE_TIME", 0): yield
Mock a successful Rova API.
def mock_rova(): """Mock a successful Rova API.""" api = MagicMock() with ( patch( "homeassistant.components.rova.config_flow.Rova", return_value=api, ) as api, patch("homeassistant.components.rova.Rova", return_value=api), ): api.is_rova_area.return_value = True api.get_calendar_items.return_value = load_json_array_fixture( "calendar_items.json", DOMAIN ) yield api
Mock config entry.
def mock_config_entry() -> MockConfigEntry: """Mock config entry.""" return MockConfigEntry( domain=DOMAIN, unique_id="8381BE13", title="8381BE 13", data={ CONF_ZIP_CODE: "8381BE", CONF_HOUSE_NUMBER: "13", CONF_HOUSE_NUMBER_SUFFIX: "", }, )
Set up test fixture.
def mock_http_client(event_loop, hass, hass_client): """Set up test fixture.""" loop = event_loop config = { "rss_feed_template": { "testfeed": { "title": "feed title is {{states.test.test1.state}}", "items": [ { "title": "item title is {{states.test.test2.state}}", "description": "desc {{states.test.test3.state}}", } ], } } } loop.run_until_complete(async_setup_component(hass, "rss_feed_template", config)) return loop.run_until_complete(hass_client())
Fixture to set initial config entry options.
def config_entry_options() -> dict[str, Any] | None: """Fixture to set initial config entry options.""" return None
Return a Ruckus Unleashed mock config entry.
def mock_config_entry() -> MockConfigEntry: """Return a Ruckus Unleashed mock config entry.""" return MockConfigEntry( domain=DOMAIN, title=DEFAULT_TITLE, unique_id=DEFAULT_UNIQUEID, data=CONFIG, options=None, )
Mock bluetooth for all tests in this module.
def mock_bluetooth(enable_bluetooth): """Mock bluetooth for all tests in this module."""
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Patch gateway function to return valid data.
def patch_gateway_ok() -> _patch: """Patch gateway function to return valid data.""" return patch( GET_GATEWAY_HISTORY_DATA, return_value=HistoryResponse( timestamp=int(time.time()), gw_mac=GATEWAY_MAC, tags=[], ), )
Patch setup entry to return True.
def patch_setup_entry_ok() -> _patch: """Patch setup entry to return True.""" return patch(ASYNC_SETUP_ENTRY, return_value=True)
Create a mock config entry.
def config_entry(hass: HomeAssistant) -> MockConfigEntry: """Create a mock config entry.""" config_entry = MockConfigEntry( domain=DOMAIN, data=TEST_DATA, unique_id=TEST_DATA[CONF_UNIQUE_ID], ) config_entry.add_to_hass(hass) return config_entry
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.sabnzbd.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.samsungtv.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock network util's async_get_source_ip.
def samsungtv_mock_get_source_ip(mock_get_source_ip): """Mock network util's async_get_source_ip."""
Mock upnp util's async_get_local_ip.
def samsungtv_mock_async_get_local_ip(): """Mock upnp util's async_get_local_ip.""" with patch( "homeassistant.components.samsungtv.media_player.async_get_local_ip", return_value=(AddressFamily.AF_INET, "10.10.10.10"), ): yield
Patch gethostbyname.
def fake_host_fixture() -> None: """Patch gethostbyname.""" with patch( "homeassistant.components.samsungtv.config_flow.socket.gethostbyname", return_value="fake_host", ): yield
Patch APP_LIST_DELAY.
def app_list_delay_fixture() -> None: """Patch APP_LIST_DELAY.""" with patch("homeassistant.components.samsungtv.media_player.APP_LIST_DELAY", 0): yield
Patch UpnpFactory.
def upnp_factory_fixture() -> Mock: """Patch UpnpFactory.""" with patch( "homeassistant.components.samsungtv.media_player.UpnpFactory", autospec=True, ) as upnp_factory_class: upnp_factory: Mock = upnp_factory_class.return_value upnp_factory.async_create_device.side_effect = UpnpConnectionError yield upnp_factory
Patch the samsungctl Remote.
def remote_fixture() -> Mock: """Patch the samsungctl Remote.""" with patch("homeassistant.components.samsungtv.bridge.Remote") as remote_class: remote = Mock(Remote) remote.__enter__ = Mock() remote.__exit__ = Mock() remote_class.return_value = remote yield remote
Patch the samsungtvws SamsungTVAsyncRest.
def rest_api_fixture() -> Mock: """Patch the samsungtvws SamsungTVAsyncRest.""" with patch( "homeassistant.components.samsungtv.bridge.SamsungTVAsyncRest", autospec=True, ) as rest_api_class: rest_api_class.return_value.rest_device_info.return_value = ( SAMPLE_DEVICE_INFO_WIFI ) yield rest_api_class.return_value
Patch the samsungtvws SamsungTVAsyncRest non-ssl only.
def rest_api_fixture_non_ssl_only() -> Mock: """Patch the samsungtvws SamsungTVAsyncRest non-ssl only.""" class MockSamsungTVAsyncRest: """Mock for a MockSamsungTVAsyncRest.""" def __init__(self, host, session, port, timeout): """Mock a MockSamsungTVAsyncRest.""" self.port = port self.host = host async def rest_device_info(self): """Mock rest_device_info to fail for ssl and work for non-ssl.""" if self.port == WEBSOCKET_SSL_PORT: raise ResponseError return SAMPLE_DEVICE_INFO_UE48JU6400 with patch( "homeassistant.components.samsungtv.bridge.SamsungTVAsyncRest", MockSamsungTVAsyncRest, ): yield
Patch the samsungtvws SamsungTVAsyncRest.
def rest_api_failure_fixture() -> Mock: """Patch the samsungtvws SamsungTVAsyncRest.""" with patch( "homeassistant.components.samsungtv.bridge.SamsungTVAsyncRest", autospec=True, ) as rest_api_class: rest_api_class.return_value.rest_device_info.side_effect = ResponseError yield
Patch the samsungtvws SamsungTVEncryptedWSAsyncRemote.
def remoteencws_failing_fixture(): """Patch the samsungtvws SamsungTVEncryptedWSAsyncRemote.""" with patch( "homeassistant.components.samsungtv.bridge.SamsungTVEncryptedWSAsyncRemote.start_listening", side_effect=OSError, ): yield
Patch the samsungtvws SamsungTVWS.
def remotews_fixture() -> Mock: """Patch the samsungtvws SamsungTVWS.""" remotews = Mock(SamsungTVWSAsyncRemote) remotews.__aenter__ = AsyncMock(return_value=remotews) remotews.__aexit__ = AsyncMock() remotews.token = "FAKE_TOKEN" remotews.app_list_data = None async def _start_listening( ws_event_callback: Callable[[str, Any], Awaitable[None] | None] | None = None, ): remotews.ws_event_callback = ws_event_callback async def _send_commands(commands: list[SamsungTVCommand]): if ( len(commands) == 1 and isinstance(commands[0], ChannelEmitCommand) and commands[0].params["event"] == "ed.installedApp.get" and remotews.app_list_data is not None ): remotews.raise_mock_ws_event_callback( ED_INSTALLED_APP_EVENT, remotews.app_list_data, ) def _mock_ws_event_callback(event: str, response: Any): if remotews.ws_event_callback: remotews.ws_event_callback(event, response) remotews.start_listening.side_effect = _start_listening remotews.send_commands.side_effect = _send_commands remotews.raise_mock_ws_event_callback = Mock(side_effect=_mock_ws_event_callback) with patch( "homeassistant.components.samsungtv.bridge.SamsungTVWSAsyncRemote", ) as remotews_class: remotews_class.return_value = remotews yield remotews
Patch the samsungtvws SamsungTVEncryptedWSAsyncRemote.
def remoteencws_fixture() -> Mock: """Patch the samsungtvws SamsungTVEncryptedWSAsyncRemote.""" remoteencws = Mock(SamsungTVEncryptedWSAsyncRemote) remoteencws.__aenter__ = AsyncMock(return_value=remoteencws) remoteencws.__aexit__ = AsyncMock() def _start_listening( ws_event_callback: Callable[[str, Any], Awaitable[None] | None] | None = None, ): remoteencws.ws_event_callback = ws_event_callback def _mock_ws_event_callback(event: str, response: Any): if remoteencws.ws_event_callback: remoteencws.ws_event_callback(event, response) remoteencws.start_listening.side_effect = _start_listening remoteencws.raise_mock_ws_event_callback = Mock(side_effect=_mock_ws_event_callback) with patch( "homeassistant.components.samsungtv.bridge.SamsungTVEncryptedWSAsyncRemote", ) as remotews_class: remotews_class.return_value = remoteencws yield remoteencws
Fixture for dtutil.now.
def mock_now() -> datetime: """Fixture for dtutil.now.""" return dt_util.utcnow()
Patch getmac.get_mac_address.
def mac_address_fixture() -> Mock: """Patch getmac.get_mac_address.""" with patch("getmac.get_mac_address", return_value=None) as mac: yield mac
Track calls to a mock service.
def calls(hass: HomeAssistant) -> list[ServiceCall]: """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Build a fixture for the Sanix API that connects successfully and returns measurements.
def mock_sanix(): """Build a fixture for the Sanix API that connects successfully and returns measurements.""" fixture = load_json_object_fixture("get_measurements.json", DOMAIN) with ( patch( "homeassistant.components.sanix.config_flow.Sanix", autospec=True, ) as mock_sanix_api, patch( "homeassistant.components.sanix.Sanix", new=mock_sanix_api, ), ): mock_sanix_api.return_value.fetch_data.return_value = Measurement( battery=fixture[ATTR_API_BATTERY], device_no=fixture[ATTR_API_DEVICE_NO], distance=fixture[ATTR_API_DISTANCE], fill_perc=fixture[ATTR_API_FILL_PERC], service_date=datetime.strptime( fixture[ATTR_API_SERVICE_DATE], "%d.%m.%Y" ).date(), ssid=fixture[ATTR_API_SSID], status=fixture[ATTR_API_STATUS], time=datetime.strptime(fixture[ATTR_API_TIME], "%d.%m.%Y %H:%M:%S").replace( tzinfo=ZoneInfo("Europe/Warsaw") ), ) yield mock_sanix_api
Mock a config entry.
def mock_config_entry() -> MockConfigEntry: """Mock a config entry.""" return MockConfigEntry( domain=DOMAIN, title="Sanix", unique_id="1810088", data={CONF_SERIAL_NUMBER: "1234", CONF_TOKEN: "abcd"}, )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.sanix.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Activate a scene.
def activate(hass, entity_id=ENTITY_MATCH_ALL): """Activate a scene.""" data = {} if entity_id: data[ATTR_ENTITY_ID] = entity_id hass.services.call(DOMAIN, SERVICE_TURN_ON, data)
Initialize the test light.
def entities( hass: HomeAssistant, mock_light_entities: list[MockLight], ) -> list[MockLight]: """Initialize the test light.""" entities = mock_light_entities[0:2] setup_test_component_platform(hass, light.DOMAIN, entities) return entities
Schedule setup.
def schedule_setup( hass: HomeAssistant, hass_storage: dict[str, Any] ) -> Callable[..., Coroutine[Any, Any, bool]]: """Schedule setup.""" async def _schedule_setup( items: dict[str, Any] | None = None, config: dict[str, Any] | None = None, ) -> bool: if items is None: hass_storage[DOMAIN] = { "key": DOMAIN, "version": STORAGE_VERSION, "minor_version": STORAGE_VERSION_MINOR, "data": { "items": [ { CONF_ID: "from_storage", CONF_NAME: "from storage", CONF_ICON: "mdi:party-popper", CONF_FRIDAY: [ {CONF_FROM: "17:00:00", CONF_TO: "23:59:59"}, ], CONF_SATURDAY: [ {CONF_FROM: "00:00:00", CONF_TO: "23:59:59"}, ], CONF_SUNDAY: [ {CONF_FROM: "00:00:00", CONF_TO: "24:00:00"}, ], } ] }, } else: hass_storage[DOMAIN] = { "key": DOMAIN, "version": 1, "minor_version": STORAGE_VERSION_MINOR, "data": {"items": items}, } if config is None: config = { DOMAIN: { "from_yaml": { CONF_NAME: "from yaml", CONF_ICON: "mdi:party-pooper", CONF_MONDAY: [{CONF_FROM: "00:00:00", CONF_TO: "23:59:59"}], CONF_TUESDAY: [{CONF_FROM: "00:00:00", CONF_TO: "23:59:59"}], CONF_WEDNESDAY: [{CONF_FROM: "00:00:00", CONF_TO: "23:59:59"}], CONF_THURSDAY: [{CONF_FROM: "00:00:00", CONF_TO: "23:59:59"}], CONF_FRIDAY: [{CONF_FROM: "00:00:00", CONF_TO: "23:59:59"}], CONF_SATURDAY: [{CONF_FROM: "00:00:00", CONF_TO: "23:59:59"}], CONF_SUNDAY: [{CONF_FROM: "00:00:00", CONF_TO: "23:59:59"}], } } } return await async_setup_component(hass, DOMAIN, config) return _schedule_setup
Mock ConfigEntry.
def mock_config_entry() -> MockConfigEntry: """Mock ConfigEntry.""" return MockConfigEntry( title="[email protected]", domain=DOMAIN, data={ CONF_USERNAME: "[email protected]", CONF_PASSWORD: "hunter2", }, unique_id="abc123", )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.schlage.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock pyschlage.Schlage.
def mock_schlage() -> Mock: """Mock pyschlage.Schlage.""" with patch("pyschlage.Schlage", autospec=True) as mock_schlage: yield mock_schlage.return_value
Mock pyschlage.Auth.
def mock_pyschlage_auth() -> Mock: """Mock pyschlage.Auth.""" with patch("pyschlage.Auth", autospec=True) as mock_auth: mock_auth.return_value.user_id = "abc123" yield mock_auth.return_value
Mock Lock fixture.
def mock_lock() -> Mock: """Mock Lock fixture.""" mock_lock = create_autospec(Lock) mock_lock.configure_mock( device_id="test", name="Vault Door", model_name="<model-name>", is_locked=False, is_jammed=False, battery_level=20, firmware_version="1.0", lock_and_leave_enabled=True, beeper_enabled=True, ) mock_lock.logs.return_value = [] mock_lock.last_changed_by.return_value = "thumbturn" mock_lock.keypad_disabled.return_value = False return mock_lock
Automatically path uuid generator.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Automatically path uuid generator.""" with patch( "homeassistant.components.scrape.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Automatically path uuid generator.
def uuid_fixture() -> str: """Automatically path uuid generator.""" with patch( "homeassistant.components.scrape.config_flow.uuid.uuid1", return_value=uuid.UUID("3699ef88-69e6-11ed-a1eb-0242ac120002"), ): yield
Return config.
def return_integration_config( *, authentication=None, username=None, password=None, headers=None, sensors=None, ) -> dict[str, dict[str, Any]]: """Return config.""" config = { "resource": "https://www.home-assistant.io", "verify_ssl": True, "sensor": sensors, } if authentication: config["authentication"] = authentication if username: config["username"] = username config["password"] = password if headers: config["headers"] = headers return config
Return a mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return a mocked config entry.""" return MockConfigEntry( title=MOCK_ADAPTER_NAME, domain=DOMAIN, data={ CONF_IP_ADDRESS: MOCK_ADAPTER_IP, CONF_PORT: MOCK_ADAPTER_PORT, }, options={ CONF_SCAN_INTERVAL: 30, }, unique_id=MOCK_ADAPTER_MAC, entry_id="screenlogictest", )
Convert all string number dict keys to integer. This needed for screenlogicpy's data dict format.
def num_key_string_to_int(data: dict) -> None: """Convert all string number dict keys to integer. This needed for screenlogicpy's data dict format. """ rpl = [] for key, value in data.items(): if isinstance(value, dict): num_key_string_to_int(value) if isinstance(key, str) and key.isnumeric(): rpl.append(key) for k in rpl: data[int(k)] = data.pop(k) return data
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""
Patch blueprint loading from a different source.
def patch_blueprint(blueprint_path: str, data_path: str) -> Iterator[None]: """Patch blueprint loading from a different source.""" orig_load = DomainBlueprints._load_blueprint @callback def mock_load_blueprint(self, path: str) -> Blueprint: if path != blueprint_path: pytest.fail(f"Unexpected blueprint {path}") return orig_load(self, path) return Blueprint( yaml.load_yaml(data_path), expected_domain=self.domain, path=path ) with patch( "homeassistant.components.blueprint.models.DomainBlueprints._load_blueprint", mock_load_blueprint, ): yield
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "script")
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="Season", domain=DOMAIN, data={CONF_TYPE: TYPE_ASTRONOMICAL}, unique_id=TYPE_ASTRONOMICAL, )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[None, None, None]: """Mock setting up a config entry.""" with patch("homeassistant.components.season.async_setup_entry", return_value=True): yield