response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Return a default climate entity mock.
def saunabox_fixture(): """Return a default climate entity mock.""" feature = mock_feature( "climates", blebox_uniapi.climate.Climate, unique_id="BleBox-saunaBox-1afe34db9437-thermostat", full_name="saunaBox-thermostat", device_class=None, is_on=None, desired=None, current=None, min_temp=-54.3, max_temp=124.3, mode=None, hvac_action=None, ) product = feature.product type(product).name = PropertyMock(return_value="My sauna") type(product).model = PropertyMock(return_value="saunaBox") return (feature, "climate.saunabox_thermostat")
Return a default climate entity mock.
def thermobox_fixture(): """Return a default climate entity mock.""" feature = mock_feature( "climates", blebox_uniapi.climate.Climate, unique_id="BleBox-thermoBox-1afe34db9437-thermostat", full_name="thermoBox-thermostat", device_class=None, is_on=None, desired=None, current=None, min_temp=-54.3, max_temp=124.3, mode=2, hvac_action=1, ) product = feature.product type(product).name = PropertyMock(return_value="My thermo") type(product).model = PropertyMock(return_value="thermoBox") return (feature, "climate.thermobox_thermostat")
Return a valid, complete BleBox feature mock.
def create_valid_feature_mock(path="homeassistant.components.blebox.Products"): """Return a valid, complete BleBox feature mock.""" feature = mock_only_feature( blebox_uniapi.cover.Cover, unique_id="BleBox-gateBox-1afe34db9437-0.position", full_name="gateBox-0.position", device_class="gate", state=0, async_update=AsyncMock(), current=None, ) product = setup_product_mock("covers", [feature], path) type(product).name = PropertyMock(return_value="My gate controller") type(product).model = PropertyMock(return_value="gateController") type(product).type = PropertyMock(return_value="gateBox") type(product).brand = PropertyMock(return_value="BleBox") type(product).firmware_version = PropertyMock(return_value="1.23") type(product).unique_id = PropertyMock(return_value="abcd0123ef5678") return feature
Return a valid, complete BleBox feature mock.
def valid_feature_mock_fixture(): """Return a valid, complete BleBox feature mock.""" return create_valid_feature_mock()
Return a mocked user flow feature.
def flow_feature_mock_fixture(): """Return a mocked user flow feature.""" return create_valid_feature_mock( "homeassistant.components.blebox.config_flow.Products" )
Return a mocked feature.
def product_class_mock_fixture(): """Return a mocked feature.""" path = "homeassistant.components.blebox.config_flow.Box" return patch(path, DEFAULT, blebox_uniapi.box.Box, True, True)
Return a shutterBox fixture.
def shutterbox_fixture(): """Return a shutterBox fixture.""" feature = mock_feature( "covers", blebox_uniapi.cover.Cover, unique_id="BleBox-shutterBox-2bee34e750b8-position", full_name="shutterBox-position", device_class="shutter", current=None, tilt_current=None, state=None, has_stop=True, has_tilt=True, is_slider=True, ) product = feature.product type(product).name = PropertyMock(return_value="My shutter") type(product).model = PropertyMock(return_value="shutterBox") return (feature, "cover.shutterbox_position")
Return a gateBox fixture.
def gatebox_fixture(): """Return a gateBox fixture.""" feature = mock_feature( "covers", blebox_uniapi.cover.Cover, unique_id="BleBox-gateBox-1afe34db9437-position", device_class="gatebox", full_name="gateBox-position", current=None, state=None, has_stop=False, is_slider=False, ) product = feature.product type(product).name = PropertyMock(return_value="My gatebox") type(product).model = PropertyMock(return_value="gateBox") return (feature, "cover.gatebox_position")
Return a gateController fixture.
def gate_fixture(): """Return a gateController fixture.""" feature = mock_feature( "covers", blebox_uniapi.cover.Cover, unique_id="BleBox-gateController-2bee34e750b8-position", full_name="gateController-position", device_class="gate", current=None, state=None, has_stop=True, is_slider=True, ) product = feature.product type(product).name = PropertyMock(return_value="My gate controller") type(product).model = PropertyMock(return_value="gateController") return (feature, "cover.gatecontroller_position")
Return an mocked feature which can be updated and stopped.
def opening_to_stop_feature_mock(feature_mock): """Return an mocked feature which can be updated and stopped.""" def initial_update(): feature_mock.state = 1 # opening def stop(): feature_mock.state = 2 # manually stopped feature_mock.async_update = AsyncMock(side_effect=initial_update) feature_mock.async_stop = AsyncMock(side_effect=stop)
Return a default light entity mock.
def dimmer_fixture(): """Return a default light entity mock.""" feature = mock_feature( "lights", blebox_uniapi.light.Light, unique_id="BleBox-dimmerBox-1afe34e750b8-brightness", full_name="dimmerBox-brightness", device_class=None, brightness=65, is_on=True, supports_color=False, supports_white=False, color_mode=blebox_uniapi.light.BleboxColorMode.MONO, effect_list=None, ) product = feature.product type(product).name = PropertyMock(return_value="My dimmer") type(product).model = PropertyMock(return_value="dimmerBox") return (feature, "light.dimmerbox_brightness")
Return a default light entity mock.
def wlightboxs_fixture(): """Return a default light entity mock.""" feature = mock_feature( "lights", blebox_uniapi.light.Light, unique_id="BleBox-wLightBoxS-1afe34e750b8-color", full_name="wLightBoxS-color", device_class=None, brightness=None, is_on=None, supports_color=False, supports_white=False, color_mode=blebox_uniapi.light.BleboxColorMode.MONO, effect_list=["NONE", "PL", "RELAX"], ) product = feature.product type(product).name = PropertyMock(return_value="My wLightBoxS") type(product).model = PropertyMock(return_value="wLightBoxS") return (feature, "light.wlightboxs_color")
Return a default light entity mock.
def wlightbox_fixture(): """Return a default light entity mock.""" feature = mock_feature( "lights", blebox_uniapi.light.Light, unique_id="BleBox-wLightBox-1afe34e750b8-color", full_name="wLightBox-color", device_class=None, is_on=None, supports_color=True, supports_white=True, white_value=None, rgbw_hex=None, color_mode=blebox_uniapi.light.BleboxColorMode.RGBW, effect="NONE", effect_list=["NONE", "PL", "POLICE"], ) product = feature.product type(product).name = PropertyMock(return_value="My wLightBox") type(product).model = PropertyMock(return_value="wLightBox") return (feature, "light.wlightbox_color")
Return a default AirQuality sensor mock.
def airsensor_fixture(): """Return a default AirQuality sensor mock.""" feature = mock_feature( "sensors", blebox_uniapi.sensor.AirQuality, unique_id="BleBox-airSensor-1afe34db9437-0.air", full_name="airSensor-0.air", device_class="pm1", unit="concentration_of_mp", native_value=None, ) product = feature.product type(product).name = PropertyMock(return_value="My air sensor") type(product).model = PropertyMock(return_value="airSensor") return (feature, "sensor.airsensor_0_air")
Return a default Temperature sensor mock.
def tempsensor_fixture(): """Return a default Temperature sensor mock.""" feature = mock_feature( "sensors", blebox_uniapi.sensor.Temperature, unique_id="BleBox-tempSensor-1afe34db9437-0.temperature", full_name="tempSensor-0.temperature", device_class="temperature", unit="celsius", current=None, native_value=None, ) product = feature.product type(product).name = PropertyMock(return_value="My temperature sensor") type(product).model = PropertyMock(return_value="tempSensor") return (feature, "sensor.tempsensor_0_temperature")
Return a default switchBox switch entity mock.
def switchbox_fixture(): """Return a default switchBox switch entity mock.""" feature = mock_feature( "switches", blebox_uniapi.switch.Switch, unique_id="BleBox-switchBox-1afe34e750b8-0.relay", full_name="switchBox-0.relay", device_class="relay", is_on=False, ) feature.async_update = AsyncMock() product = feature.product type(product).name = PropertyMock(return_value="My switch box") type(product).model = PropertyMock(return_value="switchBox") return (feature, "switch.switchbox_0_relay")
Return a default switchBoxD switch entity mock.
def relay_mock(relay_id=0): """Return a default switchBoxD switch entity mock.""" return mock_only_feature( blebox_uniapi.switch.Switch, unique_id=f"BleBox-switchBoxD-1afe34e750b8-{relay_id}.relay", full_name=f"switchBoxD-{relay_id}.relay", device_class="relay", is_on=None, )
Set up two mocked Switch features representing a switchBoxD.
def switchbox_d_fixture(): """Set up two mocked Switch features representing a switchBoxD.""" relay1 = relay_mock(0) relay2 = relay_mock(1) features = [relay1, relay2] product = setup_product_mock("switches", features) type(product).name = PropertyMock(return_value="My relays") type(product).model = PropertyMock(return_value="switchBoxD") type(product).brand = PropertyMock(return_value="BleBox") type(product).firmware_version = PropertyMock(return_value="1.23") type(product).unique_id = PropertyMock(return_value="abcd0123ef5678") type(relay1).product = product type(relay2).product = product return (features, ["switch.switchboxd_0_relay", "switch.switchboxd_1_relay"])
Set up a Blink camera fixture.
def camera() -> MagicMock: """Set up a Blink camera fixture.""" mock_blink_camera = create_autospec(blinkpy.camera.BlinkCamera, instance=True) mock_blink_camera.sync = AsyncMock(return_value=True) mock_blink_camera.name = "Camera 1" mock_blink_camera.camera_id = "111111" mock_blink_camera.serial = "12345" mock_blink_camera.motion_enabled = True mock_blink_camera.temperature = 25.1 mock_blink_camera.motion_detected = False mock_blink_camera.wifi_strength = 2.1 mock_blink_camera.camera_type = "lotus" mock_blink_camera.version = "123" mock_blink_camera.attributes = CAMERA_ATTRIBUTES return mock_blink_camera
Set up Blink API fixture.
def blink_api_fixture(camera) -> MagicMock: """Set up Blink API fixture.""" mock_blink_api = create_autospec(blinkpy.blinkpy.Blink, instance=True) mock_blink_api.available = True mock_blink_api.start = AsyncMock(return_value=True) mock_blink_api.refresh = AsyncMock(return_value=True) mock_blink_api.sync = MagicMock(return_value=True) mock_blink_api.cameras = {camera.name: camera} mock_blink_api.request_homescreen = AsyncMock(return_value=True) with patch("homeassistant.components.blink.Blink") as class_mock: class_mock.return_value = mock_blink_api yield mock_blink_api
Set up Blink API fixture.
def blink_auth_api_fixture() -> MagicMock: """Set up Blink API fixture.""" mock_blink_auth_api = create_autospec(blinkpy.auth.Auth, instance=True) mock_blink_auth_api.check_key_required.return_value = False mock_blink_auth_api.send_auth_key = AsyncMock(return_value=True) with patch("homeassistant.components.blink.Auth", autospec=True) as class_mock: class_mock.return_value = mock_blink_auth_api yield mock_blink_auth_api
Return a fake config entry.
def mock_config_fixture(): """Return a fake config entry.""" return MockConfigEntry( domain=DOMAIN, data={ CONF_USERNAME: "test_user", CONF_PASSWORD: "Password", "device_id": "Home Assistant", "uid": "BlinkCamera_e1233333e2-0909-09cd-777a-123456789012", "token": "A_token", "unique_id": "[email protected]", "host": "u034.immedia-semi.com", "region_id": "u034", "client_id": 123456, "account_id": 654321, }, entry_id=str(uuid4()), version=3, )
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Stub copying the blueprints to the config folder.
def stub_blueprint_populate_fixture_helper() -> Generator[None, Any, None]: """Stub copying the blueprints to the config folder.""" with patch( "homeassistant.components.blueprint.models.DomainBlueprints.async_populate" ): yield
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."""
Validate a folder of blueprints.
def test_default_blueprints(domain: str) -> None: """Validate a folder of blueprints.""" integration = importlib.import_module(f"homeassistant.components.{domain}") blueprint_folder = pathlib.Path(integration.__file__).parent / BLUEPRINT_FOLDER items = list(blueprint_folder.glob("*")) assert len(items) > 0, "Folder cannot be empty" for fil in items: LOGGER.info("Processing %s", fil) assert fil.name.endswith(".yaml") data = yaml.load_yaml(fil) models.Blueprint(data, expected_domain=domain)
Topic JSON with a codeblock marked as auto syntax.
def community_post(): """Topic JSON with a codeblock marked as auto syntax.""" return load_fixture("blueprint/community_post.json")
Test variations of generating import forum url.
def test_get_community_post_import_url() -> None: """Test variations of generating import forum url.""" assert ( importer._get_community_post_import_url( "https://community.home-assistant.io/t/test-topic/123" ) == "https://community.home-assistant.io/t/test-topic/123.json" ) assert ( importer._get_community_post_import_url( "https://community.home-assistant.io/t/test-topic/123/2" ) == "https://community.home-assistant.io/t/test-topic/123.json" )
Test getting github import url.
def test_get_github_import_url() -> None: """Test getting github import url.""" assert ( importer._get_github_import_url( "https://github.com/balloob/home-assistant-config/blob/main/blueprints/automation/motion_light.yaml" ) == "https://raw.githubusercontent.com/balloob/home-assistant-config/main/blueprints/automation/motion_light.yaml" ) assert ( importer._get_github_import_url( "https://raw.githubusercontent.com/balloob/home-assistant-config/main/blueprints/automation/motion_light.yaml" ) == "https://raw.githubusercontent.com/balloob/home-assistant-config/main/blueprints/automation/motion_light.yaml" )
Test extracting blueprint.
def test_extract_blueprint_from_community_topic(community_post, snapshot) -> None: """Test extracting blueprint.""" imported_blueprint = importer._extract_blueprint_from_community_topic( "http://example.com", json.loads(community_post) ) assert imported_blueprint is not None assert imported_blueprint.blueprint.domain == "automation" assert imported_blueprint.blueprint.inputs == snapshot
Test extracting blueprint with invalid YAML.
def test_extract_blueprint_from_community_topic_invalid_yaml() -> None: """Test extracting blueprint with invalid YAML.""" with pytest.raises(HomeAssistantError): importer._extract_blueprint_from_community_topic( "http://example.com", { "post_stream": { "posts": [ {"cooked": '<code class="lang-yaml">invalid: yaml: 2</code>'} ] } }, )
Test extracting blueprint with invalid YAML.
def test_extract_blueprint_from_community_topic_wrong_lang() -> None: """Test extracting blueprint with invalid YAML.""" with pytest.raises(importer.HomeAssistantError): assert importer._extract_blueprint_from_community_topic( "http://example.com", { "post_stream": { "posts": [ {"cooked": '<code class="lang-php">invalid yaml + 2</code>'} ] } }, )
Blueprint fixture.
def blueprint_1(): """Blueprint fixture.""" return models.Blueprint( { "blueprint": { "name": "Hello", "domain": "automation", "source_url": "https://github.com/balloob/home-assistant-config/blob/main/blueprints/automation/motion_light.yaml", "input": {"test-input": {"name": "Name", "description": "Description"}}, }, "example": Input("test-input"), } )
Blueprint fixture with default inputs.
def blueprint_2(): """Blueprint fixture with default inputs.""" return models.Blueprint( { "blueprint": { "name": "Hello", "domain": "automation", "source_url": "https://github.com/balloob/home-assistant-config/blob/main/blueprints/automation/motion_light.yaml", "input": { "test-input": {"name": "Name", "description": "Description"}, "test-input-default": {"default": "test"}, }, }, "example": Input("test-input"), "example-default": Input("test-input-default"), } )
Domain blueprints fixture.
def domain_bps(hass): """Domain blueprints fixture.""" return models.DomainBlueprints( hass, "automation", logging.getLogger(__name__), None, AsyncMock() )
Test constructor validation.
def test_blueprint_model_init() -> None: """Test constructor validation.""" with pytest.raises(errors.InvalidBlueprint): models.Blueprint({}) with pytest.raises(errors.InvalidBlueprint): models.Blueprint( {"blueprint": {"name": "Hello", "domain": "automation"}}, expected_domain="not-automation", ) with pytest.raises(errors.InvalidBlueprint): models.Blueprint( { "blueprint": { "name": "Hello", "domain": "automation", "input": {"something": None}, }, "trigger": {"platform": Input("non-existing")}, } )
Test properties.
def test_blueprint_properties(blueprint_1) -> None: """Test properties.""" assert blueprint_1.metadata == { "name": "Hello", "domain": "automation", "source_url": "https://github.com/balloob/home-assistant-config/blob/main/blueprints/automation/motion_light.yaml", "input": {"test-input": {"name": "Name", "description": "Description"}}, } assert blueprint_1.domain == "automation" assert blueprint_1.name == "Hello" assert blueprint_1.inputs == { "test-input": {"name": "Name", "description": "Description"} }
Test update metadata.
def test_blueprint_update_metadata() -> None: """Test update metadata.""" bp = models.Blueprint( { "blueprint": { "name": "Hello", "domain": "automation", }, } ) bp.update_metadata(source_url="http://bla.com") assert bp.metadata["source_url"] == "http://bla.com"
Test validate blueprint.
def test_blueprint_validate() -> None: """Test validate blueprint.""" assert ( models.Blueprint( { "blueprint": { "name": "Hello", "domain": "automation", }, } ).validate() is None ) assert models.Blueprint( { "blueprint": { "name": "Hello", "domain": "automation", "homeassistant": {"min_version": "100000.0.0"}, }, } ).validate() == ["Requires at least Home Assistant 100000.0.0"]
Test blueprint inputs.
def test_blueprint_inputs(blueprint_2) -> None: """Test blueprint inputs.""" inputs = models.BlueprintInputs( blueprint_2, { "use_blueprint": { "path": "bla", "input": {"test-input": 1, "test-input-default": 12}, }, "example-default": {"overridden": "via-config"}, }, ) inputs.validate() assert inputs.inputs == {"test-input": 1, "test-input-default": 12} assert inputs.async_substitute() == { "example": 1, "example-default": {"overridden": "via-config"}, }
Test blueprint input validation.
def test_blueprint_inputs_validation(blueprint_1) -> None: """Test blueprint input validation.""" inputs = models.BlueprintInputs( blueprint_1, {"use_blueprint": {"path": "bla", "input": {"non-existing-placeholder": 1}}}, ) with pytest.raises(errors.MissingInput): inputs.validate()
Test blueprint inputs.
def test_blueprint_inputs_default(blueprint_2) -> None: """Test blueprint inputs.""" inputs = models.BlueprintInputs( blueprint_2, {"use_blueprint": {"path": "bla", "input": {"test-input": 1}}}, ) inputs.validate() assert inputs.inputs == {"test-input": 1} assert inputs.inputs_with_default == { "test-input": 1, "test-input-default": "test", } assert inputs.async_substitute() == {"example": 1, "example-default": "test"}
Test blueprint inputs.
def test_blueprint_inputs_override_default(blueprint_2) -> None: """Test blueprint inputs.""" inputs = models.BlueprintInputs( blueprint_2, { "use_blueprint": { "path": "bla", "input": {"test-input": 1, "test-input-default": "custom"}, } }, ) inputs.validate() assert inputs.inputs == { "test-input": 1, "test-input-default": "custom", } assert inputs.inputs_with_default == { "test-input": 1, "test-input-default": "custom", } assert inputs.async_substitute() == {"example": 1, "example-default": "custom"}
Test different schemas.
def test_blueprint_schema(blueprint) -> None: """Test different schemas.""" try: schemas.BLUEPRINT_SCHEMA(blueprint) except vol.Invalid: _LOGGER.exception("%s", blueprint) pytest.fail("Expected schema to be valid")
Test different schemas.
def test_blueprint_schema_invalid(blueprint) -> None: """Test different schemas.""" with pytest.raises(vol.Invalid): schemas.BLUEPRINT_SCHEMA(blueprint)
Test blueprint instance fields.
def test_blueprint_instance_fields(bp_instance) -> None: """Test blueprint instance fields.""" schemas.BLUEPRINT_INSTANCE_FIELDS({"use_blueprint": bp_instance})
Automation config.
def automation_config(): """Automation config.""" return {}
Script config.
def script_config(): """Script config.""" return {}
Mock the bluez manager socket.
def disable_bluez_manager_socket(): """Mock the bluez manager socket.""" with patch.object(bleak_manager, "get_global_bluez_manager_with_timeout"): yield
Mock the dbus message bus to avoid creating a socket.
def disable_dbus_socket(): """Mock the dbus message bus to avoid creating a socket.""" with patch.object(message_bus, "MessageBus"): yield
Mock out auto recovery.
def disable_bluetooth_auto_recovery(): """Mock out auto recovery.""" with patch.object(habluetooth_utils, "recover_adapter"): yield
Mock running Home Assistant Operating system 8.5.
def mock_operating_system_85(): """Mock running Home Assistant Operating system 8.5.""" with ( patch("homeassistant.components.hassio.is_hassio", return_value=True), patch( "homeassistant.components.hassio.get_os_info", return_value={ "version": "8.5", "version_latest": "10.0.dev20220912", "update_available": False, "board": "odroid-n2", "boot": "B", "data_disk": "/dev/mmcblk1p4", }, ), patch("homeassistant.components.hassio.get_info", return_value={}), patch("homeassistant.components.hassio.get_host_info", return_value={}), ): yield
Mock running Home Assistant Operating system 9.0.
def mock_operating_system_90(): """Mock running Home Assistant Operating system 9.0.""" with ( patch("homeassistant.components.hassio.is_hassio", return_value=True), patch( "homeassistant.components.hassio.get_os_info", return_value={ "version": "9.0.dev20220912", "version_latest": "10.0.dev20220912", "update_available": False, "board": "odroid-n2", "boot": "B", "data_disk": "/dev/mmcblk1p4", }, ), patch("homeassistant.components.hassio.get_info", return_value={}), patch("homeassistant.components.hassio.get_host_info", return_value={}), ): yield
Fixture that mocks the macos adapter.
def macos_adapter(): """Fixture that mocks the macos adapter.""" with ( patch("bleak.get_platform_scanner_backend_type"), patch( "homeassistant.components.bluetooth.platform.system", return_value="Darwin", ), patch( "habluetooth.scanner.platform.system", return_value="Darwin", ), patch( "bluetooth_adapters.systems.platform.system", return_value="Darwin", ), patch("habluetooth.scanner.SYSTEM", "Darwin"), ): yield
Fixture that mocks the windows adapter.
def windows_adapter(): """Fixture that mocks the windows adapter.""" with ( patch( "bluetooth_adapters.systems.platform.system", return_value="Windows", ), patch("habluetooth.scanner.SYSTEM", "Windows"), ): yield
Fixture that mocks no adapters on Linux.
def no_adapter_fixture(): """Fixture that mocks no adapters on Linux.""" with ( patch( "homeassistant.components.bluetooth.platform.system", return_value="Linux", ), patch( "habluetooth.scanner.platform.system", return_value="Linux", ), patch( "bluetooth_adapters.systems.platform.system", return_value="Linux", ), patch("habluetooth.scanner.SYSTEM", "Linux"), patch( "bluetooth_adapters.systems.linux.LinuxAdapters.refresh", ), patch( "bluetooth_adapters.systems.linux.LinuxAdapters.adapters", {}, ), ): yield
Fixture that mocks one adapter on Linux.
def one_adapter_fixture(): """Fixture that mocks one adapter on Linux.""" with ( patch( "homeassistant.components.bluetooth.platform.system", return_value="Linux", ), patch( "habluetooth.scanner.platform.system", return_value="Linux", ), patch( "bluetooth_adapters.systems.platform.system", return_value="Linux", ), patch("habluetooth.scanner.SYSTEM", "Linux"), patch( "bluetooth_adapters.systems.linux.LinuxAdapters.refresh", ), patch( "bluetooth_adapters.systems.linux.LinuxAdapters.adapters", { "hci0": { "address": "00:00:00:00:00:01", "hw_version": "usb:v1D6Bp0246d053F", "passive_scan": True, "sw_version": "homeassistant", "manufacturer": "ACME", "product": "Bluetooth Adapter 5.0", "product_id": "aa01", "vendor_id": "cc01", }, }, ), ): yield
Fixture that mocks two adapters on Linux.
def two_adapters_fixture(): """Fixture that mocks two adapters on Linux.""" with ( patch( "homeassistant.components.bluetooth.platform.system", return_value="Linux" ), patch( "habluetooth.scanner.platform.system", return_value="Linux", ), patch("bluetooth_adapters.systems.platform.system", return_value="Linux"), patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"), patch( "bluetooth_adapters.systems.linux.LinuxAdapters.adapters", { "hci0": { "address": "00:00:00:00:00:01", "hw_version": "usb:v1D6Bp0246d053F", "passive_scan": False, "sw_version": "homeassistant", "manufacturer": "ACME", "product": "Bluetooth Adapter 5.0", "product_id": "aa01", "vendor_id": "cc01", "connection_slots": 1, }, "hci1": { "address": "00:00:00:00:00:02", "hw_version": "usb:v1D6Bp0246d053F", "passive_scan": True, "sw_version": "homeassistant", "manufacturer": "ACME", "product": "Bluetooth Adapter 5.0", "product_id": "aa01", "vendor_id": "cc01", "connection_slots": 2, }, }, ), ): yield
Fixture that mocks one crashed adapter on Linux.
def crashed_adapter_fixture(): """Fixture that mocks one crashed adapter on Linux.""" with ( patch( "homeassistant.components.bluetooth.platform.system", return_value="Linux", ), patch( "habluetooth.scanner.platform.system", return_value="Linux", ), patch( "bluetooth_adapters.systems.platform.system", return_value="Linux", ), patch("habluetooth.scanner.SYSTEM", "Linux"), patch( "bluetooth_adapters.systems.linux.LinuxAdapters.refresh", ), patch( "bluetooth_adapters.systems.linux.LinuxAdapters.adapters", { "hci0": { "address": "00:00:00:00:00:00", "hw_version": "usb:v1D6Bp0246d053F", "passive_scan": True, "sw_version": "homeassistant", "manufacturer": None, "product": None, "product_id": None, "vendor_id": None, }, }, ), ): yield
Fixture that mocks two adapters on Linux.
def one_adapter_old_bluez(): """Fixture that mocks two adapters on Linux.""" with ( patch( "homeassistant.components.bluetooth.platform.system", return_value="Linux" ), patch( "habluetooth.scanner.platform.system", return_value="Linux", ), patch("bluetooth_adapters.systems.platform.system", return_value="Linux"), patch("bluetooth_adapters.systems.linux.LinuxAdapters.refresh"), patch( "bluetooth_adapters.systems.linux.LinuxAdapters.adapters", { "hci0": { "address": "00:00:00:00:00:01", "hw_version": "usb:v1D6Bp0246d053F", "passive_scan": False, "sw_version": "homeassistant", "manufacturer": "ACME", "product": "Bluetooth Adapter 5.0", "product_id": "aa01", "vendor_id": "cc01", }, }, ), ): yield
Fixture that disables new discovery flows. We want to disable new discovery flows as we are testing the BluetoothManager and not the discovery flows. This fixture will patch the discovery_flow.async_create_flow method to ensure we do not load other integrations.
def disable_new_discovery_flows_fixture(): """Fixture that disables new discovery flows. We want to disable new discovery flows as we are testing the BluetoothManager and not the discovery flows. This fixture will patch the discovery_flow.async_create_flow method to ensure we do not load other integrations. """ with patch( "homeassistant.components.bluetooth.manager.discovery_flow.async_create_flow" ) as mock_create_flow: yield mock_create_flow
Get all the domains that were passed to async_init except bluetooth.
def _domains_from_mock_config_flow(mock_config_flow: Mock) -> list[str]: """Get all the domains that were passed to async_init except bluetooth.""" return [call[1][0] for call in mock_config_flow.mock_calls if call[1][0] != DOMAIN]
Register an hci0 scanner.
def register_hci0_scanner(hass: HomeAssistant) -> Generator[None, None, None]: """Register an hci0 scanner.""" hci0_scanner = FakeScanner("hci0", "hci0") cancel = bluetooth.async_register_scanner(hass, hci0_scanner) yield cancel()
Register an hci1 scanner.
def register_hci1_scanner(hass: HomeAssistant) -> Generator[None, None, None]: """Register an hci1 scanner.""" hci1_scanner = FakeScanner("hci1", "hci1") cancel = bluetooth.async_register_scanner(hass, hci1_scanner) yield cancel()
Mock shutdown of the HomeAssistantBluetoothManager.
def mock_shutdown(manager: HomeAssistantBluetoothManager) -> None: """Mock shutdown of the HomeAssistantBluetoothManager.""" manager.shutdown = True yield manager.shutdown = False
Generate a BLE device with adv data.
def _generate_ble_device_and_adv_data( interface: str, mac: str, rssi: int ) -> tuple[BLEDevice, AdvertisementData]: """Generate a BLE device with adv data.""" return ( generate_ble_device( mac, "any", delegate="", details={"path": f"/org/bluez/{interface}/dev_{mac}"}, ), generate_advertisement_data(rssi=rssi), )
Fixture that installs the bleak catcher.
def install_bleak_catcher_fixture(): """Fixture that installs the bleak catcher.""" install_multiple_bleak_catcher() yield uninstall_multiple_bleak_catcher()
Fixture that mocks the platform client.
def mock_platform_client_fixture(): """Fixture that mocks the platform client.""" with patch( "habluetooth.wrappers.get_platform_client_backend_type", return_value=FakeBleakClient, ): yield
Fixture that mocks the platform client that fails to connect.
def mock_platform_client_that_fails_to_connect_fixture(): """Fixture that mocks the platform client that fails to connect.""" with patch( "habluetooth.wrappers.get_platform_client_backend_type", return_value=FakeBleakClientFailsToConnect, ): yield
Fixture that mocks the platform client that fails to connect.
def mock_platform_client_that_raises_on_connect_fixture(): """Fixture that mocks the platform client that fails to connect.""" with patch( "habluetooth.wrappers.get_platform_client_backend_type", return_value=FakeBleakClientRaisesOnConnect, ): yield
Generate scanners with fake devices.
def _generate_scanners_with_fake_devices(hass): """Generate scanners with fake devices.""" manager = _get_manager() hci0_device_advs = {} for i in range(10): device, adv_data = _generate_ble_device_and_adv_data( "hci0", f"00:00:00:00:00:{i:02x}", rssi=-60 ) hci0_device_advs[device.address] = (device, adv_data) hci1_device_advs = {} for i in range(10): device, adv_data = _generate_ble_device_and_adv_data( "hci1", f"00:00:00:00:00:{i:02x}", rssi=-80 ) hci1_device_advs[device.address] = (device, adv_data) scanner_hci0 = FakeScanner("00:00:00:00:00:01", "hci0", None, True) scanner_hci1 = FakeScanner("00:00:00:00:00:02", "hci1", None, True) for device, adv_data in hci0_device_advs.values(): scanner_hci0.inject_advertisement(device, adv_data) for device, adv_data in hci1_device_advs.values(): scanner_hci1.inject_advertisement(device, adv_data) cancel_hci0 = manager.async_register_scanner(scanner_hci0, connection_slots=2) cancel_hci1 = manager.async_register_scanner(scanner_hci1, connection_slots=1) return hci0_device_advs, cancel_hci0, cancel_hci1
Patch the bluetooth time.
def patch_bluetooth_time(mock_time: float) -> None: """Patch the bluetooth time.""" with ( patch( "homeassistant.components.bluetooth.MONOTONIC_TIME", return_value=mock_time ), patch("habluetooth.base_scanner.monotonic_time_coarse", return_value=mock_time), patch("habluetooth.manager.monotonic_time_coarse", return_value=mock_time), patch("habluetooth.scanner.monotonic_time_coarse", return_value=mock_time), ): yield
Generate advertisement data with defaults.
def generate_advertisement_data(**kwargs: Any) -> AdvertisementData: """Generate advertisement data with defaults.""" new = kwargs.copy() for key, value in ADVERTISEMENT_DATA_DEFAULTS.items(): new.setdefault(key, value) return AdvertisementData(**new)
Generate a BLEDevice with defaults.
def generate_ble_device( address: str | None = None, name: str | None = None, details: Any | None = None, rssi: int | None = None, **kwargs: Any, ) -> BLEDevice: """Generate a BLEDevice with defaults.""" new = kwargs.copy() if address is not None: new["address"] = address if name is not None: new["name"] = name if details is not None: new["details"] = details if rssi is not None: new["rssi"] = rssi for key, value in BLE_DEVICE_DEFAULTS.items(): new.setdefault(key, value) return BLEDevice(**new)
Return the bluetooth manager.
def _get_manager() -> BluetoothManager: """Return the bluetooth manager.""" return get_manager()
Inject an advertisement into the manager.
def inject_advertisement( hass: HomeAssistant, device: BLEDevice, adv: AdvertisementData ) -> None: """Inject an advertisement into the manager.""" return inject_advertisement_with_source(hass, device, adv, SOURCE_LOCAL)
Inject an advertisement into the manager from a specific source.
def inject_advertisement_with_source( hass: HomeAssistant, device: BLEDevice, adv: AdvertisementData, source: str ) -> None: """Inject an advertisement into the manager from a specific source.""" inject_advertisement_with_time_and_source( hass, device, adv, time.monotonic(), source )
Inject an advertisement into the manager from a specific source at a time.
def inject_advertisement_with_time_and_source( hass: HomeAssistant, device: BLEDevice, adv: AdvertisementData, time: float, source: str, ) -> None: """Inject an advertisement into the manager from a specific source at a time.""" inject_advertisement_with_time_and_source_connectable( hass, device, adv, time, source, True )
Inject an advertisement into the manager from a specific source at a time and connectable status.
def inject_advertisement_with_time_and_source_connectable( hass: HomeAssistant, device: BLEDevice, adv: AdvertisementData, time: float, source: str, connectable: bool, ) -> None: """Inject an advertisement into the manager from a specific source at a time and connectable status.""" async_get_advertisement_callback(hass)( BluetoothServiceInfoBleak( name=adv.local_name or device.name or device.address, address=device.address, rssi=adv.rssi, manufacturer_data=adv.manufacturer_data, service_data=adv.service_data, service_uuids=adv.service_uuids, source=source, device=device, advertisement=adv, connectable=connectable, time=time, ) )
Inject an advertisement into the manager with connectable status.
def inject_bluetooth_service_info_bleak( hass: HomeAssistant, info: BluetoothServiceInfoBleak ) -> None: """Inject an advertisement into the manager with connectable status.""" advertisement_data = generate_advertisement_data( local_name=None if info.name == "" else info.name, manufacturer_data=info.manufacturer_data, service_data=info.service_data, service_uuids=info.service_uuids, rssi=info.rssi, ) device = generate_ble_device( # type: ignore[no-untyped-call] address=info.address, name=info.name, details={}, ) inject_advertisement_with_time_and_source_connectable( hass, device, advertisement_data, info.time, SOURCE_LOCAL, connectable=info.connectable, )
Inject a BluetoothServiceInfo into the manager.
def inject_bluetooth_service_info( hass: HomeAssistant, info: BluetoothServiceInfo ) -> None: """Inject a BluetoothServiceInfo into the manager.""" advertisement_data = generate_advertisement_data( # type: ignore[no-untyped-call] local_name=None if info.name == "" else info.name, manufacturer_data=info.manufacturer_data, service_data=info.service_data, service_uuids=info.service_uuids, rssi=info.rssi, ) device = generate_ble_device( # type: ignore[no-untyped-call] address=info.address, name=info.name, details={}, ) inject_advertisement(hass, device, advertisement_data)
Mock all the discovered devices from all the scanners.
def patch_all_discovered_devices(mock_discovered: list[BLEDevice]) -> None: """Mock all the discovered devices from all the scanners.""" manager = _get_manager() original_history = {} scanners = list( itertools.chain( manager._connectable_scanners, manager._non_connectable_scanners ) ) for scanner in scanners: data = scanner.discovered_devices_and_advertisement_data original_history[scanner] = data.copy() data.clear() if scanners: data = scanners[0].discovered_devices_and_advertisement_data data.clear() data.update( {device.address: (device, MagicMock()) for device in mock_discovered} ) yield for scanner in scanners: data = scanner.discovered_devices_and_advertisement_data data.clear() data.update(original_history[scanner])
Mock the combined best path to discovered devices from all the scanners.
def patch_discovered_devices(mock_discovered: list[BLEDevice]) -> None: """Mock the combined best path to discovered devices from all the scanners.""" manager = _get_manager() original_all_history = manager._all_history original_connectable_history = manager._connectable_history manager._connectable_history = {} manager._all_history = { device.address: MagicMock(device=device) for device in mock_discovered } yield manager._all_history = original_all_history manager._connectable_history = original_connectable_history
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Define a config entry fixture.
def config_entry_fixture() -> MockConfigEntry: """Define a config entry fixture.""" return MockConfigEntry( domain=DOMAIN, entry_id="uuid", unique_id="1234", data={"api_token": "123"}, )
Create a mock of the bluecurrent-api Client.
def create_client_mock( hass: HomeAssistant, future_container: FutureContainer, started_loop: Event, charge_point: dict, status: dict, grid: dict, ) -> MagicMock: """Create a mock of the bluecurrent-api Client.""" client_mock = MagicMock(spec=Client) received_charge_points = Event() async def wait_for_charge_points(): """Wait until chargepoints are received.""" await received_charge_points.wait() async def connect(receiver, on_open): """Set the receiver and await future.""" client_mock.receiver = receiver await on_open() started_loop.set() started_loop.clear() if future_container.future.done(): future_container.future = hass.loop.create_future() await future_container.future async def get_charge_points() -> None: """Send a list of charge points to the callback.""" await client_mock.receiver( { "object": "CHARGE_POINTS", "data": [charge_point], } ) received_charge_points.set() async def get_status(evse_id: str) -> None: """Send the status of a charge point to the callback.""" await client_mock.receiver( { "object": "CH_STATUS", "data": {"evse_id": evse_id} | status, } ) async def get_grid_status(evse_id: str) -> None: """Send the grid status to the callback.""" await client_mock.receiver({"object": "GRID_STATUS", "data": grid}) client_mock.connect.side_effect = connect client_mock.wait_for_charge_points.side_effect = wait_for_charge_points client_mock.get_charge_points.side_effect = get_charge_points client_mock.get_status.side_effect = get_status client_mock.get_grid_status.side_effect = get_grid_status return client_mock
Patch MyBMW login API calls.
def bmw_fixture( request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch ) -> Generator[respx.MockRouter, None, None]: """Patch MyBMW login API calls.""" # we use the library's mock router to mock the API calls, but only with a subset of vehicles router = MyBMWMockRouter( vehicles_to_load=[ "WBA00000000DEMO01", "WBA00000000DEMO02", "WBA00000000DEMO03", "WBY00000000REXI01", ], states=ALL_STATES, charging_settings=ALL_CHARGING_SETTINGS, ) # we don't want to wait when triggering a remote service monkeypatch.setattr( remote_services, "_POLLING_CYCLE", 0, ) with router: yield router
Mock logging in and setting a refresh token.
def login_sideeffect(self: MyBMWAuthentication): """Mock logging in and setting a refresh token.""" self.refresh_token = FIXTURE_REFRESH_TOKEN self.gcid = FIXTURE_GCID
Check if the last call was a successful remote service call.
def check_remote_service_call( router: respx.MockRouter, remote_service: str | None = None, remote_service_params: dict | None = None, remote_service_payload: dict | None = None, ): """Check if the last call was a successful remote service call.""" # Check if remote service call was made correctly if remote_service: # Get remote service call first_remote_service_call: respx.models.Call = next( c for c in router.calls if c.request.url.path.startswith(REMOTE_SERVICE_BASE_URL) or c.request.url.path.startswith( VEHICLE_CHARGING_BASE_URL.replace("/{vin}", "") ) ) assert ( first_remote_service_call.request.url.path.endswith(remote_service) is True ) assert first_remote_service_call.has_response is True assert first_remote_service_call.response.is_success is True # test params. # we don't test payload as this creates a lot of noise in the tests # and is end-to-end tested with the HA states if remote_service_params: assert ( dict(first_remote_service_call.request.url.params.items()) == remote_service_params ) # Now check final result last_event_status_call = next( c for c in reversed(router.calls) if c.request.url.path.endswith("eventStatus") ) assert last_event_status_call is not None assert ( last_event_status_call.request.url.path == "/eadrax-vrccs/v3/presentation/remote-commands/eventStatus" ) assert last_event_status_call.has_response is True assert last_event_status_call.response.is_success is True assert last_event_status_call.response.json() == {"eventStatus": "EXECUTED"}
Create a ceiling fan with given name with breeze support.
def ceiling_fan_with_breeze(name: str): """Create a ceiling fan with given name with breeze support.""" return { "name": name, "type": DeviceType.CEILING_FAN, "actions": ["SetSpeed", "SetDirection", "BreezeOn"], }
Patch async_setup_entry for specified domain.
def patch_setup_entry(domain: str, *, enabled: bool = True): """Patch async_setup_entry for specified domain.""" if not enabled: return nullcontext() return patch(f"homeassistant.components.bond.{domain}.async_setup_entry")
Patch Bond API version endpoint.
def patch_bond_version( enabled: bool = True, return_value: dict | None = None, side_effect=None ): """Patch Bond API version endpoint.""" if not enabled: return nullcontext() if return_value is None: return_value = { "bondid": "ZXXX12345", "target": "test-model", "fw_ver": "test-version", "mcu_ver": "test-hw-version", } return patch( "homeassistant.components.bond.Bond.version", return_value=return_value, side_effect=side_effect, )
Patch Bond API bridge endpoint.
def patch_bond_bridge( enabled: bool = True, return_value: dict | None = None, side_effect=None ): """Patch Bond API bridge endpoint.""" if not enabled: return nullcontext() if return_value is None: return_value = { "name": "bond-name", "location": "bond-location", "bluelight": 127, } return patch( "homeassistant.components.bond.Bond.bridge", return_value=return_value, side_effect=side_effect, )
Patch Bond API token endpoint.
def patch_bond_token( enabled: bool = True, return_value: dict | None = None, side_effect=None ): """Patch Bond API token endpoint.""" if not enabled: return nullcontext() if return_value is None: return_value = {"locked": 1} return patch( "homeassistant.components.bond.Bond.token", return_value=return_value, side_effect=side_effect, )
Patch Bond API devices endpoint.
def patch_bond_device_ids(enabled: bool = True, return_value=None, side_effect=None): """Patch Bond API devices endpoint.""" if not enabled: return nullcontext() if return_value is None: return_value = [] return patch( "homeassistant.components.bond.Bond.devices", return_value=return_value, side_effect=side_effect, )
Patch Bond API device endpoint.
def patch_bond_device(return_value=None): """Patch Bond API device endpoint.""" return patch( "homeassistant.components.bond.Bond.device", return_value=return_value, )
Patch start_bpup.
def patch_start_bpup(): """Patch start_bpup.""" return patch( "homeassistant.components.bond.start_bpup", return_value=MagicMock(), )
Patch Bond API action endpoint.
def patch_bond_action(): """Patch Bond API action endpoint.""" return patch("homeassistant.components.bond.Bond.action")
Patch Bond API action endpoint to throw ClientResponseError.
def patch_bond_action_returns_clientresponseerror(): """Patch Bond API action endpoint to throw ClientResponseError.""" return patch( "homeassistant.components.bond.Bond.action", side_effect=ClientResponseError( request_info=None, history=None, status=405, message="Method Not Allowed" ), )