示例#1
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up RainMachine as config entry."""
    session = aiohttp_client.async_get_clientsession(hass)
    client = Client(entry.data[CONF_PLACE_ID],
                    entry.data[CONF_SERVICE_ID],
                    session=session)

    async def async_get_pickup_events() -> list[PickupEvent]:
        """Get the next pickup."""
        try:
            return await client.async_get_pickup_events(
                start_date=date.today(),
                end_date=date.today() + timedelta(weeks=4))
        except RecollectError as err:
            raise UpdateFailed(
                f"Error while requesting data from ReCollect: {err}") from err

    coordinator = DataUpdateCoordinator(
        hass,
        LOGGER,
        name=
        f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
        update_interval=DEFAULT_UPDATE_INTERVAL,
        update_method=async_get_pickup_events,
    )

    await coordinator.async_config_entry_first_refresh()
    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = coordinator

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    entry.async_on_unload(entry.add_update_listener(async_reload_entry))

    return True
示例#2
0
    async def async_step_user(self, user_input: dict = None) -> dict:
        """Handle configuration via the UI."""
        if user_input is None:
            return self.async_show_form(step_id="user",
                                        data_schema=DATA_SCHEMA,
                                        errors={})

        unique_id = f"{user_input[CONF_PLACE_ID]}, {user_input[CONF_SERVICE_ID]}"

        await self.async_set_unique_id(unique_id)
        self._abort_if_unique_id_configured()

        session = aiohttp_client.async_get_clientsession(self.hass)
        client = Client(user_input[CONF_PLACE_ID],
                        user_input[CONF_SERVICE_ID],
                        session=session)

        try:
            await client.async_get_next_pickup_event()
        except RecollectError as err:
            LOGGER.error("Error during setup of integration: %s", err)
            return self.async_show_form(
                step_id="user",
                data_schema=DATA_SCHEMA,
                errors={"base": "invalid_place_or_service_id"},
            )

        return self.async_create_entry(
            title=unique_id,
            data={
                CONF_PLACE_ID: user_input[CONF_PLACE_ID],
                CONF_SERVICE_ID: user_input[CONF_SERVICE_ID],
            },
        )
示例#3
0
async def test_request_error(aresponses):
    """Test that an HTTP error raises a RequestError."""
    aresponses.add(
        "api.recollect.net",
        f"/api/places/{TEST_PLACE_ID}/services/{TEST_SERVICE_ID}/events",
        "get",
        aresponses.Response(text=None, status=502),
    )

    async with ClientSession() as session:
        with pytest.raises(RequestError):
            client = Client(TEST_PLACE_ID, TEST_SERVICE_ID, session=session)
            await client.async_get_pickup_events()
示例#4
0
async def test_get_next_pickup_event_none_left(aresponses):
    """Test throwing an error when there isn't a next pickup event."""
    aresponses.add(
        "api.recollect.net",
        f"/api/places/{TEST_PLACE_ID}/services/{TEST_SERVICE_ID}/events",
        "get",
        aresponses.Response(
            text=load_fixture("pickup_data_response_1.json"),
            status=200,
            headers={"Content-Type": "application/json"},
        ),
    )

    async with ClientSession() as session:
        client = Client(TEST_PLACE_ID, TEST_SERVICE_ID, session=session)
        with pytest.raises(DataError):
            await client.async_get_next_pickup_event()
示例#5
0
async def test_get_pickup_events(aresponses):
    """Test getting all available pickup events."""
    aresponses.add(
        "api.recollect.net",
        f"/api/places/{TEST_PLACE_ID}/services/{TEST_SERVICE_ID}/events",
        "get",
        aresponses.Response(
            text=load_fixture("pickup_data_response_1.json"),
            status=200,
            headers={"Content-Type": "application/json"},
        ),
    )

    async with ClientSession() as session:
        client = Client(TEST_PLACE_ID, TEST_SERVICE_ID, session=session)
        pickup_events = await client.async_get_pickup_events()

        assert len(pickup_events) == 6
示例#6
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up RainMachine as config entry."""
    session = aiohttp_client.async_get_clientsession(hass)
    client = Client(
        entry.data[CONF_PLACE_ID], entry.data[CONF_SERVICE_ID], session=session
    )

    async def async_get_pickup_events() -> List[PickupEvent]:
        """Get the next pickup."""
        try:
            return await client.async_get_pickup_events(
                start_date=date.today(), end_date=date.today() + timedelta(weeks=4)
            )
        except RecollectError as err:
            raise UpdateFailed(
                f"Error while requesting data from ReCollect: {err}"
            ) from err

    coordinator = DataUpdateCoordinator(
        hass,
        LOGGER,
        name=f"Place {entry.data[CONF_PLACE_ID]}, Service {entry.data[CONF_SERVICE_ID]}",
        update_interval=DEFAULT_UPDATE_INTERVAL,
        update_method=async_get_pickup_events,
    )

    await coordinator.async_refresh()

    if not coordinator.last_update_success:
        raise ConfigEntryNotReady

    hass.data[DOMAIN][DATA_COORDINATOR][entry.entry_id] = coordinator

    for platform in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, platform)
        )

    hass.data[DOMAIN][DATA_LISTENER][entry.entry_id] = entry.add_update_listener(
        async_reload_entry
    )

    return True
示例#7
0
async def test_get_pickup_events_in_range(aresponses):
    """Test getting pickup events within a date range."""
    aresponses.add(
        "api.recollect.net",
        f"/api/places/{TEST_PLACE_ID}/services/{TEST_SERVICE_ID}/events",
        "get",
        aresponses.Response(
            text=load_fixture("pickup_data_range_response.json"),
            status=200,
            headers={"Content-Type": "application/json"},
        ),
    )

    async with ClientSession() as session:
        client = Client(TEST_PLACE_ID, TEST_SERVICE_ID, session=session)
        pickup_events = await client.async_get_pickup_events(
            start_date=date(2020, 11, 1), end_date=date(2020, 11, 10))

        assert len(pickup_events) == 2
示例#8
0
async def test_get_next_pickup_event_oneshot(aresponses):
    """Test getting the next pickup event with an on-the-fly aiohttp session."""
    aresponses.add(
        "api.recollect.net",
        f"/api/places/{TEST_PLACE_ID}/services/{TEST_SERVICE_ID}/events",
        "get",
        aresponses.Response(
            text=load_fixture("pickup_data_response_1.json"),
            status=200,
            headers={"Content-Type": "application/json"},
        ),
    )

    client = Client(TEST_PLACE_ID, TEST_SERVICE_ID)
    next_pickup_event = await client.async_get_next_pickup_event()

    assert next_pickup_event.date == date(2020, 11, 2)
    assert next_pickup_event.pickup_types == [
        PickupType("garbage", "Trash"),
        PickupType("recycle"),
        PickupType("organics"),
    ]
    assert next_pickup_event.area_name == "Atlantis"
示例#9
0
async def test_get_next_pickup_event_type2(aresponses):
    """Test getting the next pickup event from data sample 2."""
    aresponses.add(
        "api.recollect.net",
        f"/api/places/{TEST_PLACE_ID}/services/{TEST_SERVICE_ID}/events",
        "get",
        aresponses.Response(
            text=load_fixture("pickup_data_response_2.json"),
            status=200,
            headers={"Content-Type": "application/json"},
        ),
    )

    async with ClientSession() as session:
        client = Client(TEST_PLACE_ID, TEST_SERVICE_ID, session=session)
        next_pickup_event = await client.async_get_next_pickup_event()

        assert next_pickup_event.date == date(2020, 12, 1)
        assert next_pickup_event.pickup_types == [
            PickupType("Recycling", "Recycling"),
            PickupType("Organics", "Organics"),
            PickupType("Garbage", "Garbage"),
        ]
        assert next_pickup_event.area_name == "GuelphON"
示例#10
0
async def test_get_next_pickup_event_same_day(aresponses):
    """Test always returning the next pickup event (even when today is an event)."""
    aresponses.add(
        "api.recollect.net",
        f"/api/places/{TEST_PLACE_ID}/services/{TEST_SERVICE_ID}/events",
        "get",
        aresponses.Response(
            text=load_fixture("pickup_data_response_1.json"),
            status=200,
            headers={"Content-Type": "application/json"},
        ),
    )

    async with ClientSession() as session:
        client = Client(TEST_PLACE_ID, TEST_SERVICE_ID, session=session)
        next_pickup_event = await client.async_get_next_pickup_event()

        assert next_pickup_event.date == date(2020, 11, 2)
        assert next_pickup_event.pickup_types == [
            PickupType("garbage", "Trash"),
            PickupType("recycle"),
            PickupType("organics"),
        ]
        assert next_pickup_event.area_name == "Atlantis"
示例#11
0
async def test_create_client():
    """Test creating a client and verifying its attributes."""
    client = Client(TEST_PLACE_ID, TEST_SERVICE_ID)

    assert client.place_id == TEST_PLACE_ID
    assert client.service_id == TEST_SERVICE_ID