async def _update_entry(self):
        try:
            entry = ConfigEntry(0,
                                "",
                                "",
                                self._data,
                                "",
                                "", {},
                                options=self._options)

            await self._config_manager.update(entry)
        except InvalidToken:
            _LOGGER.info("Reset password")

            del self._data[CONF_PASSWORD]

            entry = ConfigEntry(0,
                                "",
                                "",
                                self._data,
                                "",
                                "", {},
                                options=self._options)

            await self._config_manager.update(entry)
async def test_async_setup_entry_filter_all(mock_hass):
    config_entry = ConfigEntry(1, DOMAIN, "entry", {}, "source", "POLL", {})
    api = MagicMock()
    api.devices = {
        "light":
        Light(
            "light",
            "name",
            DeviceType.BASIC_LIGHT,
            DeviceMode(DeviceType.BASIC_LIGHT),
            list(),
        )
    }
    async_add_entries = AsyncAddEntries()
    mock_hass.data = {
        DOMAIN: {
            config_entry.entry_id: {
                ONYX_API: api,
                ONYX_COORDINATOR: None,
                ONYX_TIMEZONE: "UTC",
            }
        }
    }

    await async_setup_entry(mock_hass, config_entry, async_add_entries.call)
    assert async_add_entries.called_async_add_entities
    assert len(async_add_entries.data) == 0
Exemple #3
0
    def __init__(self):
        _LOGGER.info("Started")

        self._data = None
        self._config_manager = ConfigManager()

        data = {CONF_HOST: "", CONF_NAME: DEFAULT_NAME}

        config_entry: ConfigEntry = ConfigEntry(
            version=0,
            domain=DOMAIN,
            title=DEFAULT_NAME,
            data=data,
            source="",
            connection_class="",
            system_options={},
        )
        print("1.1")
        self._config_manager.update(config_entry)

        print("1.2")

        self._config_manager.data.file_reader = self.file_data_provider

        print("1.3")

        hass = HomeAssistant()

        print("1.4")

        self._device_data = HPDeviceData(hass, self._config_manager)
Exemple #4
0
async def test_setup_entry_error(hass: HomeAssistant):
    """Test for successfully setting a config entry."""
    with patch("huisbaasje.Huisbaasje.authenticate",
               side_effect=HuisbaasjeException) as mock_authenticate:
        hass.config.components.add(huisbaasje.DOMAIN)
        config_entry = ConfigEntry(
            1,
            huisbaasje.DOMAIN,
            "userId",
            {
                CONF_ID: "userId",
                CONF_USERNAME: "******",
                CONF_PASSWORD: "******",
            },
            "test",
            CONN_CLASS_CLOUD_POLL,
            system_options={},
        )
        hass.config_entries._entries.append(config_entry)

        assert config_entry.state == ENTRY_STATE_NOT_LOADED
        await hass.config_entries.async_setup(config_entry.entry_id)
        await hass.async_block_till_done()

        # Assert integration is loaded with error
        assert config_entry.state == ENTRY_STATE_SETUP_ERROR
        assert huisbaasje.DOMAIN not in hass.data

        # Assert entities are not loaded
        entities = hass.states.async_entity_ids("sensor")
        assert len(entities) == 0

        # Assert mocks are called
        assert len(mock_authenticate.mock_calls) == 1
Exemple #5
0
    def _get_prefix(self, user_set_prefix=""):
        prefix_entry = self.hass.config_entries.async_get_entry(
            CONF_MQTT_PREFIX)
        if prefix_entry is None:
            prefix_entry = ConfigEntry(
                version=1,
                domain=DOMAIN,
                entry_id=CONF_MQTT_PREFIX,
                data={CONF_MQTT_PREFIX: ""},
                source="calibration",
                title="~Calibration Prefix",
                connection_class=CONN_CLASS_UNKNOWN,
                options={},
                system_options={},
                unique_id=CONF_MQTT_PREFIX,
            )

            self.hass.async_create_task(
                self.hass.config_entries.async_add(prefix_entry))

        elif user_set_prefix is not None and prefix_entry.data[
                CONF_MQTT_PREFIX] != user_set_prefix:
            self.hass.config_entries.async_update_entry(
                prefix_entry, data={CONF_MQTT_PREFIX: user_set_prefix})
        return prefix_entry.data[CONF_MQTT_PREFIX]
Exemple #6
0
def test_flow_handler_async_profile_config_entry(
    hass: HomeAssistantType, flow_handler: WithingsFlowHandler
):
    """Test profile config entry."""
    config_entries = [
        ConfigEntry(
            version=1,
            domain=const.DOMAIN,
            title="AAA",
            data={},
            source="source",
            connection_class="connection_class",
            system_options={},
        ),
        ConfigEntry(
            version=1,
            domain=const.DOMAIN,
            title="Person 1",
            data={const.PROFILE: "Person 1"},
            source="source",
            connection_class="connection_class",
            system_options={},
        ),
        ConfigEntry(
            version=1,
            domain=const.DOMAIN,
            title="BBB",
            data={},
            source="source",
            connection_class="connection_class",
            system_options={},
        ),
    ]

    hass.config_entries.async_entries = MagicMock(return_value=config_entries)

    config_entry = flow_handler.async_profile_config_entry

    assert not config_entry("GGGG")
    hass.config_entries.async_entries.assert_called_with(const.DOMAIN)

    assert not config_entry("CCC")
    hass.config_entries.async_entries.assert_called_with(const.DOMAIN)

    assert config_entry("Person 1") == config_entries[1]
    hass.config_entries.async_entries.assert_called_with(const.DOMAIN)
    def _update_entry(self):
        entry = ConfigEntry(version=0,
                            domain="",
                            title="",
                            data=self.data,
                            source="",
                            options=self.options)

        self.config_manager.update(entry)
Exemple #8
0
def config_entry_fixture(hass, installed_app, location):
    """Fixture representing a config entry."""
    data = {
        CONF_ACCESS_TOKEN: str(uuid4()),
        CONF_INSTALLED_APP_ID: installed_app.installed_app_id,
        CONF_APP_ID: installed_app.app_id,
        CONF_LOCATION_ID: location.location_id
    }
    return ConfigEntry("1", DOMAIN, location.name, data, SOURCE_USER,
                       CONN_CLASS_CLOUD_PUSH)
Exemple #9
0
    def _update_entry(self):
        entry = ConfigEntry(0,
                            "",
                            "",
                            self.data,
                            "",
                            "", {},
                            options=self.options)

        self.config_manager.update(entry)
Exemple #10
0
async def _setup_platform(hass, *devices):
    """Set up the SmartThings light platform and prerequisites."""
    hass.config.components.add(DOMAIN)
    broker = DeviceBroker(hass, devices, '')
    config_entry = ConfigEntry("1", DOMAIN, "Test", {}, SOURCE_USER,
                               CONN_CLASS_CLOUD_PUSH)
    hass.data[DOMAIN] = {DATA_BROKERS: {config_entry.entry_id: broker}}
    await hass.config_entries.async_forward_entry_setup(config_entry, 'light')
    await hass.async_block_till_done()
    return config_entry
Exemple #11
0
async def test_async_setup_entry_credentials_saver(hass: HomeAssistantType):
    """Test method."""
    expected_creds = {
        "access_token": "my_access_token2",
        "refresh_token": "my_refresh_token2",
        "token_type": "my_token_type2",
        "expires_in": "2",
    }

    original_withings_api = WithingsApi
    withings_api_instance = None

    def new_withings_api(*args, **kwargs):
        nonlocal withings_api_instance
        withings_api_instance = original_withings_api(*args, **kwargs)
        withings_api_instance.request = MagicMock()
        return withings_api_instance

    withings_api_patch = patch("withings_api.WithingsApi",
                               side_effect=new_withings_api)
    session_patch = patch("requests_oauthlib.OAuth2Session")
    client_patch = patch("oauthlib.oauth2.WebApplicationClient")
    update_entry_patch = patch.object(
        hass.config_entries,
        "async_update_entry",
        wraps=hass.config_entries.async_update_entry,
    )

    with session_patch, client_patch, withings_api_patch, update_entry_patch:
        async_add_entities = MagicMock()
        hass.config_entries.async_update_entry = MagicMock()
        config_entry = ConfigEntry(
            version=1,
            domain=const.DOMAIN,
            title="my title",
            data={
                const.PROFILE: "Person 1",
                const.CREDENTIALS: {
                    "access_token": "my_access_token",
                    "refresh_token": "my_refresh_token",
                    "token_type": "my_token_type",
                    "token_expiry": "9999999999",
                },
            },
            source="source",
            connection_class="conn_class",
            system_options={},
        )

        await async_setup_entry(hass, config_entry, async_add_entities)

        withings_api_instance.set_token(expected_creds)

        new_creds = config_entry.data[const.CREDENTIALS]
        assert new_creds["access_token"] == "my_access_token2"
async def test_setup_entry(hass: HomeAssistant):
    """Test for successfully loading sensor states."""
    with patch(
        "huisbaasje.Huisbaasje.authenticate", return_value=None
    ) as mock_authenticate, patch(
        "huisbaasje.Huisbaasje.is_authenticated", return_value=True
    ) as mock_is_authenticated, patch(
        "huisbaasje.Huisbaasje.current_measurements",
        return_value=MOCK_CURRENT_MEASUREMENTS,
    ) as mock_current_measurements:

        hass.config.components.add(huisbaasje.DOMAIN)
        config_entry = ConfigEntry(
            1,
            huisbaasje.DOMAIN,
            "userId",
            {
                CONF_ID: "userId",
                CONF_USERNAME: "******",
                CONF_PASSWORD: "******",
            },
            "test",
            CONN_CLASS_CLOUD_POLL,
            system_options={},
        )
        hass.config_entries._entries.append(config_entry)

        assert await hass.config_entries.async_setup(config_entry.entry_id)
        await hass.async_block_till_done()

        # Assert data is loaded
        assert hass.states.get("sensor.huisbaasje_current_power").state == "1012.0"
        assert hass.states.get("sensor.huisbaasje_current_power_in").state == "1012.0"
        assert (
            hass.states.get("sensor.huisbaasje_current_power_in_low").state == "unknown"
        )
        assert hass.states.get("sensor.huisbaasje_current_power_out").state == "unknown"
        assert (
            hass.states.get("sensor.huisbaasje_current_power_out_low").state
            == "unknown"
        )
        assert hass.states.get("sensor.huisbaasje_current_gas").state == "0.0"
        assert hass.states.get("sensor.huisbaasje_energy_today").state == "3.3"
        assert hass.states.get("sensor.huisbaasje_energy_this_week").state == "17.5"
        assert hass.states.get("sensor.huisbaasje_energy_this_month").state == "103.3"
        assert hass.states.get("sensor.huisbaasje_energy_this_year").state == "673.0"
        assert hass.states.get("sensor.huisbaasje_gas_today").state == "1.1"
        assert hass.states.get("sensor.huisbaasje_gas_this_week").state == "5.6"
        assert hass.states.get("sensor.huisbaasje_gas_this_month").state == "39.1"
        assert hass.states.get("sensor.huisbaasje_gas_this_year").state == "116.7"

        # Assert mocks are called
        assert len(mock_authenticate.mock_calls) == 1
        assert len(mock_is_authenticated.mock_calls) == 1
        assert len(mock_current_measurements.mock_calls) == 1
Exemple #13
0
    async def _update_entry(self):
        try:
            entry = ConfigEntry(0,
                                "",
                                "",
                                self._data,
                                "",
                                "", {},
                                options=self._options)

            await self._config_manager.update(entry)
        except InvalidToken:
            entry = ConfigEntry(0,
                                "",
                                "",
                                self._data,
                                "",
                                "", {},
                                options=self._options)

            await self._config_manager.update(entry)
Exemple #14
0
async def setup_platform(hass, platform: str, *, devices=None, scenes=None):
    """Set up the SmartThings platform and prerequisites."""
    hass.config.components.add(DOMAIN)
    config_entry = ConfigEntry(2, DOMAIN, "Test",
                               {CONF_INSTALLED_APP_ID: str(uuid4())},
                               SOURCE_USER, CONN_CLASS_CLOUD_PUSH)
    broker = DeviceBroker(hass, config_entry, Mock(), Mock(), devices or [],
                          scenes or [])

    hass.data[DOMAIN] = {DATA_BROKERS: {config_entry.entry_id: broker}}
    await hass.config_entries.async_forward_entry_setup(config_entry, platform)
    await hass.async_block_till_done()
    return config_entry
Exemple #15
0
    async def _update_entry(self):
        try:
            entry = ConfigEntry(version=0,
                                domain="",
                                title="",
                                data=self._data,
                                source="",
                                options=self._options)

            await self._config_manager.update(entry)
        except InvalidToken:
            _LOGGER.info("Reset password")

            del self._data[CONF_PASSWORD]

            entry = ConfigEntry(version=0,
                                domain="",
                                title="",
                                data=self._data,
                                source="",
                                options=self._options)

            await self._config_manager.update(entry)
Exemple #16
0
async def test_unload_entry(hass: HomeAssistant):
    """Test for successfully unloading the config entry."""
    with patch("huisbaasje.Huisbaasje.authenticate",
               return_value=None) as mock_authenticate, patch(
                   "huisbaasje.Huisbaasje.is_authenticated",
                   return_value=True) as mock_is_authenticated, patch(
                       "huisbaasje.Huisbaasje.current_measurements",
                       return_value=MOCK_CURRENT_MEASUREMENTS,
                   ) as mock_current_measurements:
        hass.config.components.add(huisbaasje.DOMAIN)
        config_entry = ConfigEntry(
            1,
            huisbaasje.DOMAIN,
            "userId",
            {
                CONF_ID: "userId",
                CONF_USERNAME: "******",
                CONF_PASSWORD: "******",
            },
            "test",
            CONN_CLASS_CLOUD_POLL,
            system_options={},
        )
        hass.config_entries._entries.append(config_entry)

        # Load config entry
        assert await hass.config_entries.async_setup(config_entry.entry_id)
        await hass.async_block_till_done()
        assert config_entry.state == ENTRY_STATE_LOADED
        entities = hass.states.async_entity_ids("sensor")
        assert len(entities) == 14

        # Unload config entry
        await hass.config_entries.async_unload(config_entry.entry_id)
        assert config_entry.state == ENTRY_STATE_NOT_LOADED
        entities = hass.states.async_entity_ids("sensor")
        assert len(entities) == 14
        for entity in entities:
            assert hass.states.get(entity).state == STATE_UNAVAILABLE

        # Remove config entry
        await hass.config_entries.async_remove(config_entry.entry_id)
        await hass.async_block_till_done()
        entities = hass.states.async_entity_ids("sensor")
        assert len(entities) == 0

        # Assert mocks are called
        assert len(mock_authenticate.mock_calls) == 1
        assert len(mock_is_authenticated.mock_calls) == 1
        assert len(mock_current_measurements.mock_calls) == 1
Exemple #17
0
async def test_setup_entry(hass: HomeAssistant):
    """Test for successfully setting a config entry."""
    with patch("huisbaasje.Huisbaasje.authenticate",
               return_value=None) as mock_authenticate, patch(
                   "huisbaasje.Huisbaasje.is_authenticated",
                   return_value=True) as mock_is_authenticated, patch(
                       "huisbaasje.Huisbaasje.current_measurements",
                       return_value=MOCK_CURRENT_MEASUREMENTS,
                   ) as mock_current_measurements:
        hass.config.components.add(huisbaasje.DOMAIN)
        config_entry = ConfigEntry(
            1,
            huisbaasje.DOMAIN,
            "userId",
            {
                CONF_ID: "userId",
                CONF_USERNAME: "******",
                CONF_PASSWORD: "******",
            },
            "test",
            CONN_CLASS_CLOUD_POLL,
            system_options={},
        )
        hass.config_entries._entries.append(config_entry)

        assert config_entry.state == ENTRY_STATE_NOT_LOADED
        assert await hass.config_entries.async_setup(config_entry.entry_id)
        await hass.async_block_till_done()

        # Assert integration is loaded
        assert config_entry.state == ENTRY_STATE_LOADED
        assert huisbaasje.DOMAIN in hass.config.components
        assert huisbaasje.DOMAIN in hass.data
        assert config_entry.entry_id in hass.data[huisbaasje.DOMAIN]

        # Assert entities are loaded
        entities = hass.states.async_entity_ids("sensor")
        assert len(entities) == 14

        # Assert mocks are called
        assert len(mock_authenticate.mock_calls) == 1
        assert len(mock_is_authenticated.mock_calls) == 1
        assert len(mock_current_measurements.mock_calls) == 1
async def test_async_setup_entry(mock_hass):
    config_entry = ConfigEntry(
        1, DOMAIN, "entry", {CONF_NAME: "name"}, "source", "POLL", {}
    )

    class AsyncAddEntries:
        def __init__(self):
            self.called_async_add_entities = False

        def call(self, sensors, boolean):
            self.called_async_add_entities = True

    async_add_entries = AsyncAddEntries()

    mock_hass.data.return_value = {
        DOMAIN: {"entry_id": {LEDPI_API: None, LEDPI_COORDINATOR: None}}
    }

    await async_setup_entry(mock_hass, config_entry, async_add_entries.call)
    assert async_add_entries.called_async_add_entities
async def test_token_already_setup(hass):
    """Test an error is shown when the token is already setup."""
    flow = SmartThingsFlowHandler()
    flow.hass = hass
    token = str(uuid4())
    entries = [
        ConfigEntry(version='',
                    domain='',
                    title='',
                    data={'access_token': token},
                    source='',
                    connection_class='')
    ]

    with patch.object(hass.config_entries,
                      'async_entries',
                      return_value=entries):
        result = await flow.async_step_user({'access_token': token})

    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'user'
    assert result['errors'] == {'access_token': 'token_already_setup'}
Exemple #20
0
    async def async_step_pubsub(self,
                                user_input: dict[str, Any] | None = None
                                ) -> FlowResult:
        """Configure and create Pub/Sub subscriber."""
        # Populate data from the previous config entry during reauth, then
        # overwrite with the user entered values.
        data = {}
        if self._reauth:
            data.update(self._data)
        if user_input:
            data.update(user_input)
        cloud_project_id = data.get(CONF_CLOUD_PROJECT_ID, "")

        errors = {}
        config = self.hass.data[DOMAIN][DATA_NEST_CONFIG]
        if cloud_project_id == config[CONF_PROJECT_ID]:
            _LOGGER.error(
                "Wrong Project ID. Device Access Project ID used, but expected Cloud Project ID"
            )
            errors[CONF_CLOUD_PROJECT_ID] = "wrong_project_id"

        if user_input is not None and not errors:
            # Create the subscriber id and/or verify it already exists. Note that
            # the existing id is used, and create call below is idempotent
            subscriber_id = data.get(CONF_SUBSCRIBER_ID, "")
            if not subscriber_id:
                subscriber_id = _generate_subscription_id(cloud_project_id)
            _LOGGER.debug("Creating subscriber id '%s'", subscriber_id)
            # Create a placeholder ConfigEntry to use since with the auth we've already created.
            entry = ConfigEntry(version=1,
                                domain=DOMAIN,
                                title="",
                                data=self._data,
                                source="")
            subscriber = await api.new_subscriber_with_impl(
                self.hass, entry, subscriber_id, self.flow_impl)
            try:
                await subscriber.create_subscription()
            except AuthException as err:
                _LOGGER.error("Subscriber authentication error: %s", err)
                return self.async_abort(reason="invalid_access_token")
            except ConfigurationException as err:
                _LOGGER.error("Configuration error creating subscription: %s",
                              err)
                errors[CONF_CLOUD_PROJECT_ID] = "bad_project_id"
            except SubscriberException as err:
                _LOGGER.error("Error creating subscription: %s", err)
                errors[CONF_CLOUD_PROJECT_ID] = "subscriber_error"
            if not errors:

                try:
                    device_manager = await subscriber.async_get_device_manager(
                    )
                except ApiException as err:
                    # Generating a user friendly home name is best effort
                    _LOGGER.debug("Error fetching structures: %s", err)
                else:
                    self._structure_config_title = generate_config_title(
                        device_manager.structures.values())

                self._data.update({
                    CONF_SUBSCRIBER_ID: subscriber_id,
                    CONF_CLOUD_PROJECT_ID: cloud_project_id,
                })
                return await self.async_step_finish()

        return self.async_show_form(
            step_id="pubsub",
            data_schema=vol.Schema({
                vol.Required(CONF_CLOUD_PROJECT_ID, default=cloud_project_id):
                str,
            }),
            description_placeholders={"url": CLOUD_CONSOLE_URL},
            errors=errors,
        )
Exemple #21
0
    def update_config_data(self, data: dict, options: dict = None):
        entry = ConfigEntry(0, "", "", data, "", "", {}, options=options)

        self.config_manager.update(entry)