Ejemplo n.º 1
0
async def async_setup_platform(
    hass: HomeAssistantType,
    config: ConfigType,
    async_add_entities: Callable,
    discovery_info: Optional[DiscoveryInfoType] = None,
) -> None:
    """Set up the sensor platform."""
    _LOGGER.debug("setup sensor for platform")
    session = async_get_clientsession(hass)

    if CONF_BASEURL in config:
        _LOGGER.warning("Baseurl is not supported anymore.")

    parser = RkiCovidParser(session)
    coordinator = await get_coordinator(hass, parser)

    if coordinator is None or coordinator.data is None:
        raise PlatformNotReady("Data coordinator could not be initialized!")

    districts = config[CONF_DISTRICTS]

    sensors = [
        RKICovidNumbersSensor(coordinator, district[CONF_DISTRICT_NAME],
                              info_type) for info_type in SENSORS
        for district in districts
    ]
    async_add_entities(sensors, update_before_add=True)
Ejemplo n.º 2
0
async def async_setup(hass: core.HomeAssistant, config: dict) -> bool:
    """Set up the component into HomeAssistant."""
    _LOGGER.debug("setup component.")
    parser = RkiCovidParser(async_get_clientsession(hass))

    # Make sure coordinator is initialized.
    await get_coordinator(hass, parser)

    # Return boolean to indicate that initialization was successful.
    return True
Ejemplo n.º 3
0
async def test_successful_form(hass, aiohttp_client):
    """Test a successful form with mock data."""
    parser = RkiCovidParser(aiohttp_client)
    parser.load_data = AsyncMock(return_value=None)
    parser.districts = MOCK_DISTRICTS
    parser.states = MOCK_STATES
    parser.country = MOCK_COUNTRY
    with patch(
            "rki_covid_parser.parser.RkiCovidParser",
            return_value=parser,
    ):
        # Setup persisten notifications (will be skipped through a fixture)
        await setup.async_setup_component(hass, "persistent_notification", {})

        # Initialize a config flow
        result = await hass.config_entries.flow.async_init(
            DOMAIN, context={"source": config_entries.SOURCE_USER})

        # Check that the config flow
        assert result["type"] == "form"
        assert result["errors"] == {}

        # Enter data into the config flow
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {"county": "SK Amberg"},
        )

        # Validate the result
        assert result2["type"] == "create_entry"
        assert result2["title"] == "SK Amberg"
        assert result2["data"] == {"county": "SK Amberg"}
        await hass.async_block_till_done()
Ejemplo n.º 4
0
async def test_successful_config_flow(hass, aiohttp_client):
    """Test a successful config flow with mock data."""
    parser = RkiCovidParser(aiohttp_client)
    parser.load_data = AsyncMock(return_value=None)
    parser.districts = MOCK_DISTRICTS
    parser.states = MOCK_STATES
    parser.country = MOCK_COUNTRY
    with patch(
            "rki_covid_parser.parser.RkiCovidParser",
            return_value=parser,
    ):
        # Initialize a config flow
        result = await hass.config_entries.flow.async_init(
            DOMAIN, context={"source": config_entries.SOURCE_USER})

        # Check that the config flow shows the user form
        assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
        assert result["step_id"] == "user"

        # Enter data into the config flow
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {"county": "SK Amberg"},
        )

        # Validate the result
        assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
        assert result["title"] == "SK Amberg"
        assert result["result"]
Ejemplo n.º 5
0
    async def async_step_user(self,
                              user_input: Optional[Dict[str, Any]] = None
                              ):  # type: ignore
        """Invoke when a user initiates a flow via the user interface."""
        _LOGGER.debug(
            f"User triggered configuration flow via UI. user_input: {user_input}"
        )

        parser = RkiCovidParser(async_get_clientsession(self.hass))

        errors: Dict[str, str] = {}

        if self._options is None:
            self._options = {}

            # add items from coordinator
            coordinator = await get_coordinator(self.hass, parser)
            for case in sorted(coordinator.data.values(),
                               key=lambda case: case.name):
                if case.county:
                    self._options[case.county] = case.county
                else:
                    self._options[case.name] = case.name

        if user_input is not None:
            await self.async_set_unique_id(user_input[ATTR_COUNTY])
            self._abort_if_unique_id_configured()

            # User is done adding sensors, create the config entry.
            _LOGGER.debug("Create entry from Configuration UI")
            return self.async_create_entry(
                title=self._options[user_input[ATTR_COUNTY]], data=user_input)

        # Show user input for adding sensors.
        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema(
                {vol.Required(ATTR_COUNTY): vol.In(self._options)}),
            errors=errors,
        )
Ejemplo n.º 6
0
async def async_setup_entry(
    hass: core.HomeAssistant,
    config_entry: config_entries.ConfigEntry,
    async_add_entities,
):
    """Create sensors from a config entry in the integrations UI."""
    _LOGGER.debug(f"create sensor from config entry {config_entry.data}")
    session = async_get_clientsession(hass)
    parser = RkiCovidParser(session)
    coordinator = await get_coordinator(hass, parser)

    if coordinator is None or coordinator.data is None:
        raise PlatformNotReady("Data coordinator could not be initialized!")

    try:
        district = config_entry.data[ATTR_COUNTY]
        sensors = [
            RKICovidNumbersSensor(coordinator, district, info_type)
            for info_type in SENSORS
        ]
        async_add_entities(sensors, update_before_add=True)
    except KeyError:
        _LOGGER.error("Could not determine %s from config!", ATTR_COUNTY)