response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Perform common setup tasks for the tests.
def _setup(config) -> tuple[str, str, MockConfigEntry]: """Perform common setup tasks for the tests.""" patch_key = config[ADB_PATCH_KEY] entity_id = f"{MP_DOMAIN}.{slugify(config[TEST_ENTITY_NAME])}" config_entry = MockConfigEntry( domain=DOMAIN, data=config[DOMAIN], unique_id="a1:b1:c1:d1:e1:f1", ) return patch_key, entity_id, config_entry
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.androidtv_remote.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Mock unloading a config entry.
def mock_unload_entry() -> Generator[AsyncMock, None, None]: """Mock unloading a config entry.""" with patch( "homeassistant.components.androidtv_remote.async_unload_entry", return_value=True, ) as mock_unload_entry: yield mock_unload_entry
Return a mocked AndroidTVRemote.
def mock_api() -> Generator[None, MagicMock, None]: """Return a mocked AndroidTVRemote.""" with patch( "homeassistant.components.androidtv_remote.helpers.AndroidTVRemote", ) as mock_api_cl: mock_api = mock_api_cl.return_value mock_api.async_connect = AsyncMock(return_value=None) mock_api.device_info = { "manufacturer": "My Android TV manufacturer", "model": "My Android TV model", } is_on_updated_callbacks: list[Callable] = [] current_app_updated_callbacks: list[Callable] = [] volume_info_updated_callbacks: list[Callable] = [] is_available_updated_callbacks: list[Callable] = [] def mocked_add_is_on_updated_callback(callback: Callable): is_on_updated_callbacks.append(callback) def mocked_add_current_app_updated_callback(callback: Callable): current_app_updated_callbacks.append(callback) def mocked_add_volume_info_updated_callback(callback: Callable): volume_info_updated_callbacks.append(callback) def mocked_add_is_available_updated_callbacks(callback: Callable): is_available_updated_callbacks.append(callback) def mocked_is_on_updated(is_on: bool): for callback in is_on_updated_callbacks: callback(is_on) def mocked_current_app_updated(current_app: str): for callback in current_app_updated_callbacks: callback(current_app) def mocked_volume_info_updated(volume_info: dict[str, str | bool]): for callback in volume_info_updated_callbacks: callback(volume_info) def mocked_is_available_updated(is_available: bool): for callback in is_available_updated_callbacks: callback(is_available) mock_api.add_is_on_updated_callback.side_effect = ( mocked_add_is_on_updated_callback ) mock_api.add_current_app_updated_callback.side_effect = ( mocked_add_current_app_updated_callback ) mock_api.add_volume_info_updated_callback.side_effect = ( mocked_add_volume_info_updated_callback ) mock_api.add_is_available_updated_callback.side_effect = ( mocked_add_is_available_updated_callbacks ) mock_api._on_is_on_updated.side_effect = mocked_is_on_updated mock_api._on_current_app_updated.side_effect = mocked_current_app_updated mock_api._on_volume_info_updated.side_effect = mocked_volume_info_updated mock_api._on_is_available_updated.side_effect = mocked_is_available_updated yield mock_api
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="My Android TV", domain=DOMAIN, data={"host": "1.2.3.4", "name": "My Android TV", "mac": "1A:2B:3C:4D:5E:6F"}, unique_id="1a:2b:3c:4d:5e:6f", state=ConfigEntryState.NOT_LOADED, )
Fixture to provide a aioclient mocker.
def aioclient_mock_fixture(aioclient_mock) -> None: """Fixture to provide a aioclient mocker.""" aioclient_mock.get( "http://1.1.1.1:8080/status.json?show_avail=1", text=load_fixture("android_ip_webcam/status_data.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.get( "http://1.1.1.1:8080/sensors.json", text=load_fixture("android_ip_webcam/sensor_data.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, )
Add config entry in Home Assistant.
def create_entry(hass: HomeAssistant, device_id: str = DEVICE_UNIQUE_ID) -> ConfigEntry: """Add config entry in Home Assistant.""" entry = MockConfigEntry( domain=DOMAIN, title="Anova", data={ CONF_USERNAME: "[email protected]", CONF_PASSWORD: "sample", "devices": [(device_id, "type_sample")], }, unique_id="[email protected]", ) entry.add_to_hass(hass) return entry
Return the default mocked anthemav.
def mock_anthemav() -> AsyncMock: """Return the default mocked anthemav.""" avr = AsyncMock() avr.protocol.macaddress = "000000000001" avr.protocol.model = "MRX 520" avr.reconnect = AsyncMock() avr.protocol.wait_for_device_initialised = AsyncMock() avr.close = MagicMock() avr.protocol.input_list = [] avr.protocol.audio_listening_mode_list = [] avr.protocol.zones = {1: get_zone(), 2: get_zone()} return avr
Return a mocked zone.
def get_zone() -> MagicMock: """Return a mocked zone.""" zone = MagicMock() zone.power = False return zone
Return the default mocked connection.create.
def mock_connection_create(mock_anthemav: AsyncMock) -> AsyncMock: """Return the default mocked connection.create.""" with patch( "anthemav.Connection.create", return_value=mock_anthemav, ) as mock: yield mock
Return the update_callback used when creating the connection.
def update_callback(mock_connection_create: AsyncMock) -> Callable[[str], None]: """Return the update_callback used when creating the connection.""" return mock_connection_create.call_args[1]["update_callback"]
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( domain=DOMAIN, title="Anthem AV", data={ CONF_HOST: "1.1.1.1", CONF_PORT: 14999, CONF_MAC: "00:00:00:00:00:01", CONF_MODEL: "MRX 520", }, unique_id="00:00:00:00:00:01", )
Build a fixture for a device.
def build_device_fixture( heat_pump: bool, mode_pending: bool, setpoint_pending: bool, has_vacation_mode: bool ): """Build a fixture for a device.""" supported_modes: list[SupportedOperationModeInfo] = [ SupportedOperationModeInfo( mode=OperationMode.ELECTRIC, original_name="ELECTRIC", has_day_selection=True, ), ] if heat_pump: supported_modes.append( SupportedOperationModeInfo( mode=OperationMode.HYBRID, original_name="HYBRID", has_day_selection=False, ) ) supported_modes.append( SupportedOperationModeInfo( mode=OperationMode.HEAT_PUMP, original_name="HEAT_PUMP", has_day_selection=False, ) ) if has_vacation_mode: supported_modes.append( SupportedOperationModeInfo( mode=OperationMode.VACATION, original_name="VACATION", has_day_selection=True, ) ) device_type = ( DeviceType.NEXT_GEN_HEAT_PUMP if heat_pump else DeviceType.RE3_CONNECTED ) current_mode = OperationMode.HEAT_PUMP if heat_pump else OperationMode.ELECTRIC model = "HPTS-50 200 202172000" if heat_pump else "EE12-50H55DVF 100,3806368" return Device( brand="aosmith", model=model, device_type=device_type, dsn="dsn", junction_id="junctionId", name="My water heater", serial="serial", install_location="Basement", supported_modes=supported_modes, status=DeviceStatus( firmware_version="2.14", is_online=True, current_mode=current_mode, mode_change_pending=mode_pending, temperature_setpoint=130, temperature_setpoint_pending=setpoint_pending, temperature_setpoint_previous=130, temperature_setpoint_maximum=130, hot_water_status=HotWaterStatus.LOW, ), )
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( domain=DOMAIN, data=FIXTURE_USER_INPUT, unique_id=FIXTURE_USER_INPUT[CONF_EMAIL], )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.aosmith.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Return whether the device in the get_devices fixture should be a heat pump water heater.
def get_devices_fixture_heat_pump() -> bool: """Return whether the device in the get_devices fixture should be a heat pump water heater.""" return True
Return whether to set mode_pending in the get_devices fixture.
def get_devices_fixture_mode_pending() -> bool: """Return whether to set mode_pending in the get_devices fixture.""" return False
Return whether to set setpoint_pending in the get_devices fixture.
def get_devices_fixture_setpoint_pending() -> bool: """Return whether to set setpoint_pending in the get_devices fixture.""" return False
Return whether to include vacation mode in the get_devices fixture.
def get_devices_fixture_has_vacation_mode() -> bool: """Return whether to include vacation mode in the get_devices fixture.""" return True
Mock the apache kafka client.
def mock_client_fixture(): """Mock the apache kafka client.""" with ( patch(f"{PRODUCER_PATH}.start") as start, patch(f"{PRODUCER_PATH}.send_and_wait") as send_and_wait, patch(f"{PRODUCER_PATH}.__init__", return_value=None) as init, ): yield MockKafkaClient(init, start, send_and_wait)
Mock client stop at module scope for teardown.
def mock_client_stop(): """Mock client stop at module scope for teardown.""" with patch(f"{PRODUCER_PATH}.stop") as stop: yield stop
Start the Home Assistant HTTP component and return admin API client.
def mock_api_client( hass: HomeAssistant, hass_client: ClientSessionGenerator ) -> TestClient: """Start the Home Assistant HTTP component and return admin API client.""" hass.loop.run_until_complete(async_setup_component(hass, "api", {})) return hass.loop.run_until_complete(hass_client())
Return number of event listeners.
def _listen_count(hass: HomeAssistant) -> int: """Return number of event listeners.""" return sum(hass.bus.async_listeners().values())
Create an Apple TV configuration.
def create_conf(name, address, *services): """Create an Apple TV configuration.""" atv = conf.AppleTV(name, address) for service in services: atv.add_service(service) return atv
Create example MRP service.
def mrp_service(enabled=True, unique_id="mrpid"): """Create example MRP service.""" return conf.ManualService( unique_id, Protocol.MRP, 5555, {}, pairing_requirement=const.PairingRequirement.Mandatory, enabled=enabled, )
Create example AirPlay service.
def airplay_service(): """Create example AirPlay service.""" return conf.ManualService( "airplayid", Protocol.AirPlay, 7777, {}, pairing_requirement=const.PairingRequirement.Mandatory, )
Create example RAOP service.
def raop_service(): """Create example RAOP service.""" return conf.ManualService( "AABBCCDDEEFF", Protocol.RAOP, 7000, {}, pairing_requirement=const.PairingRequirement.Mandatory, )
Mock pyatv.scan.
def mock_scan_fixture(): """Mock pyatv.scan.""" with patch("homeassistant.components.apple_tv.config_flow.scan") as mock_scan: async def _scan( loop, timeout=5, identifier=None, protocol=None, hosts=None, aiozc=None ): if not mock_scan.hosts: mock_scan.hosts = hosts return mock_scan.result mock_scan.result = [] mock_scan.hosts = None mock_scan.side_effect = _scan yield mock_scan
Mock pyatv.scan.
def dmap_pin_fixture(): """Mock pyatv.scan.""" with patch("homeassistant.components.apple_tv.config_flow.randrange") as mock_pin: mock_pin.side_effect = lambda start, stop: 1111 yield mock_pin
Mock pyatv.scan.
def pairing(): """Mock pyatv.scan.""" with patch("homeassistant.components.apple_tv.config_flow.pair") as mock_pair: async def _pair(config, protocol, loop, session=None, **kwargs): handler = MockPairingHandler( await http.create_session(session), config.get_service(protocol) ) handler.always_fail = mock_pair.always_fail return handler mock_pair.always_fail = False mock_pair.side_effect = _pair yield mock_pair
Mock pyatv.scan.
def pairing_mock(): """Mock pyatv.scan.""" with patch("homeassistant.components.apple_tv.config_flow.pair") as mock_pair: async def _pair(config, protocol, loop, session=None, **kwargs): return mock_pair async def _begin(): pass async def _close(): pass mock_pair.close.side_effect = _close mock_pair.begin.side_effect = _begin mock_pair.pin = lambda pin: None mock_pair.side_effect = _pair yield mock_pair
Mock pyatv.scan.
def full_device(mock_scan, dmap_pin): """Mock pyatv.scan.""" mock_scan.result.append( create_conf( "127.0.0.1", "MRP Device", mrp_service(), conf.ManualService( "dmapid", Protocol.DMAP, 6666, {}, pairing_requirement=PairingRequirement.Mandatory, ), airplay_service(), ) ) return mock_scan
Mock pyatv.scan.
def mrp_device(mock_scan): """Mock pyatv.scan.""" mock_scan.result.extend( [ create_conf( "127.0.0.1", "MRP Device", mrp_service(), ), create_conf( "127.0.0.2", "MRP Device 2", mrp_service(unique_id="unrelated"), ), ] ) return mock_scan
Mock pyatv.scan.
def airplay_with_disabled_mrp(mock_scan): """Mock pyatv.scan.""" mock_scan.result.append( create_conf( "127.0.0.1", "AirPlay Device", mrp_service(enabled=False), conf.ManualService( "airplayid", Protocol.AirPlay, 7777, {}, pairing_requirement=PairingRequirement.Mandatory, ), ) ) return mock_scan
Mock pyatv.scan.
def dmap_device(mock_scan): """Mock pyatv.scan.""" mock_scan.result.append( create_conf( "127.0.0.1", "DMAP Device", conf.ManualService( "dmapid", Protocol.DMAP, 6666, {}, credentials=None, pairing_requirement=PairingRequirement.Mandatory, ), ) ) return mock_scan
Mock pyatv.scan.
def dmap_device_with_credentials(mock_scan): """Mock pyatv.scan.""" mock_scan.result.append( create_conf( "127.0.0.1", "DMAP Device", conf.ManualService( "dmapid", Protocol.DMAP, 6666, {}, credentials="dummy_creds", pairing_requirement=PairingRequirement.NotNeeded, ), ) ) return mock_scan
Mock pyatv.scan.
def airplay_device_with_password(mock_scan): """Mock pyatv.scan.""" mock_scan.result.append( create_conf( "127.0.0.1", "AirPlay Device", conf.ManualService( "airplayid", Protocol.AirPlay, 7777, {}, requires_password=True ), ) ) return mock_scan
Mock pyatv.scan.
def dmap_with_requirement(mock_scan, pairing_requirement): """Mock pyatv.scan.""" mock_scan.result.append( create_conf( "127.0.0.1", "DMAP Device", conf.ManualService( "dmapid", Protocol.DMAP, 6666, {}, pairing_requirement=pairing_requirement, ), ) ) return mock_scan
Prevent the aggregation time from delaying the tests.
def zero_aggregation_time(): """Prevent the aggregation time from delaying the tests.""" with patch.object(config_flow, "DISCOVERY_AGGREGATION_TIME", 0): yield
Mock zeroconf in all tests.
def use_mocked_zeroconf(mock_async_zeroconf): """Mock zeroconf in all tests."""
Mock setting up a config entry.
def mock_setup_entry(): """Mock setting up a config entry.""" with patch( "homeassistant.components.apple_tv.async_setup_entry", return_value=True ): yield
Fixture for a test config flow.
def config_flow_handler( hass: HomeAssistant, current_request_with_host: Any ) -> Generator[FakeConfigFlow, None, None]: """Fixture for a test config flow.""" mock_platform(hass, f"{TEST_DOMAIN}.config_flow") with mock_config_flow(TEST_DOMAIN, FakeConfigFlow): yield
Return a mock client.
def client() -> AprilaireClient: """Return a mock client.""" return AsyncMock(AprilaireClient)
Mock aprslib.
def mock_ais() -> Generator[MagicMock, None, None]: """Mock aprslib.""" with patch("aprslib.IS") as mock_ais: yield mock_ais
Test filter.
def test_make_filter() -> None: """Test filter.""" callsigns = ["CALLSIGN1", "callsign2"] res = device_tracker.make_filter(callsigns) assert res == "b/CALLSIGN1 b/CALLSIGN2"
Test GPS accuracy level 0.
def test_gps_accuracy_0() -> None: """Test GPS accuracy level 0.""" acc = device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, 0) assert acc == 0
Test GPS accuracy level 1.
def test_gps_accuracy_1() -> None: """Test GPS accuracy level 1.""" acc = device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, 1) assert acc == 186
Test GPS accuracy level 2.
def test_gps_accuracy_2() -> None: """Test GPS accuracy level 2.""" acc = device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, 2) assert acc == 1855
Test GPS accuracy level 3.
def test_gps_accuracy_3() -> None: """Test GPS accuracy level 3.""" acc = device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, 3) assert acc == 18553
Test GPS accuracy level 4.
def test_gps_accuracy_4() -> None: """Test GPS accuracy level 4.""" acc = device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, 4) assert acc == 111319
Test GPS accuracy with invalid input.
def test_gps_accuracy_invalid_int() -> None: """Test GPS accuracy with invalid input.""" level = 5 try: device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level) pytest.fail("No exception.") except ValueError: pass
Test GPS accuracy with invalid input.
def test_gps_accuracy_invalid_string() -> None: """Test GPS accuracy with invalid input.""" level = "not an int" try: device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level) pytest.fail("No exception.") except ValueError: pass
Test GPS accuracy with invalid input.
def test_gps_accuracy_invalid_float() -> None: """Test GPS accuracy with invalid input.""" level = 1.2 try: device_tracker.gps_accuracy(TEST_COORDS_NULL_ISLAND, level) pytest.fail("No exception.") except ValueError: pass
Test listener thread.
def test_aprs_listener(mock_ais: MagicMock) -> None: """Test listener thread.""" callsign = TEST_CALLSIGN password = TEST_PASSWORD host = TEST_HOST server_filter = TEST_FILTER port = DEFAULT_PORT see = Mock() listener = device_tracker.AprsListenerThread( callsign, password, host, server_filter, see ) listener.run() assert listener.callsign == callsign assert listener.host == host assert listener.server_filter == server_filter assert listener.see == see assert listener.start_event.is_set() assert listener.start_success assert listener.start_message == "Connected to testhost with callsign testcall." mock_ais.assert_called_with(callsign, passwd=password, host=host, port=port)
Test listener thread start failure.
def test_aprs_listener_start_fail() -> None: """Test listener thread start failure.""" with patch.object( IS, "connect", side_effect=aprslib.ConnectionError("Unable to connect.") ): callsign = TEST_CALLSIGN password = TEST_PASSWORD host = TEST_HOST server_filter = TEST_FILTER see = Mock() listener = device_tracker.AprsListenerThread( callsign, password, host, server_filter, see ) listener.run() assert listener.callsign == callsign assert listener.host == host assert listener.server_filter == server_filter assert listener.see == see assert listener.start_event.is_set() assert not listener.start_success assert listener.start_message == "Unable to connect."
Test listener thread stop.
def test_aprs_listener_stop(mock_ais: MagicMock) -> None: """Test listener thread stop.""" callsign = TEST_CALLSIGN password = TEST_PASSWORD host = TEST_HOST server_filter = TEST_FILTER see = Mock() listener = device_tracker.AprsListenerThread( callsign, password, host, server_filter, see ) listener.ais.close = Mock() listener.run() listener.stop() assert listener.callsign == callsign assert listener.host == host assert listener.server_filter == server_filter assert listener.see == see assert listener.start_event.is_set() assert listener.start_message == "Connected to testhost with callsign testcall." assert listener.start_success listener.ais.close.assert_called_with()
Test rx_msg.
def test_aprs_listener_rx_msg(mock_ais: MagicMock) -> None: """Test rx_msg.""" callsign = TEST_CALLSIGN password = TEST_PASSWORD host = TEST_HOST server_filter = TEST_FILTER see = Mock() sample_msg = { device_tracker.ATTR_FORMAT: "uncompressed", device_tracker.ATTR_FROM: "ZZ0FOOBAR-1", device_tracker.ATTR_LATITUDE: 0.0, device_tracker.ATTR_LONGITUDE: 0.0, device_tracker.ATTR_ALTITUDE: 0, } listener = device_tracker.AprsListenerThread( callsign, password, host, server_filter, see ) listener.run() listener.rx_msg(sample_msg) assert listener.callsign == callsign assert listener.host == host assert listener.server_filter == server_filter assert listener.see == see assert listener.start_event.is_set() assert listener.start_success assert listener.start_message == "Connected to testhost with callsign testcall." see.assert_called_with( dev_id=device_tracker.slugify("ZZ0FOOBAR-1"), gps=(0.0, 0.0), attributes={"altitude": 0}, )
Test rx_msg with posambiguity.
def test_aprs_listener_rx_msg_ambiguity(mock_ais: MagicMock) -> None: """Test rx_msg with posambiguity.""" callsign = TEST_CALLSIGN password = TEST_PASSWORD host = TEST_HOST server_filter = TEST_FILTER see = Mock() sample_msg = { device_tracker.ATTR_FORMAT: "uncompressed", device_tracker.ATTR_FROM: "ZZ0FOOBAR-1", device_tracker.ATTR_LATITUDE: 0.0, device_tracker.ATTR_LONGITUDE: 0.0, device_tracker.ATTR_POS_AMBIGUITY: 1, } listener = device_tracker.AprsListenerThread( callsign, password, host, server_filter, see ) listener.run() listener.rx_msg(sample_msg) assert listener.callsign == callsign assert listener.host == host assert listener.server_filter == server_filter assert listener.see == see assert listener.start_event.is_set() assert listener.start_success assert listener.start_message == "Connected to testhost with callsign testcall." see.assert_called_with( dev_id=device_tracker.slugify("ZZ0FOOBAR-1"), gps=(0.0, 0.0), attributes={device_tracker.ATTR_GPS_ACCURACY: 186}, )
Test rx_msg with invalid posambiguity.
def test_aprs_listener_rx_msg_ambiguity_invalid(mock_ais: MagicMock) -> None: """Test rx_msg with invalid posambiguity.""" callsign = TEST_CALLSIGN password = TEST_PASSWORD host = TEST_HOST server_filter = TEST_FILTER see = Mock() sample_msg = { device_tracker.ATTR_FORMAT: "uncompressed", device_tracker.ATTR_FROM: "ZZ0FOOBAR-1", device_tracker.ATTR_LATITUDE: 0.0, device_tracker.ATTR_LONGITUDE: 0.0, device_tracker.ATTR_POS_AMBIGUITY: 5, } listener = device_tracker.AprsListenerThread( callsign, password, host, server_filter, see ) listener.run() listener.rx_msg(sample_msg) assert listener.callsign == callsign assert listener.host == host assert listener.server_filter == server_filter assert listener.see == see assert listener.start_event.is_set() assert listener.start_success assert listener.start_message == "Connected to testhost with callsign testcall." see.assert_called_with( dev_id=device_tracker.slugify("ZZ0FOOBAR-1"), gps=(0.0, 0.0), attributes={} )
Test rx_msg with non-position report.
def test_aprs_listener_rx_msg_no_position(mock_ais: MagicMock) -> None: """Test rx_msg with non-position report.""" callsign = TEST_CALLSIGN password = TEST_PASSWORD host = TEST_HOST server_filter = TEST_FILTER see = Mock() sample_msg = {device_tracker.ATTR_FORMAT: "invalid"} listener = device_tracker.AprsListenerThread( callsign, password, host, server_filter, see ) listener.run() listener.rx_msg(sample_msg) assert listener.callsign == callsign assert listener.host == host assert listener.server_filter == server_filter assert listener.see == see assert listener.start_event.is_set() assert listener.start_success assert listener.start_message == "Connected to testhost with callsign testcall." see.assert_not_called()
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Return a BluetoothServiceInfoBleak for use in testing.
def fake_service_info(name, service_uuid, manufacturer_data): """Return a BluetoothServiceInfoBleak for use in testing.""" return BluetoothServiceInfoBleak( name=name, address="aa:bb:cc:dd:ee:ff", rssi=-60, manufacturer_data=manufacturer_data, service_data={}, service_uuids=[service_uuid], source="local", connectable=False, time=time(), device=generate_ble_device("aa:bb:cc:dd:ee:ff", name=name), advertisement=AdvertisementData( local_name=name, manufacturer_data=manufacturer_data, service_data={}, service_uuids=[service_uuid], rssi=-60, tx_power=-127, platform_data=(), ), )
Get a mocked client.
def client_fixture(): """Get a mocked client.""" client = Mock(Client) client.host = MOCK_HOST client.port = MOCK_PORT return client
Get a mocked state.
def state_1_fixture(client): """Get a mocked state.""" state = Mock(State) state.client = client state.zn = 1 state.get_power.return_value = True state.get_volume.return_value = 0.0 state.get_source_list.return_value = [] state.get_incoming_audio_format.return_value = (0, 0) state.get_mute.return_value = None state.get_decode_modes.return_value = [] return state
Get a mocked state.
def state_2_fixture(client): """Get a mocked state.""" state = Mock(State) state.client = client state.zn = 2 state.get_power.return_value = True state.get_volume.return_value = 0.0 state.get_source_list.return_value = [] state.get_incoming_audio_format.return_value = (0, 0) state.get_mute.return_value = None state.get_decode_modes.return_value = [] return state
Get a mocked state.
def state_fixture(state_1): """Get a mocked state.""" return state_1
Get standard player.
def player_fixture(hass, state): """Get standard player.""" player = ArcamFmj(MOCK_NAME, state, MOCK_UUID) player.entity_id = MOCK_ENTITY_ID player.hass = hass player.platform = MockEntityPlatform(hass) player.async_write_ha_state = Mock() return player
Mock out the real client.
def dummy_client_fixture(hass): """Mock out the real client.""" with patch("homeassistant.components.arcam_fmj.config_flow.Client") as client: client.return_value.start.side_effect = AsyncMock(return_value=None) client.return_value.stop.side_effect = AsyncMock(return_value=None) yield client.return_value
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder."""
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.arve.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Return the default mocked config entry.
def mock_config_entry(hass: HomeAssistant, mock_arve: MagicMock) -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="Arve", domain=DOMAIN, data=USER_INPUT, unique_id=mock_arve.customer_id )
Return a mocked Arve client.
def mock_arve(): """Return a mocked Arve client.""" with ( patch( "homeassistant.components.arve.coordinator.Arve", autospec=True ) as arve_mock, patch("homeassistant.components.arve.config_flow.Arve", new=arve_mock), ): arve = arve_mock.return_value arve.customer_id = 12345 arve.get_customer_id.return_value = ArveCustomer(12345) arve.get_devices.return_value = ArveDevices(["test-serial-number"]) arve.get_sensor_info.return_value = ArveSensPro("Test Sensor", "1.0", "prov1") arve.device_sensor_data.return_value = ArveSensProData( 14, 595.75, 28.71, 0.16, 0.19, 26.02, 7 ) yield arve
Mock the TTS cache dir with empty dir.
def mock_tts_cache_dir_autouse(mock_tts_cache_dir): """Mock the TTS cache dir with empty dir.""" return mock_tts_cache_dir
Test provider entity fixture.
def mock_stt_provider_entity() -> MockSttProviderEntity: """Test provider entity fixture.""" return MockSttProviderEntity(_TRANSCRIPT)
Mock config flow.
def config_flow_fixture(hass: HomeAssistant) -> Generator[None, None, None]: """Mock config flow.""" mock_platform(hass, "test.config_flow") with mock_config_flow("test", MockFlow): yield
Return pipeline data.
def pipeline_data(hass: HomeAssistant, init_components) -> PipelineData: """Return pipeline data.""" return hass.data[DOMAIN]
Return pipeline storage collection.
def pipeline_storage(pipeline_data) -> PipelineStorageCollection: """Return pipeline storage collection.""" return pipeline_data.pipeline_store
Process events to remove dynamic values.
def process_events(events: list[assist_pipeline.PipelineEvent]) -> list[dict]: """Process events to remove dynamic values.""" processed = [] for event in events: as_dict = asdict(event) as_dict.pop("timestamp") if as_dict["type"] == assist_pipeline.PipelineEventType.RUN_START: as_dict["data"]["pipeline"] = ANY processed.append(as_dict) return processed
Test that pipeline run equality uses unique id.
def test_pipeline_run_equality(hass: HomeAssistant, init_components) -> None: """Test that pipeline run equality uses unique id.""" def event_callback(event): pass pipeline = assist_pipeline.pipeline.async_get_pipeline(hass) run_1 = assist_pipeline.pipeline.PipelineRun( hass, context=Context(), pipeline=pipeline, start_stage=assist_pipeline.PipelineStage.STT, end_stage=assist_pipeline.PipelineStage.TTS, event_callback=event_callback, ) run_2 = assist_pipeline.pipeline.PipelineRun( hass, context=Context(), pipeline=pipeline, start_stage=assist_pipeline.PipelineStage.STT, end_stage=assist_pipeline.PipelineStage.TTS, event_callback=event_callback, ) assert run_1 == run_1 # noqa: PLR0124 assert run_1 != run_2 assert run_1 != 1234
Test empty ring buffer.
def test_ring_buffer_empty() -> None: """Test empty ring buffer.""" rb = RingBuffer(10) assert rb.maxlen == 10 assert rb.pos == 0 assert rb.getvalue() == b""
Test putting some data smaller than the maximum length.
def test_ring_buffer_put_1() -> None: """Test putting some data smaller than the maximum length.""" rb = RingBuffer(10) rb.put(bytes([1, 2, 3, 4, 5])) assert len(rb) == 5 assert rb.pos == 5 assert rb.getvalue() == bytes([1, 2, 3, 4, 5])
Test putting some data past the end of the buffer.
def test_ring_buffer_put_2() -> None: """Test putting some data past the end of the buffer.""" rb = RingBuffer(10) rb.put(bytes([1, 2, 3, 4, 5])) rb.put(bytes([6, 7, 8, 9, 10, 11, 12])) assert len(rb) == 10 assert rb.pos == 2 assert rb.getvalue() == bytes([3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
Test putting data too large for the buffer.
def test_ring_buffer_put_too_large() -> None: """Test putting data too large for the buffer.""" rb = RingBuffer(10) rb.put(bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])) assert len(rb) == 10 assert rb.pos == 2 assert rb.getvalue() == bytes([3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
Test that 3 seconds of silence does not trigger a voice command.
def test_silence() -> None: """Test that 3 seconds of silence does not trigger a voice command.""" segmenter = VoiceCommandSegmenter() # True return value indicates voice command has not finished assert segmenter.process(_ONE_SECOND * 3, False)
Test that silence + speech + silence triggers a voice command.
def test_speech() -> None: """Test that silence + speech + silence triggers a voice command.""" def is_speech(chunk): """Anything non-zero is speech.""" return sum(chunk) > 0 segmenter = VoiceCommandSegmenter() # silence assert segmenter.process(_ONE_SECOND, False) # "speech" assert segmenter.process(_ONE_SECOND, True) # silence # False return value indicates voice command is finished assert not segmenter.process(_ONE_SECOND, False)
Test audio buffer wrapping.
def test_audio_buffer() -> None: """Test audio buffer wrapping.""" class DisabledVad(VoiceActivityDetector): def is_speech(self, chunk): return False @property def samples_per_chunk(self): return 160 # 10 ms vad = DisabledVad() bytes_per_chunk = vad.samples_per_chunk * 2 vad_buffer = AudioBuffer(bytes_per_chunk) segmenter = VoiceCommandSegmenter() with patch.object(vad, "is_speech", return_value=False) as mock_process: # Partially fill audio buffer half_chunk = bytes(it.islice(it.cycle(range(256)), bytes_per_chunk // 2)) segmenter.process_with_vad(half_chunk, vad, vad_buffer) assert not mock_process.called assert vad_buffer is not None assert vad_buffer.bytes() == half_chunk # Fill and wrap with 1/4 chunk left over three_quarters_chunk = bytes( it.islice(it.cycle(range(256)), int(0.75 * bytes_per_chunk)) ) segmenter.process_with_vad(three_quarters_chunk, vad, vad_buffer) assert mock_process.call_count == 1 assert ( vad_buffer.bytes() == three_quarters_chunk[ len(three_quarters_chunk) - (bytes_per_chunk // 4) : ] ) assert ( mock_process.call_args[0][0] == half_chunk + three_quarters_chunk[: bytes_per_chunk // 2] ) # Run 2 chunks through segmenter.reset() vad_buffer.clear() assert len(vad_buffer) == 0 mock_process.reset_mock() two_chunks = bytes(it.islice(it.cycle(range(256)), bytes_per_chunk * 2)) segmenter.process_with_vad(two_chunks, vad, vad_buffer) assert mock_process.call_count == 2 assert len(vad_buffer) == 0 assert mock_process.call_args_list[0][0][0] == two_chunks[:bytes_per_chunk] assert mock_process.call_args_list[1][0][0] == two_chunks[bytes_per_chunk:]
Test that chunk_samples returns when given a partial chunk.
def test_partial_chunk() -> None: """Test that chunk_samples returns when given a partial chunk.""" bytes_per_chunk = 5 samples = bytes([1, 2, 3]) leftover_chunk_buffer = AudioBuffer(bytes_per_chunk) chunks = list(chunk_samples(samples, bytes_per_chunk, leftover_chunk_buffer)) assert len(chunks) == 0 assert leftover_chunk_buffer.bytes() == samples
Test that chunk_samples property keeps left over bytes across calls.
def test_chunk_samples_leftover() -> None: """Test that chunk_samples property keeps left over bytes across calls.""" bytes_per_chunk = 5 samples = bytes([1, 2, 3, 4, 5, 6]) leftover_chunk_buffer = AudioBuffer(bytes_per_chunk) chunks = list(chunk_samples(samples, bytes_per_chunk, leftover_chunk_buffer)) assert len(chunks) == 1 assert leftover_chunk_buffer.bytes() == bytes([6]) # Add some more to the chunk chunks = list(chunk_samples(samples, bytes_per_chunk, leftover_chunk_buffer)) assert len(chunks) == 1 assert leftover_chunk_buffer.bytes() == bytes([5, 6])
Test VAD that doesn't require chunking.
def test_vad_no_chunking() -> None: """Test VAD that doesn't require chunking.""" class VadNoChunk(VoiceActivityDetector): def is_speech(self, chunk: bytes) -> bool: return sum(chunk) > 0 @property def samples_per_chunk(self) -> int | None: return None vad = VadNoChunk() segmenter = VoiceCommandSegmenter( speech_seconds=1.0, silence_seconds=1.0, reset_seconds=0.5 ) silence = bytes([0] * 16000) speech = bytes([255] * (16000 // 2)) # Test with differently-sized chunks assert vad.is_speech(speech) assert not vad.is_speech(silence) # Simulate voice command assert segmenter.process_with_vad(silence, vad, None) # begin assert segmenter.process_with_vad(speech, vad, None) assert segmenter.process_with_vad(speech, vad, None) assert segmenter.process_with_vad(speech, vad, None) # reset with silence assert segmenter.process_with_vad(silence, vad, None) # resume assert segmenter.process_with_vad(speech, vad, None) assert segmenter.process_with_vad(speech, vad, None) assert segmenter.process_with_vad(speech, vad, None) assert segmenter.process_with_vad(speech, vad, None) # end assert segmenter.process_with_vad(silence, vad, None) assert not segmenter.process_with_vad(silence, vad, None)
Mock client.
def client() -> Generator[Mock, None, None]: """Mock client.""" with patch( "homeassistant.components.asterisk_mbox.asteriskClient", autospec=True ) as client: yield client
Return a new device for specific protocol.
def new_device(protocol, mac, ip, name): """Return a new device for specific protocol.""" if protocol in [PROTOCOL_HTTP, PROTOCOL_HTTPS]: return HttpDevice(mac, ip, name, ROUTER_MAC_ADDR, None) return LegacyDevice(mac, ip, name)
Mock setting up a config entry.
def mock_controller_patch_setup_entry(): """Mock setting up a config entry.""" with patch( f"{ASUSWRT_BASE}.async_setup_entry", return_value=True ) as setup_entry_mock: yield setup_entry_mock
Mock a list of devices.
def mock_devices_legacy_fixture(): """Mock a list of devices.""" return { MOCK_MACS[0]: new_device(PROTOCOL_SSH, MOCK_MACS[0], "192.168.1.2", "Test"), MOCK_MACS[1]: new_device(PROTOCOL_SSH, MOCK_MACS[1], "192.168.1.3", "TestTwo"), }
Mock a list of devices.
def mock_devices_http_fixture(): """Mock a list of devices.""" return { MOCK_MACS[0]: new_device(PROTOCOL_HTTP, MOCK_MACS[0], "192.168.1.2", "Test"), MOCK_MACS[1]: new_device(PROTOCOL_HTTP, MOCK_MACS[1], "192.168.1.3", "TestTwo"), }
Mock a list of available temperature sensors.
def mock_available_temps_fixture(): """Mock a list of available temperature sensors.""" return [True, False, True]
Mock a successful connection with legacy library.
def mock_controller_connect_legacy(mock_devices_legacy, mock_available_temps): """Mock a successful connection with legacy library.""" with patch(ASUSWRT_LEGACY_LIB, spec=AsusWrtLegacy) as service_mock: service_mock.return_value.connection = Mock(spec=TelnetConnection) service_mock.return_value.is_connected = True service_mock.return_value.async_get_nvram.return_value = { "label_mac": ROUTER_MAC_ADDR, "model": "abcd", "firmver": "efg", "buildno": "123", } service_mock.return_value.async_get_connected_devices.return_value = ( mock_devices_legacy ) service_mock.return_value.async_get_bytes_total.return_value = MOCK_BYTES_TOTAL service_mock.return_value.async_get_current_transfer_rates.return_value = ( MOCK_CURRENT_TRANSFER_RATES ) service_mock.return_value.async_get_loadavg.return_value = MOCK_LOAD_AVG service_mock.return_value.async_get_temperature.return_value = MOCK_TEMPERATURES service_mock.return_value.async_find_temperature_commands.return_value = ( mock_available_temps ) yield service_mock
Mock a successful connection using legacy library with sensors fail.
def mock_controller_connect_legacy_sens_fail(connect_legacy): """Mock a successful connection using legacy library with sensors fail.""" connect_legacy.return_value.async_get_nvram.side_effect = OSError connect_legacy.return_value.async_get_connected_devices.side_effect = OSError connect_legacy.return_value.async_get_bytes_total.side_effect = OSError connect_legacy.return_value.async_get_current_transfer_rates.side_effect = OSError connect_legacy.return_value.async_get_loadavg.side_effect = OSError connect_legacy.return_value.async_get_temperature.side_effect = OSError connect_legacy.return_value.async_find_temperature_commands.return_value = [ True, True, True, ]
Mock a successful connection with http library.
def mock_controller_connect_http(mock_devices_http): """Mock a successful connection with http library.""" with patch(ASUSWRT_HTTP_LIB, spec_set=AsusWrtHttp) as service_mock: service_mock.return_value.is_connected = True service_mock.return_value.mac = ROUTER_MAC_ADDR service_mock.return_value.model = "FAKE_MODEL" service_mock.return_value.firmware = "FAKE_FIRMWARE" service_mock.return_value.async_get_connected_devices.return_value = ( mock_devices_http ) service_mock.return_value.async_get_traffic_bytes.return_value = ( MOCK_BYTES_TOTAL_HTTP ) service_mock.return_value.async_get_traffic_rates.return_value = ( MOCK_CURRENT_TRANSFER_RATES_HTTP ) service_mock.return_value.async_get_loadavg.return_value = MOCK_LOAD_AVG_HTTP service_mock.return_value.async_get_temperatures.return_value = { k: v for k, v in MOCK_TEMPERATURES_HTTP.items() if k != "5.0GHz" } yield service_mock
Mock a successful connection using http library with sensors fail.
def mock_controller_connect_http_sens_fail(connect_http): """Mock a successful connection using http library with sensors fail.""" connect_http.return_value.mac = None connect_http.return_value.async_get_connected_devices.side_effect = AsusWrtError connect_http.return_value.async_get_traffic_bytes.side_effect = AsusWrtError connect_http.return_value.async_get_traffic_rates.side_effect = AsusWrtError connect_http.return_value.async_get_loadavg.side_effect = AsusWrtError connect_http.return_value.async_get_temperatures.side_effect = AsusWrtError