response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Fixture info.
def info_fixture(): """Fixture info.""" return json.loads(load_fixture("info.json", "evil_genius_labs"))
Fixture info.
def product_fixture(): """Fixture info.""" return {"productName": "Fibonacci256"}
Evil genius labs config entry.
def config_entry(hass): """Evil genius labs config entry.""" entry = MockConfigEntry(domain="evil_genius_labs", data={"host": "192.168.1.113"}) entry.add_to_hass(hass) return entry
Mock ffmpeg is loaded.
def mock_ffmpeg(hass): """Mock ffmpeg is loaded.""" hass.config.components.add("ffmpeg")
Mock the EzvizApi for easier testing.
def ezviz_test_rtsp_config_flow(hass): """Mock the EzvizApi for easier testing.""" with ( patch.object(TestRTSPAuth, "main", return_value=True), patch( "homeassistant.components.ezviz.config_flow.TestRTSPAuth" ) as mock_ezviz_test_rtsp, ): instance = mock_ezviz_test_rtsp.return_value = TestRTSPAuth( "test-ip", "test-username", "test-password", ) instance.main = MagicMock(return_value=True) yield mock_ezviz_test_rtsp
Mock the EzvizAPI for easier config flow testing.
def ezviz_config_flow(hass): """Mock the EzvizAPI for easier config flow testing.""" with ( patch.object(EzvizClient, "login", return_value=True), patch("homeassistant.components.ezviz.config_flow.EzvizClient") as mock_ezviz, ): instance = mock_ezviz.return_value = EzvizClient( "test-username", "test-password", "local.host", "1", ) instance.login = MagicMock(return_value=ezviz_login_token_return) instance.get_detection_sensibility = MagicMock(return_value=True) yield mock_ezviz
Fixture for facebook.
def facebook(): """Fixture for facebook.""" access_token = "page-access-token" return fb.FacebookNotificationService(access_token)
Return a fake fail2ban log.
def fake_log(log_key): """Return a fake fail2ban log.""" fake_log_dict = { "single_ban": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 111.111.111.111" ), "ipv6_ban": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 2607:f0d0:1002:51::4" ), "multi_ban": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 111.111.111.111\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 222.222.222.222" ), "multi_jail": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 111.111.111.111\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_two] Ban 222.222.222.222" ), "unban_all": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 111.111.111.111\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Unban 111.111.111.111\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 222.222.222.222\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Unban 222.222.222.222" ), "unban_one": ( "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 111.111.111.111\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Ban 222.222.222.222\n" "2017-01-01 12:23:35 fail2ban.actions [111]: " "NOTICE [jail_one] Unban 111.111.111.111" ), } return fake_log_dict[log_key]
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."""
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")
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")
Test fan entity methods.
def test_fanentity() -> None: """Test fan entity methods.""" fan = BaseFan() assert fan.state == "off" assert fan.preset_modes is None assert fan.supported_features == 0 assert fan.percentage_step == 1 assert fan.speed_count == 100 assert fan.capability_attributes == {} # Test set_speed not required with pytest.raises(NotImplementedError): fan.oscillate(True) with pytest.raises(AttributeError): fan.set_speed("low") with pytest.raises(NotImplementedError): fan.set_percentage(0) with pytest.raises(NotImplementedError): fan.set_preset_mode("auto") with pytest.raises(NotImplementedError): fan.turn_on() with pytest.raises(NotImplementedError): fan.turn_off()
Test fan entity attribute shorthand.
def test_fanentity_attributes(attribute_name, attribute_value) -> None: """Test fan entity attribute shorthand.""" fan = BaseFan() setattr(fan, f"_attr_{attribute_name}", attribute_value) assert getattr(fan, attribute_name) == attribute_value
Test module.__all__ is correctly set.
def test_all() -> None: """Test module.__all__ is correctly set.""" help_test_all(fan)
Test deprecated constants.
def test_deprecated_constants( caplog: pytest.LogCaptureFixture, enum: fan.FanEntityFeature, ) -> None: """Test deprecated constants.""" import_and_test_deprecated_constant_enum(caplog, fan, enum, "SUPPORT_", "2025.1")
Test deprecated supported features ints.
def test_deprecated_supported_features_ints(caplog: pytest.LogCaptureFixture) -> None: """Test deprecated supported features ints.""" class MockFan(FanEntity): @property def supported_features(self) -> int: """Return supported features.""" return 1 entity = MockFan() assert entity.supported_features_compat is FanEntityFeature(1) assert "MockFan" in caplog.text assert "is using deprecated supported features values" in caplog.text assert "Instead it should use" in caplog.text assert "FanEntityFeature.SET_SPEED" in caplog.text caplog.clear() assert entity.supported_features_compat is FanEntityFeature(1) assert "is using deprecated supported features values" not in caplog.text
Return byte stream of fixture.
def load_fixture_bytes(src: str) -> bytes: """Return byte stream of fixture.""" feed_data = load_fixture(src, DOMAIN) return bytes(feed_data, "utf-8")
Load test feed data for one event.
def fixture_feed_one_event(hass: HomeAssistant) -> bytes: """Load test feed data for one event.""" return load_fixture_bytes("feedreader.xml")
Load test feed data for two event.
def fixture_feed_two_events(hass: HomeAssistant) -> bytes: """Load test feed data for two event.""" return load_fixture_bytes("feedreader1.xml")
Load test feed data for twenty one events.
def fixture_feed_21_events(hass: HomeAssistant) -> bytes: """Load test feed data for twenty one events.""" return load_fixture_bytes("feedreader2.xml")
Load test feed data for three events.
def fixture_feed_three_events(hass: HomeAssistant) -> bytes: """Load test feed data for three events.""" return load_fixture_bytes("feedreader3.xml")
Load test feed data for atom event.
def fixture_feed_atom_event(hass: HomeAssistant) -> bytes: """Load test feed data for atom event.""" return load_fixture_bytes("feedreader5.xml")
Load test feed data for two events published at the exact same time.
def fixture_feed_identically_timed_events(hass: HomeAssistant) -> bytes: """Load test feed data for two events published at the exact same time.""" return load_fixture_bytes("feedreader6.xml")
Set up the test storage environment.
def fixture_storage(request: pytest.FixtureRequest) -> Generator[None, None, None]: """Set up the test storage environment.""" if request.param == "legacy_storage": with patch("os.path.exists", return_value=False): yield elif request.param == "json_storage": with patch("os.path.exists", return_value=True): yield else: raise RuntimeError("Invalid storage fixture")
Mock builtins.open for feedreader storage.
def fixture_legacy_storage_open() -> Generator[MagicMock, None, None]: """Mock builtins.open for feedreader storage.""" with patch( "homeassistant.components.feedreader.open", mock_open(), create=True, ) as open_mock: yield open_mock
Mock builtins.open for feedreader storage.
def fixture_legacy_storage_load( legacy_storage_open, ) -> Generator[MagicMock, None, None]: """Mock builtins.open for feedreader storage.""" with patch( "homeassistant.components.feedreader.pickle.load", return_value={} ) as pickle_load: yield pickle_load
Start a FFmpeg process on entity. This is a legacy helper method. Do not use it for new tests.
def async_start(hass, entity_id=None): """Start a FFmpeg process on entity. This is a legacy helper method. Do not use it for new tests. """ data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_START, data))
Stop a FFmpeg process on entity. This is a legacy helper method. Do not use it for new tests.
def async_stop(hass, entity_id=None): """Stop a FFmpeg process on entity. This is a legacy helper method. Do not use it for new tests. """ data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_STOP, data))
Restart a FFmpeg process on entity. This is a legacy helper method. Do not use it for new tests.
def async_restart(hass, entity_id=None): """Restart a FFmpeg process on entity. This is a legacy helper method. Do not use it for new tests. """ data = {ATTR_ENTITY_ID: entity_id} if entity_id else {} hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_RESTART, data))
Set up ffmpeg component.
def test_setup_component(): """Set up ffmpeg component.""" with get_test_home_assistant() as hass: with assert_setup_component(1): setup_component(hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}}) assert hass.data[ffmpeg.DATA_FFMPEG].binary == "ffmpeg" hass.stop()
Set up ffmpeg component test services.
def test_setup_component_test_service(): """Set up ffmpeg component test services.""" with get_test_home_assistant() as hass: with assert_setup_component(1): setup_component(hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}}) assert hass.services.has_service(ffmpeg.DOMAIN, "start") assert hass.services.has_service(ffmpeg.DOMAIN, "stop") assert hass.services.has_service(ffmpeg.DOMAIN, "restart") hass.stop()
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.fibaro.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Fixture for an individual scene.
def mock_scene() -> Mock: """Fixture for an individual scene.""" scene = Mock() scene.fibaro_id = 1 scene.name = "Test scene" scene.room_id = 1 scene.visible = True return scene
Fixture for an individual room.
def mock_room() -> Mock: """Fixture for an individual room.""" room = Mock() room.fibaro_id = 1 room.name = "Room 1" return room
Return the default mocked config entry.
def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry: """Return the default mocked config entry.""" mock_config_entry = MockConfigEntry( domain=DOMAIN, data={ CONF_URL: TEST_URL, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_IMPORT_PLUGINS: True, }, ) mock_config_entry.add_to_hass(hass) return mock_config_entry
Return a mocked FibaroClient.
def mock_fibaro_client() -> Generator[Mock, None, None]: """Return a mocked FibaroClient.""" info_mock = Mock() info_mock.serial_number = TEST_SERIALNUMBER info_mock.hc_name = TEST_NAME info_mock.current_version = TEST_VERSION info_mock.platform = TEST_MODEL with patch( "homeassistant.components.fibaro.FibaroClient", autospec=True ) as fibaro_client_mock: client = fibaro_client_mock.return_value client.set_authentication.return_value = None client.connect.return_value = True client.read_info.return_value = info_mock client.read_rooms.return_value = [] client.read_scenes.return_value = [] client.read_devices.return_value = [] client.register_update_handler.return_value = None client.unregister_update_handler.return_value = None yield client
Return the default mocked config entry.
def mock_config_entry(tmp_path: Path) -> MockConfigEntry: """Return the default mocked config entry.""" test_file = str(tmp_path.joinpath(TEST_FILE_NAME)) return MockConfigEntry( title=TEST_FILE_NAME, domain=DOMAIN, data={CONF_FILE_PATH: test_file}, unique_id=test_file, )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[None, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.filesize.async_setup_entry", return_value=True ): yield
Create the test file.
def create_file(path: str) -> None: """Create the test file.""" with open(path, "w", encoding="utf-8") as test_file: test_file.write("test")
Generate a file on the fly. Simulates a large file.
def large_file_io() -> StringIO: """Generate a file on the fly. Simulates a large file.""" return StringIO( 2 * "Home Assistant is awesome. Open source home automation that puts local control and privacy first." )
Fixture for a list of test States.
def values_fixture() -> list[State]: """Fixture for a list of test States.""" values = [] raw_values = [20, 19, 18, 21, 22, 0] timestamp = dt_util.utcnow() for val in raw_values: values.append(State("sensor.test_monitored", str(val), last_updated=timestamp)) timestamp += timedelta(minutes=1) return values
Test step-change handling in outlier. Test if outlier filter handles long-running step-changes correctly. It should converge to no longer filter once just over half the window_size is occupied by the new post step-change values.
def test_outlier_step(values: list[State]) -> None: """Test step-change handling in outlier. Test if outlier filter handles long-running step-changes correctly. It should converge to no longer filter once just over half the window_size is occupied by the new post step-change values. """ filt = OutlierFilter(window_size=3, precision=2, entity=None, radius=1.1) values[-1].state = 22 for state in values: filtered = filt.filter_state(state) assert filtered.state == 22
Test issue #13363.
def test_initial_outlier(values: list[State]) -> None: """Test issue #13363.""" filt = OutlierFilter(window_size=3, precision=2, entity=None, radius=4.0) out = State("sensor.test_monitored", "4000") for state in [out, *values]: filtered = filt.filter_state(state) assert filtered.state == 21
Test issue #32395.
def test_unknown_state_outlier(values: list[State]) -> None: """Test issue #32395.""" filt = OutlierFilter(window_size=3, precision=2, entity=None, radius=4.0) out = State("sensor.test_monitored", "unknown") for state in [out, *values, out]: try: filtered = filt.filter_state(state) except ValueError: assert state.state == "unknown" assert filtered.state == 21
Test if precision of zero returns an integer.
def test_precision_zero(values: list[State]) -> None: """Test if precision of zero returns an integer.""" filt = LowPassFilter(window_size=10, precision=0, entity=None, time_constant=10) for state in values: filtered = filt.filter_state(state) assert isinstance(filtered.state, int)
Test if lowpass filter works.
def test_lowpass(values: list[State]) -> None: """Test if lowpass filter works.""" filt = LowPassFilter(window_size=10, precision=2, entity=None, time_constant=10) out = State("sensor.test_monitored", "unknown") for state in [out, *values, out]: try: filtered = filt.filter_state(state) except ValueError: assert state.state == "unknown" assert filtered.state == 18.05
Test if range filter works.
def test_range(values: list[State]) -> None: """Test if range filter works.""" lower = 10 upper = 20 filt = RangeFilter(entity=None, precision=2, lower_bound=lower, upper_bound=upper) for unf_state in values: unf = float(unf_state.state) filtered = filt.filter_state(unf_state) if unf < lower: assert lower == filtered.state elif unf > upper: assert upper == filtered.state else: assert unf == filtered.state
Test if range filter works with zeroes as bounds.
def test_range_zero(values: list[State]) -> None: """Test if range filter works with zeroes as bounds.""" lower = 0 upper = 0 filt = RangeFilter(entity=None, precision=2, lower_bound=lower, upper_bound=upper) for unf_state in values: unf = float(unf_state.state) filtered = filt.filter_state(unf_state) if unf < lower: assert lower == filtered.state elif unf > upper: assert upper == filtered.state else: assert unf == filtered.state
Test if lowpass filter works.
def test_throttle(values: list[State]) -> None: """Test if lowpass filter works.""" filt = ThrottleFilter(window_size=3, precision=2, entity=None) filtered = [] for state in values: new_state = filt.filter_state(state) if not filt.skip_processing: filtered.append(new_state) assert [20, 21] == [f.state for f in filtered]
Test if lowpass filter works.
def test_time_throttle(values: list[State]) -> None: """Test if lowpass filter works.""" filt = TimeThrottleFilter( window_size=timedelta(minutes=2), precision=2, entity=None ) filtered = [] for state in values: new_state = filt.filter_state(state) if not filt.skip_processing: filtered.append(new_state) assert [20, 18, 22] == [f.state for f in filtered]
Test if time_sma filter works.
def test_time_sma(values: list[State]) -> None: """Test if time_sma filter works.""" filt = TimeSMAFilter( window_size=timedelta(minutes=2), precision=2, entity=None, type="last" ) for state in values: filtered = filt.filter_state(state) assert filtered.state == 21.5
Fixture for expiration time of the config entry auth token.
def mcok_token_expiration_time() -> float: """Fixture for expiration time of the config entry auth token.""" return time.time() + 86400
Fixture for expiration time of the config entry auth token.
def mock_scopes() -> list[str]: """Fixture for expiration time of the config entry auth token.""" return OAUTH_SCOPES
Fixture for OAuth 'token' data for a ConfigEntry.
def mock_token_entry(token_expiration_time: float, scopes: list[str]) -> dict[str, Any]: """Fixture for OAuth 'token' data for a ConfigEntry.""" return { "access_token": FAKE_ACCESS_TOKEN, "refresh_token": FAKE_REFRESH_TOKEN, "scope": " ".join(scopes), "token_type": "Bearer", "expires_at": token_expiration_time, }
Fixture for a config entry.
def mock_config_entry(token_entry: dict[str, Any]) -> MockConfigEntry: """Fixture for a config entry.""" return MockConfigEntry( domain=DOMAIN, data={ "auth_implementation": FAKE_AUTH_IMPL, "token": token_entry, }, unique_id=PROFILE_USER_ID, )
Fixture for the yaml fitbit.conf file contents.
def mock_fitbit_config_yaml(token_expiration_time: float) -> dict[str, Any] | None: """Fixture for the yaml fitbit.conf file contents.""" return { CONF_CLIENT_ID: CLIENT_ID, CONF_CLIENT_SECRET: CLIENT_SECRET, "access_token": FAKE_ACCESS_TOKEN, "refresh_token": FAKE_REFRESH_TOKEN, "last_saved_at": token_expiration_time, }
Fixture to mock out fitbit.conf file data loading and persistence.
def mock_fitbit_config_setup( fitbit_config_yaml: dict[str, Any] | None, ) -> Generator[None, None, None]: """Fixture to mock out fitbit.conf file data loading and persistence.""" has_config = fitbit_config_yaml is not None with ( patch( "homeassistant.components.fitbit.sensor.os.path.isfile", return_value=has_config, ), patch( "homeassistant.components.fitbit.sensor.load_json_object", return_value=fitbit_config_yaml, ), ): yield
Fixture for the fitbit yaml config monitored_resources field.
def mock_monitored_resources() -> list[str] | None: """Fixture for the fitbit yaml config monitored_resources field.""" return None
Fixture for the fitbit yaml config monitored_resources field.
def mock_configured_unit_syststem() -> str | None: """Fixture for the fitbit yaml config monitored_resources field.""" return None
Fixture for the fitbit sensor platform configuration data in configuration.yaml.
def mock_sensor_platform_config( monitored_resources: list[str] | None, configured_unit_system: str | None, ) -> dict[str, Any]: """Fixture for the fitbit sensor platform configuration data in configuration.yaml.""" config = {} if monitored_resources is not None: config["monitored_resources"] = monitored_resources if configured_unit_system is not None: config["unit_system"] = configured_unit_system return config
Fixture to specify platforms to test.
def platforms() -> list[Platform]: """Fixture to specify platforms to test.""" return []
Fixture for the profile id returned from the API response.
def mock_profile_id() -> str: """Fixture for the profile id returned from the API response.""" return PROFILE_USER_ID
Fixture to set the API response for the user profile.
def mock_profile_locale() -> str: """Fixture to set the API response for the user profile.""" return "en_US"
Fixture to return other profile data fields.
def mock_profile_data() -> dict[str, Any]: """Fixture to return other profile data fields.""" return PROFILE_DATA
Fixture to construct the fake profile API response.
def mock_profile_response( profile_id: str, profile_locale: str, profile_data: dict[str, Any] ) -> dict[str, Any]: """Fixture to construct the fake profile API response.""" return { "user": { "encodedId": profile_id, "locale": profile_locale, **profile_data, }, }
Fixture to setup fake requests made to Fitbit API during config flow.
def mock_profile(requests_mock: Mocker, profile_response: dict[str, Any]) -> None: """Fixture to setup fake requests made to Fitbit API during config flow.""" requests_mock.register_uri( "GET", PROFILE_API_URL, status_code=HTTPStatus.OK, json=profile_response, )
Return the list of devices.
def mock_device_response() -> list[dict[str, Any]]: """Return the list of devices.""" return []
Fixture to setup fake device responses.
def mock_devices(requests_mock: Mocker, devices_response: dict[str, Any]) -> None: """Fixture to setup fake device responses.""" requests_mock.register_uri( "GET", DEVICES_API_URL, status_code=HTTPStatus.OK, json=devices_response, )
Create a timeseries response value.
def timeseries_response(resource: str, value: str) -> dict[str, Any]: """Create a timeseries response value.""" return { resource: [{"dateTime": datetime.datetime.today().isoformat(), "value": value}] }
Fixture to setup fake timeseries API responses.
def mock_register_timeseries( requests_mock: Mocker, ) -> Callable[[str, dict[str, Any]], None]: """Fixture to setup fake timeseries API responses.""" def register(resource: str, response: dict[str, Any]) -> None: requests_mock.register_uri( "GET", TIMESERIES_API_URL_FORMAT.format(resource=resource), status_code=HTTPStatus.OK, json=response, ) return register
Fixture to specify platforms to test.
def platforms() -> list[str]: """Fixture to specify platforms to test.""" return [Platform.SENSOR]
Test that platform configuration is imported successfully.
def mock_token_refresh(requests_mock: Mocker) -> None: """Test that platform configuration is imported successfully.""" requests_mock.register_uri( "POST", OAUTH2_TOKEN, status_code=HTTPStatus.OK, json=SERVER_ACCESS_TOKEN, )
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Mock data from the device.
def mock_flexit_bacnet() -> Generator[AsyncMock, None, None]: """Mock data from the device.""" flexit_bacnet = AsyncMock(spec=FlexitBACnet) with ( patch( "homeassistant.components.flexit_bacnet.config_flow.FlexitBACnet", return_value=flexit_bacnet, ), patch( "homeassistant.components.flexit_bacnet.coordinator.FlexitBACnet", return_value=flexit_bacnet, ), ): flexit_bacnet.serial_number = "0000-0001" flexit_bacnet.device_name = "Device Name" flexit_bacnet.room_temperature = 19.0 flexit_bacnet.air_temp_setpoint_away = 18.0 flexit_bacnet.air_temp_setpoint_home = 22.0 flexit_bacnet.ventilation_mode = 4 flexit_bacnet.air_filter_operating_time = 8000 flexit_bacnet.outside_air_temperature = -8.6 flexit_bacnet.supply_air_temperature = 19.1 flexit_bacnet.exhaust_air_temperature = -3.3 flexit_bacnet.extract_air_temperature = 19.0 flexit_bacnet.fireplace_ventilation_remaining_duration = 10.0 flexit_bacnet.rapid_ventilation_remaining_duration = 30.0 flexit_bacnet.supply_air_fan_control_signal = 74 flexit_bacnet.supply_air_fan_rpm = 2784 flexit_bacnet.exhaust_air_fan_control_signal = 70 flexit_bacnet.exhaust_air_fan_rpm = 2606 flexit_bacnet.electric_heater_power = 0.39636585116386414 flexit_bacnet.air_filter_operating_time = 8820.0 flexit_bacnet.heat_exchanger_efficiency = 81 flexit_bacnet.heat_exchanger_speed = 100 flexit_bacnet.air_filter_polluted = False flexit_bacnet.air_filter_exchange_interval = 8784 flexit_bacnet.electric_heater = True # Mock fan setpoints flexit_bacnet.fan_setpoint_extract_air_fire = 10 flexit_bacnet.fan_setpoint_supply_air_fire = 20 flexit_bacnet.fan_setpoint_extract_air_away = 30 flexit_bacnet.fan_setpoint_supply_air_away = 40 flexit_bacnet.fan_setpoint_extract_air_home = 50 flexit_bacnet.fan_setpoint_supply_air_home = 60 flexit_bacnet.fan_setpoint_extract_air_high = 70 flexit_bacnet.fan_setpoint_supply_air_high = 80 flexit_bacnet.fan_setpoint_extract_air_cooker = 90 flexit_bacnet.fan_setpoint_supply_air_cooker = 100 yield flexit_bacnet
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.flexit_bacnet.async_setup_entry", return_value=True ) as setup_entry_mock: yield setup_entry_mock
Mock a config entry.
def mock_config_entry() -> MockConfigEntry: """Mock a config entry.""" return MockConfigEntry( domain=DOMAIN, data={ CONF_IP_ADDRESS: "1.1.1.1", CONF_DEVICE_ID: 2, }, unique_id="0000-0001", )
Prevent setup.
def mock_setups(): """Prevent setup.""" with patch( "homeassistant.components.flipr.async_setup_entry", return_value=True, ): yield
Config entry version 1 fixture.
def config_entry(hass): """Config entry version 1 fixture.""" return MockConfigEntry( domain=FLO_DOMAIN, data={CONF_USERNAME: TEST_USER_ID, CONF_PASSWORD: TEST_PASSWORD}, version=1, )
Fixture to provide a aioclient mocker.
def aioclient_mock_fixture(aioclient_mock): """Fixture to provide a aioclient mocker.""" now = round(time.time()) # Mocks the login response for flo. aioclient_mock.post( "https://api.meetflo.com/api/v1/users/auth", text=json.dumps( { "token": TEST_TOKEN, "tokenPayload": { "user": {"user_id": TEST_USER_ID, "email": TEST_EMAIL_ADDRESS}, "timestamp": now, }, "tokenExpiration": 86400, "timeNow": now, } ), headers={"Content-Type": CONTENT_TYPE_JSON}, status=HTTPStatus.OK, ) # Mocks the presence ping response for flo. aioclient_mock.post( "https://api-gw.meetflo.com/api/v2/presence/me", text=load_fixture("flo/ping_response.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, status=HTTPStatus.OK, ) # Mocks the devices for flo. aioclient_mock.get( "https://api-gw.meetflo.com/api/v2/devices/98765", text=load_fixture("flo/device_info_response.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.get( "https://api-gw.meetflo.com/api/v2/devices/32839", text=load_fixture("flo/device_info_response_detector.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, ) # Mocks the water consumption for flo. aioclient_mock.get( "https://api-gw.meetflo.com/api/v2/water/consumption", text=load_fixture("flo/water_consumption_info_response.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, ) # Mocks the location info for flo. aioclient_mock.get( "https://api-gw.meetflo.com/api/v2/locations/mmnnoopp", text=load_fixture("flo/location_info_expand_devices_response.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, ) # Mocks the user info for flo. aioclient_mock.get( "https://api-gw.meetflo.com/api/v2/users/12345abcde", text=load_fixture("flo/user_info_expand_locations_response.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, params={"expand": "locations"}, ) # Mocks the user info for flo. aioclient_mock.get( "https://api-gw.meetflo.com/api/v2/users/12345abcde", text=load_fixture("flo/user_info_expand_locations_response.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, ) # Mocks the valve open call for flo. aioclient_mock.post( "https://api-gw.meetflo.com/api/v2/devices/98765", text=load_fixture("flo/device_info_response.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, json={"valve": {"target": "open"}}, ) # Mocks the valve close call for flo. aioclient_mock.post( "https://api-gw.meetflo.com/api/v2/devices/98765", text=load_fixture("flo/device_info_response_closed.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, json={"valve": {"target": "closed"}}, ) # Mocks the health test call for flo. aioclient_mock.post( "https://api-gw.meetflo.com/api/v2/devices/98765/healthTest/run", text=load_fixture("flo/user_info_expand_locations_response.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, ) # Mocks the health test call for flo. aioclient_mock.post( "https://api-gw.meetflo.com/api/v2/locations/mmnnoopp/systemMode", text=load_fixture("flo/user_info_expand_locations_response.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, json={"systemMode": {"target": "home"}}, ) # Mocks the health test call for flo. aioclient_mock.post( "https://api-gw.meetflo.com/api/v2/locations/mmnnoopp/systemMode", text=load_fixture("flo/user_info_expand_locations_response.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, json={"systemMode": {"target": "away"}}, ) # Mocks the health test call for flo. aioclient_mock.post( "https://api-gw.meetflo.com/api/v2/locations/mmnnoopp/systemMode", text=load_fixture("flo/user_info_expand_locations_response.json"), status=HTTPStatus.OK, headers={"Content-Type": CONTENT_TYPE_JSON}, json={ "systemMode": { "target": "sleep", "revertMinutes": 120, "revertMode": "home", } }, )
Set timezone to UTC.
def set_utc(hass): """Set timezone to UTC.""" hass.config.set_time_zone("UTC")
Return an empty, loaded, registry.
def device_reg_fixture(hass): """Return an empty, loaded, registry.""" return mock_device_registry(hass)
Mock network's async_async_get_ipv4_broadcast_addresses.
def mock_single_broadcast_address(): """Mock network's async_async_get_ipv4_broadcast_addresses.""" with patch( "homeassistant.components.network.async_get_ipv4_broadcast_addresses", return_value={"10.255.255.255"}, ): yield
Mock network's async_async_get_ipv4_broadcast_addresses to return multiple addresses.
def mock_multiple_broadcast_addresses(): """Mock network's async_async_get_ipv4_broadcast_addresses to return multiple addresses.""" with patch( "homeassistant.components.network.async_get_ipv4_broadcast_addresses", return_value={"10.255.255.255", "192.168.0.255"}, ): yield
Disable waiting for state change in tests.
def no_wait_on_state_change(): """Disable waiting for state change in tests.""" with patch("homeassistant.components.flux_led.select.STATE_CHANGE_LATENCY", 0): yield
Create a test file.
def create_file(path): """Create a test file.""" with open(path, "w") as test_file: test_file.write("test")
Remove test file.
def remove_test_file(): """Remove test file.""" if os.path.isfile(TEST_FILE): os.remove(TEST_FILE) os.rmdir(TEST_DIR)
Mock setting up a config entry.
def mock_setup_entry() -> Generator[None, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.folder_watcher.async_setup_entry", return_value=True ): yield
Check that Home Assistant events are fired correctly on watchdog event.
def test_event() -> None: """Check that Home Assistant events are fired correctly on watchdog event.""" class MockPatternMatchingEventHandler: """Mock base class for the pattern matcher event handler.""" def __init__(self, patterns): pass with patch( "homeassistant.components.folder_watcher.PatternMatchingEventHandler", MockPatternMatchingEventHandler, ): hass = Mock() handler = folder_watcher.create_event_handler(["*"], hass) handler.on_created( SimpleNamespace( is_directory=False, src_path="/hello/world.txt", event_type="created" ) ) assert hass.bus.fire.called assert hass.bus.fire.mock_calls[0][1][0] == folder_watcher.DOMAIN assert hass.bus.fire.mock_calls[0][1][1] == { "event_type": "created", "path": "/hello/world.txt", "file": "world.txt", "folder": "/hello", }
Check that Home Assistant events are fired correctly on watchdog event.
def test_move_event() -> None: """Check that Home Assistant events are fired correctly on watchdog event.""" class MockPatternMatchingEventHandler: """Mock base class for the pattern matcher event handler.""" def __init__(self, patterns): pass with patch( "homeassistant.components.folder_watcher.PatternMatchingEventHandler", MockPatternMatchingEventHandler, ): hass = Mock() handler = folder_watcher.create_event_handler(["*"], hass) handler.on_moved( SimpleNamespace( is_directory=False, src_path="/hello/world.txt", dest_path="/hello/earth.txt", event_type="moved", ) ) assert hass.bus.fire.called assert hass.bus.fire.mock_calls[0][1][0] == folder_watcher.DOMAIN assert hass.bus.fire.mock_calls[0][1][1] == { "event_type": "moved", "path": "/hello/world.txt", "dest_path": "/hello/earth.txt", "file": "world.txt", "dest_file": "earth.txt", "folder": "/hello", "dest_folder": "/hello", }
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.forecast_solar.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="Green House", unique_id="unique", version=2, domain=DOMAIN, data={ CONF_LATITUDE: 52.42, CONF_LONGITUDE: 4.42, }, options={ CONF_API_KEY: "abcdef12345", CONF_DECLINATION: 30, CONF_AZIMUTH: 190, CONF_MODULES_POWER: 5100, CONF_DAMPING_MORNING: 0.5, CONF_DAMPING_EVENING: 0.5, CONF_INVERTER_SIZE: 2000, }, )
Return a mocked Forecast.Solar client. hass fixture included because it sets the time zone.
def mock_forecast_solar(hass) -> Generator[None, MagicMock, None]: """Return a mocked Forecast.Solar client. hass fixture included because it sets the time zone. """ with patch( "homeassistant.components.forecast_solar.coordinator.ForecastSolar", autospec=True, ) as forecast_solar_mock: forecast_solar = forecast_solar_mock.return_value now = datetime(2021, 6, 27, 6, 0, tzinfo=dt_util.DEFAULT_TIME_ZONE) estimate = MagicMock(spec=models.Estimate) estimate.now.return_value = now estimate.timezone = "Europe/Amsterdam" estimate.api_rate_limit = 60 estimate.account_type.value = "public" estimate.energy_production_today = 100000 estimate.energy_production_today_remaining = 50000 estimate.energy_production_tomorrow = 200000 estimate.power_production_now = 300000 estimate.power_highest_peak_time_today = datetime( 2021, 6, 27, 13, 0, tzinfo=dt_util.DEFAULT_TIME_ZONE ) estimate.power_highest_peak_time_tomorrow = datetime( 2021, 6, 27, 14, 0, tzinfo=dt_util.DEFAULT_TIME_ZONE ) estimate.energy_current_hour = 800000 estimate.power_production_at_time.side_effect = { now + timedelta(hours=1): 400000, now + timedelta(hours=12): 600000, now + timedelta(hours=24): 700000, }.get estimate.sum_energy_production.side_effect = { 1: 900000, }.get estimate.watts = { datetime(2021, 6, 27, 13, 0, tzinfo=dt_util.DEFAULT_TIME_ZONE): 10, datetime(2022, 6, 27, 13, 0, tzinfo=dt_util.DEFAULT_TIME_ZONE): 100, } estimate.wh_days = { datetime(2021, 6, 27, 13, 0, tzinfo=dt_util.DEFAULT_TIME_ZONE): 20, datetime(2022, 6, 27, 13, 0, tzinfo=dt_util.DEFAULT_TIME_ZONE): 200, } estimate.wh_period = { datetime(2021, 6, 27, 13, 0, tzinfo=dt_util.DEFAULT_TIME_ZONE): 30, datetime(2022, 6, 27, 13, 0, tzinfo=dt_util.DEFAULT_TIME_ZONE): 300, } forecast_solar.estimate.return_value = estimate yield forecast_solar
Create hass config_entry fixture.
def config_entry_fixture(): """Create hass config_entry fixture.""" data = { CONF_HOST: "192.168.1.1", CONF_PORT: "2345", CONF_PASSWORD: "", } return MockConfigEntry( version=1, domain=DOMAIN, title="", data=data, options={CONF_TTS_PAUSE_TIME: 0}, source=SOURCE_USER, entry_id=1, )
Create hass config_entry fixture.
def config_entry_fixture(): """Create hass config_entry fixture.""" data = { CONF_HOST: "192.168.1.1", CONF_PORT: "2345", CONF_PASSWORD: "", } return MockConfigEntry( version=1, domain=DOMAIN, title="", data=data, options={}, source=SOURCE_USER, entry_id=1, )
Test master state attributes.
def test_master_state(hass: HomeAssistant, mock_api_object) -> None: """Test master state attributes.""" state = hass.states.get(TEST_MASTER_ENTITY_NAME) assert state.state == STATE_PAUSED assert state.attributes[ATTR_FRIENDLY_NAME] == "OwnTone server" assert state.attributes[ATTR_SUPPORTED_FEATURES] == SUPPORTED_FEATURES assert not state.attributes[ATTR_MEDIA_VOLUME_MUTED] assert state.attributes[ATTR_MEDIA_VOLUME_LEVEL] == 0.2 assert state.attributes[ATTR_MEDIA_CONTENT_ID] == 12322 assert state.attributes[ATTR_MEDIA_CONTENT_TYPE] == MediaType.MUSIC assert state.attributes[ATTR_MEDIA_DURATION] == 0.05 assert state.attributes[ATTR_MEDIA_POSITION] == 0.005 assert state.attributes[ATTR_MEDIA_TITLE] == "No album" # reversed for url assert state.attributes[ATTR_MEDIA_ARTIST] == "Some artist" assert state.attributes[ATTR_MEDIA_ALBUM_NAME] == "Some song" # reversed assert state.attributes[ATTR_MEDIA_ALBUM_ARTIST] == "The xx" assert state.attributes[ATTR_MEDIA_TRACK] == 1 assert not state.attributes[ATTR_MEDIA_SHUFFLE]
Mock FoscamCamera simulating behaviour using a base valid config.
def setup_mock_foscam_camera(mock_foscam_camera): """Mock FoscamCamera simulating behaviour using a base valid config.""" def configure_mock_on_init(host, port, user, passwd, verbose=False): product_all_info_rc = 0 dev_info_rc = 0 dev_info_data = {} if ( host != VALID_CONFIG[config_flow.CONF_HOST] or port != VALID_CONFIG[config_flow.CONF_PORT] ): product_all_info_rc = dev_info_rc = ERROR_FOSCAM_UNAVAILABLE elif ( user not in [ VALID_CONFIG[config_flow.CONF_USERNAME], OPERATOR_CONFIG[config_flow.CONF_USERNAME], INVALID_RESPONSE_CONFIG[config_flow.CONF_USERNAME], ] or passwd != VALID_CONFIG[config_flow.CONF_PASSWORD] ): product_all_info_rc = dev_info_rc = ERROR_FOSCAM_AUTH elif user == INVALID_RESPONSE_CONFIG[config_flow.CONF_USERNAME]: product_all_info_rc = dev_info_rc = ERROR_FOSCAM_UNKNOWN elif user == OPERATOR_CONFIG[config_flow.CONF_USERNAME]: dev_info_rc = ERROR_FOSCAM_CMD else: dev_info_data["devName"] = CAMERA_NAME dev_info_data["mac"] = CAMERA_MAC mock_foscam_camera.get_product_all_info.return_value = (product_all_info_rc, {}) mock_foscam_camera.get_dev_info.return_value = (dev_info_rc, dev_info_data) return mock_foscam_camera mock_foscam_camera.side_effect = configure_mock_on_init
Mock path lib.
def mock_path(): """Mock path lib.""" with ( patch("homeassistant.components.freebox.router.Path"), patch("homeassistant.components.freebox.router.os.makedirs"), ): yield
Make sure all entities are enabled.
def enable_all_entities(): """Make sure all entities are enabled.""" with patch( "homeassistant.helpers.entity.Entity.entity_registry_enabled_default", PropertyMock(return_value=True), ): yield