Esempio n. 1
0
async def test_switches_states(hass: HomeAssistant,
                               aioclient_mock: AiohttpClientMocker):
    """Test we get sensor data."""
    await async_setup_platform(hass, aioclient_mock, DOMAIN)

    assert hass.states.get(
        f"switch.{DEFAULT_NAME}_usb_port_status").state == STATE_OFF
    assert hass.states.get(
        f"switch.{DEFAULT_NAME}_ac_port_status").state == STATE_ON
    entity_id = f"switch.{DEFAULT_NAME}_12v_port_status"
    assert hass.states.get(entity_id).state == STATE_OFF
    aioclient_mock.post(
        "http://1.2.3.4/state",
        text=load_fixture("goalzero/state_change.json"),
    )
    await hass.services.async_call(
        DOMAIN,
        SERVICE_TURN_ON,
        {ATTR_ENTITY_ID: [entity_id]},
        blocking=True,
    )
    assert hass.states.get(entity_id).state == STATE_ON
    aioclient_mock.clear_requests()
    aioclient_mock.post(
        "http://1.2.3.4/state",
        text=load_fixture("goalzero/state_data.json"),
    )
    await hass.services.async_call(
        DOMAIN,
        SERVICE_TURN_OFF,
        {ATTR_ENTITY_ID: [entity_id]},
        blocking=True,
    )
    assert hass.states.get(entity_id).state == STATE_OFF
Esempio n. 2
0
async def test_sensor_updates_with_empty_release_array(
    hass: HomeAssistant,
    init_integration: MockConfigEntry,
    aioclient_mock: AiohttpClientMocker,
) -> None:
    """Test the sensor updates by default GitHub sensors."""
    state = hass.states.get(TEST_SENSOR_ENTITY)
    assert state.state == "v1.0.0"

    response_json = json.loads(load_fixture("graphql.json", DOMAIN))
    response_json["data"]["repository"]["release"] = None
    headers = json.loads(load_fixture("base_headers.json", DOMAIN))

    aioclient_mock.clear_requests()
    aioclient_mock.get(
        f"https://api.github.com/repos/{TEST_REPOSITORY}/events",
        json=[],
        headers=headers,
    )
    aioclient_mock.post(
        "https://api.github.com/graphql",
        json=response_json,
        headers=headers,
    )

    async_fire_time_changed(hass, dt.utcnow() + FALLBACK_UPDATE_INTERVAL)
    await hass.async_block_till_done()

    new_state = hass.states.get(TEST_SENSOR_ENTITY)
    assert new_state.state == "unavailable"
Esempio n. 3
0
async def test_bad_alerts(
    hass: HomeAssistant,
    hass_ws_client,
    aioclient_mock: AiohttpClientMocker,
    ha_version,
    fixture,
    expected_alerts,
) -> None:
    """Test creating issues based on alerts."""
    fixture_content = load_fixture(fixture, "homeassistant_alerts")
    aioclient_mock.clear_requests()
    aioclient_mock.get(
        "https://alerts.home-assistant.io/alerts.json",
        text=fixture_content,
    )
    for alert in json.loads(fixture_content):
        stub_alert(aioclient_mock, alert["filename"])

    activated_components = (
        "darksky",
        "hikvision",
        "hikvisioncam",
    )
    for domain in activated_components:
        hass.config.components.add(domain)

    with patch(
            "homeassistant.components.homeassistant_alerts.__version__",
            ha_version,
    ):
        assert await async_setup_component(hass, DOMAIN, {})

    client = await hass_ws_client(hass)

    await client.send_json({"id": 1, "type": "repairs/list_issues"})
    msg = await client.receive_json()
    assert msg["success"]
    assert msg["result"] == {
        "issues": [{
            "breaks_in_ha_version": None,
            "created": ANY,
            "dismissed_version": None,
            "domain": "homeassistant_alerts",
            "ignored": False,
            "is_fixable": False,
            "issue_id": f"{alert}_{integration}",
            "issue_domain": integration,
            "learn_more_url": None,
            "severity": "warning",
            "translation_key": "alert",
            "translation_placeholders": {
                "title": f"Title for {alert}",
                "description": f"Content for {alert}",
            },
        } for alert, integration in expected_alerts]
    }
Esempio n. 4
0
async def test_scan_calendars(
    hass: HomeAssistant,
    component_setup: ComponentSetup,
    mock_calendars_list: ApiResult,
    mock_events_list: ApiResult,
    setup_config_entry: MockConfigEntry,
    aioclient_mock: AiohttpClientMocker,
) -> None:
    """Test finding a calendar from the API."""

    mock_calendars_list({"items": []})
    assert await component_setup()

    calendar_1 = {
        "id": "calendar-id-1",
        "summary": "Calendar 1",
    }
    calendar_2 = {
        "id": "calendar-id-2",
        "summary": "Calendar 2",
    }

    aioclient_mock.clear_requests()
    mock_calendars_list({"items": [calendar_1]})
    mock_events_list({}, calendar_id="calendar-id-1")
    await hass.services.async_call(DOMAIN,
                                   SERVICE_SCAN_CALENDARS, {},
                                   blocking=True)
    await hass.async_block_till_done()

    state = hass.states.get("calendar.calendar_1")
    assert state
    assert state.name == "Calendar 1"
    assert state.state == STATE_OFF
    assert not hass.states.get("calendar.calendar_2")

    aioclient_mock.clear_requests()
    mock_calendars_list({"items": [calendar_1, calendar_2]})
    mock_events_list({}, calendar_id="calendar-id-1")
    mock_events_list({}, calendar_id="calendar-id-2")
    await hass.services.async_call(DOMAIN,
                                   SERVICE_SCAN_CALENDARS, {},
                                   blocking=True)
    await hass.async_block_till_done()

    state = hass.states.get("calendar.calendar_1")
    assert state
    assert state.name == "Calendar 1"
    assert state.state == STATE_OFF
    state = hass.states.get("calendar.calendar_2")
    assert state
    assert state.name == "Calendar 2"
    assert state.state == STATE_OFF
Esempio n. 5
0
def mock_responses(
    aioclient_mock: AiohttpClientMocker,
    host: str = MOCK_HOST,
    fixture_set: str = "symo",
    inverter_ids: list[str | int] = [1],
    night: bool = False,
) -> None:
    """Mock responses for Fronius devices."""
    aioclient_mock.clear_requests()
    _night = "_night" if night else ""

    aioclient_mock.get(
        f"{host}/solar_api/GetAPIVersion.cgi",
        text=load_fixture(f"{fixture_set}/GetAPIVersion.json", "fronius"),
    )
    for inverter_id in inverter_ids:
        aioclient_mock.get(
            f"{host}/solar_api/v1/GetInverterRealtimeData.cgi?Scope=Device&"
            f"DeviceId={inverter_id}&DataCollection=CommonInverterData",
            text=load_fixture(
                f"{fixture_set}/GetInverterRealtimeData_Device_{inverter_id}{_night}.json",
                "fronius",
            ),
        )
    aioclient_mock.get(
        f"{host}/solar_api/v1/GetInverterInfo.cgi",
        text=load_fixture(f"{fixture_set}/GetInverterInfo.json", "fronius"),
    )
    aioclient_mock.get(
        f"{host}/solar_api/v1/GetLoggerInfo.cgi",
        text=load_fixture(f"{fixture_set}/GetLoggerInfo.json", "fronius"),
    )
    aioclient_mock.get(
        f"{host}/solar_api/v1/GetMeterRealtimeData.cgi?Scope=System",
        text=load_fixture(f"{fixture_set}/GetMeterRealtimeData.json",
                          "fronius"),
    )
    aioclient_mock.get(
        f"{host}/solar_api/v1/GetPowerFlowRealtimeData.fcgi",
        text=load_fixture(
            f"{fixture_set}/GetPowerFlowRealtimeData{_night}.json", "fronius"),
    )
    aioclient_mock.get(
        f"{host}/solar_api/v1/GetStorageRealtimeData.cgi?Scope=System",
        text=load_fixture(f"{fixture_set}/GetStorageRealtimeData.json",
                          "fronius"),
    )
    aioclient_mock.get(
        f"{host}/solar_api/v1/GetOhmPilotRealtimeData.cgi?Scope=System",
        text=load_fixture(f"{fixture_set}/GetOhmPilotRealtimeData.json",
                          "fronius"),
    )
Esempio n. 6
0
async def test_multiple_config_entries(
    hass: HomeAssistant,
    component_setup: ComponentSetup,
    mock_calendars_list: ApiResult,
    test_api_calendar: dict[str, Any],
    mock_events_list: ApiResult,
    config_entry: MockConfigEntry,
    aioclient_mock: AiohttpClientMocker,
) -> None:
    """Test finding a calendar from the API."""

    assert await component_setup()

    config_entry1 = MockConfigEntry(
        domain=DOMAIN, data=config_entry.data, unique_id=EMAIL_ADDRESS
    )
    calendar1 = {
        **test_api_calendar,
        "id": "calendar-id1",
        "summary": "Example Calendar 1",
    }

    mock_calendars_list({"items": [calendar1]})
    mock_events_list({}, calendar_id="calendar-id1")
    config_entry1.add_to_hass(hass)
    await hass.config_entries.async_setup(config_entry1.entry_id)
    await hass.async_block_till_done()

    state = hass.states.get("calendar.example_calendar_1")
    assert state
    assert state.state == STATE_OFF
    assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Example calendar 1"

    config_entry2 = MockConfigEntry(
        domain=DOMAIN, data=config_entry.data, unique_id="*****@*****.**"
    )
    calendar2 = {
        **test_api_calendar,
        "id": "calendar-id2",
        "summary": "Example Calendar 2",
    }
    aioclient_mock.clear_requests()
    mock_calendars_list({"items": [calendar2]})
    mock_events_list({}, calendar_id="calendar-id2")
    config_entry2.add_to_hass(hass)
    await hass.config_entries.async_setup(config_entry2.entry_id)
    await hass.async_block_till_done()

    state = hass.states.get("calendar.example_calendar_2")
    assert state
    assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Example calendar 2"
Esempio n. 7
0
async def test_failed_update_and_reconnection(
        hass: HomeAssistant, aioclient_mock: AiohttpClientMocker):
    """Test failed update and reconnection."""
    await setup_platform(hass, aioclient_mock, SENSOR_DOMAIN)
    assert hass.states.get("sensor.power_usage").state == "1580"
    aioclient_mock.clear_requests()
    await mock_responses(hass, aioclient_mock, error=True)
    next_update = dt_util.utcnow() + timedelta(seconds=30)
    async_fire_time_changed(hass, next_update)
    await hass.async_block_till_done()
    assert hass.states.get("sensor.power_usage").state == STATE_UNAVAILABLE
    aioclient_mock.clear_requests()
    await mock_responses(hass, aioclient_mock)
    next_update = dt_util.utcnow() + timedelta(seconds=30)
    async_fire_time_changed(hass, next_update)
    await hass.async_block_till_done()
    assert hass.states.get("sensor.power_usage").state == "1580"
Esempio n. 8
0
async def test_add_event_date_time(
    hass: HomeAssistant,
    component_setup: ComponentSetup,
    mock_calendars_list: ApiResult,
    mock_insert_event: Callable[[str, dict[str, Any]], None],
    test_api_calendar: dict[str, Any],
    mock_events_list: ApiResult,
    setup_config_entry: MockConfigEntry,
    aioclient_mock: AiohttpClientMocker,
    add_event_call_service: Callable[dict[str, Any], Awaitable[None]],
) -> None:
    """Test service call that adds an event with a date time range."""

    mock_calendars_list({"items": [test_api_calendar]})
    mock_events_list({})
    assert await component_setup()

    start_datetime = datetime.datetime.now()
    delta = datetime.timedelta(days=3, hours=3)
    end_datetime = start_datetime + delta

    aioclient_mock.clear_requests()
    mock_insert_event(
        calendar_id=CALENDAR_ID,
    )

    await add_event_call_service(
        {
            "start_date_time": start_datetime.isoformat(),
            "end_date_time": end_datetime.isoformat(),
        },
    )
    assert len(aioclient_mock.mock_calls) == 1
    assert aioclient_mock.mock_calls[0][2] == {
        "summary": TEST_EVENT_SUMMARY,
        "description": TEST_EVENT_DESCRIPTION,
        "start": {
            "dateTime": start_datetime.isoformat(timespec="seconds"),
            "timeZone": "America/Regina",
        },
        "end": {
            "dateTime": end_datetime.isoformat(timespec="seconds"),
            "timeZone": "America/Regina",
        },
    }
Esempio n. 9
0
async def test_failed_update_and_reconnection(
        hass: HomeAssistant, aioclient_mock: AiohttpClientMocker):
    """Test failed update and reconnection."""
    mock_responses(aioclient_mock)
    assert await async_setup_component(hass, SENSOR_DOMAIN,
                                       {SENSOR_DOMAIN: ONE_SENSOR_CONFIG})
    aioclient_mock.clear_requests()
    mock_responses(aioclient_mock, error=True)
    next_update = dt_util.utcnow() + timedelta(seconds=3)
    async_fire_time_changed(hass, next_update)
    await hass.async_block_till_done()
    assert hass.states.get("sensor.efergy_728386").state == STATE_UNAVAILABLE
    aioclient_mock.clear_requests()
    mock_responses(aioclient_mock)
    next_update = dt_util.utcnow() + timedelta(seconds=30)
    async_fire_time_changed(hass, next_update)
    await hass.async_block_till_done()
    assert hass.states.get("sensor.efergy_728386").state == "1628"
Esempio n. 10
0
async def test_availability(
    opp: OpenPeerPower, aioclient_mock: AiohttpClientMocker
) -> None:
    """Test entity availability."""
    now = dt_util.utcnow()

    with patch("openpeerpower.util.dt.utcnow", return_value=now):
        await setup_integration(opp, aioclient_mock)

    assert opp.states.get(UPCOMING_ENTITY_ID).state == "1"

    # state to unavailable
    aioclient_mock.clear_requests()
    mock_connection(aioclient_mock, error=True)

    future = now + timedelta(minutes=1)
    with patch("openpeerpower.util.dt.utcnow", return_value=future):
        async_fire_time_changed(opp, future)
        await opp.async_block_till_done()

    assert opp.states.get(UPCOMING_ENTITY_ID).state == STATE_UNAVAILABLE

    # state to available
    aioclient_mock.clear_requests()
    mock_connection(aioclient_mock)

    future += timedelta(minutes=1)
    with patch("openpeerpower.util.dt.utcnow", return_value=future):
        async_fire_time_changed(opp, future)
        await opp.async_block_till_done()

    assert opp.states.get(UPCOMING_ENTITY_ID).state == "1"

    # state to unavailable
    aioclient_mock.clear_requests()
    mock_connection(aioclient_mock, invalid_auth=True)

    future += timedelta(minutes=1)
    with patch("openpeerpower.util.dt.utcnow", return_value=future):
        async_fire_time_changed(opp, future)
        await opp.async_block_till_done()

    assert opp.states.get(UPCOMING_ENTITY_ID).state == STATE_UNAVAILABLE

    # state to available
    aioclient_mock.clear_requests()
    mock_connection(aioclient_mock)

    future += timedelta(minutes=1)
    with patch("openpeerpower.util.dt.utcnow", return_value=future):
        async_fire_time_changed(opp, future)
        await opp.async_block_till_done()

    assert opp.states.get(UPCOMING_ENTITY_ID).state == "1"
async def test_switch_error(
    hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog
) -> None:
    """Test error handling of the Modern Forms switches."""
    await init_integration(hass, aioclient_mock)

    aioclient_mock.clear_requests()
    aioclient_mock.post("http://192.168.1.123:80/mf", text="", status=400)

    with patch("homeassistant.components.modern_forms.ModernFormsDevice.update"):
        await hass.services.async_call(
            SWITCH_DOMAIN,
            SERVICE_TURN_ON,
            {ATTR_ENTITY_ID: "switch.modernformsfan_away_mode"},
            blocking=True,
        )
        await hass.async_block_till_done()

        state = hass.states.get("switch.modernformsfan_away_mode")
        assert state.state == STATE_OFF
        assert "Invalid response from API" in caplog.text
Esempio n. 12
0
async def test_no_alerts(
    hass: HomeAssistant,
    hass_ws_client,
    aioclient_mock: AiohttpClientMocker,
) -> None:
    """Test creating issues based on alerts."""

    aioclient_mock.clear_requests()
    aioclient_mock.get(
        "https://alerts.home-assistant.io/alerts.json",
        text="",
    )

    assert await async_setup_component(hass, DOMAIN, {})

    client = await hass_ws_client(hass)

    await client.send_json({"id": 1, "type": "repairs/list_issues"})
    msg = await client.receive_json()
    assert msg["success"]
    assert msg["result"] == {"issues": []}
Esempio n. 13
0
async def test_add_event_date(
    hass: HomeAssistant,
    component_setup: ComponentSetup,
    mock_calendars_list: ApiResult,
    test_api_calendar: dict[str, Any],
    mock_insert_event: Callable[[str, dict[str, Any]], None],
    mock_events_list: ApiResult,
    setup_config_entry: MockConfigEntry,
    aioclient_mock: AiohttpClientMocker,
    add_event_call_service: Callable[dict[str, Any], Awaitable[None]],
) -> None:
    """Test service call that sets a date range."""

    mock_calendars_list({"items": [test_api_calendar]})
    mock_events_list({})
    assert await component_setup()

    now = utcnow()
    today = now.date()
    end_date = today + datetime.timedelta(days=2)

    aioclient_mock.clear_requests()
    mock_insert_event(
        calendar_id=CALENDAR_ID,
    )

    await add_event_call_service(
        {
            "start_date": today.isoformat(),
            "end_date": end_date.isoformat(),
        },
    )
    assert len(aioclient_mock.mock_calls) == 1
    assert aioclient_mock.mock_calls[0][2] == {
        "summary": TEST_EVENT_SUMMARY,
        "description": TEST_EVENT_DESCRIPTION,
        "start": {"date": today.isoformat()},
        "end": {"date": end_date.isoformat()},
    }
Esempio n. 14
0
async def test_add_event_date_in_x(
    hass: HomeAssistant,
    component_setup: ComponentSetup,
    mock_calendars_list: ApiResult,
    mock_insert_event: Callable[[..., dict[str, Any]], None],
    test_api_calendar: dict[str, Any],
    mock_events_list: ApiResult,
    date_fields: dict[str, Any],
    start_timedelta: datetime.timedelta,
    end_timedelta: datetime.timedelta,
    setup_config_entry: MockConfigEntry,
    aioclient_mock: AiohttpClientMocker,
    add_event_call_service: Callable[dict[str, Any], Awaitable[None]],
) -> None:
    """Test service call that adds an event with various time ranges."""

    mock_calendars_list({"items": [test_api_calendar]})
    mock_events_list({})
    assert await component_setup()

    now = datetime.datetime.now()
    start_date = now + start_timedelta
    end_date = now + end_timedelta

    aioclient_mock.clear_requests()
    mock_insert_event(
        calendar_id=CALENDAR_ID,
    )

    await add_event_call_service(date_fields)
    assert len(aioclient_mock.mock_calls) == 1
    assert aioclient_mock.mock_calls[0][2] == {
        "summary": TEST_EVENT_SUMMARY,
        "description": TEST_EVENT_DESCRIPTION,
        "start": {"date": start_date.date().isoformat()},
        "end": {"date": end_date.date().isoformat()},
    }
Esempio n. 15
0
async def test_data_manager_webhook_subscription(
    hass: HomeAssistant,
    component_factory: ComponentFactory,
    aioclient_mock: AiohttpClientMocker,
) -> None:
    """Test data manager webhook subscriptions."""
    person0 = new_profile_config("person0", 0)
    await component_factory.configure_component(profile_configs=(person0, ))

    api: ConfigEntryWithingsApi = MagicMock(spec=ConfigEntryWithingsApi)
    data_manager = DataManager(
        hass,
        "person0",
        api,
        0,
        WebhookConfig(id="1234",
                      url="http://localhost/api/webhook/1234",
                      enabled=True),
    )

    # pylint: disable=protected-access
    data_manager._notify_subscribe_delay = datetime.timedelta(seconds=0)
    data_manager._notify_unsubscribe_delay = datetime.timedelta(seconds=0)

    api.notify_list.return_value = NotifyListResponse(profiles=(
        NotifyListProfile(
            appli=NotifyAppli.BED_IN,
            callbackurl="https://not.my.callback/url",
            expires=None,
            comment=None,
        ),
        NotifyListProfile(
            appli=NotifyAppli.BED_IN,
            callbackurl=data_manager.webhook_config.url,
            expires=None,
            comment=None,
        ),
        NotifyListProfile(
            appli=NotifyAppli.BED_OUT,
            callbackurl=data_manager.webhook_config.url,
            expires=None,
            comment=None,
        ),
    ))

    aioclient_mock.clear_requests()
    aioclient_mock.request(
        "HEAD",
        data_manager.webhook_config.url,
        status=200,
    )

    # Test subscribing
    await data_manager.async_subscribe_webhook()
    api.notify_subscribe.assert_any_call(data_manager.webhook_config.url,
                                         NotifyAppli.WEIGHT)
    api.notify_subscribe.assert_any_call(data_manager.webhook_config.url,
                                         NotifyAppli.CIRCULATORY)
    api.notify_subscribe.assert_any_call(data_manager.webhook_config.url,
                                         NotifyAppli.ACTIVITY)
    api.notify_subscribe.assert_any_call(data_manager.webhook_config.url,
                                         NotifyAppli.SLEEP)
    try:
        api.notify_subscribe.assert_any_call(data_manager.webhook_config.url,
                                             NotifyAppli.USER)
        assert False
    except AssertionError:
        pass
    try:
        api.notify_subscribe.assert_any_call(data_manager.webhook_config.url,
                                             NotifyAppli.BED_IN)
        assert False
    except AssertionError:
        pass
    try:
        api.notify_subscribe.assert_any_call(data_manager.webhook_config.url,
                                             NotifyAppli.BED_OUT)
        assert False
    except AssertionError:
        pass

    # Test unsubscribing.
    await data_manager.async_unsubscribe_webhook()
    api.notify_revoke.assert_any_call(data_manager.webhook_config.url,
                                      NotifyAppli.BED_IN)
    api.notify_revoke.assert_any_call(data_manager.webhook_config.url,
                                      NotifyAppli.BED_OUT)
Esempio n. 16
0
async def test_sensor_available(
    aioclient_mock: AiohttpClientMocker, hass: HomeAssistant
) -> None:
    """Test that the sensors are working."""
    # Totals Test
    aioclient_mock.get(
        "https://kubra.io/stormcenter/api/v1/stormcenters/39e6d9f3-fdea-4539-848f-b8631945da6f/views/74de8a50-3f45-4f6a-9483-fd618bb9165d/currentState?preview=false",
        json={"data": {"interval_generation_data": "data/TEST"}},
    )
    aioclient_mock.get(
        "https://kubra.io/data/TEST/public/reports/a36a6292-1c55-44de-a6a9-44fedf9482ee_report.json",
        json={
            "file_data": {
                "totals": {
                    "cust_a": {
                        "val": 123,
                    },
                    "percent_cust_a": {
                        "val": 1.23,
                    },
                    "n_out": 456,
                    "cust_s": 789,
                }
            }
        },
    )

    config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_ENTRY_DATA)
    config_entry.add_to_hass(hass)

    assert await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()
    assert hass.data[DOMAIN]

    entries = hass.config_entries.async_entries(DOMAIN)
    assert len(entries) == 1
    assert config_entry.state == ConfigEntryState.LOADED

    sensors_to_get = [
        "total_customers_out",
        "total_percent_customers_out",
        "total_outage_count",
        "total_customers_served",
    ]

    for sensor in sensors_to_get:
        sensor_entity = hass.states.get(f"sensor.{sensor}")
        assert sensor_entity is not None
        assert sensor_entity.state != "unavailable"

        if sensor == "total_customers_out":
            assert sensor_entity.state == "123"
        elif sensor == "total_percent_customers_out":
            assert sensor_entity.state == "15.589"
        elif sensor == "total_outage_count":
            assert sensor_entity.state == "456"
        elif sensor == "total_customers_served":
            assert sensor_entity.state == "789"

    # County Test
    aioclient_mock.clear_requests()
    aioclient_mock.get(
        "https://kubra.io/stormcenter/api/v1/stormcenters/39e6d9f3-fdea-4539-848f-b8631945da6f/views/74de8a50-3f45-4f6a-9483-fd618bb9165d/currentState?preview=false",
        json={"data": {"interval_generation_data": "data/TEST"}},
    )
    aioclient_mock.get(
        "https://kubra.io/data/TEST/public/reports/a36a6292-1c55-44de-a6a9-44fedf9482ee_report.json",
        json={
            "file_data": {
                "areas": [
                    {
                        "name": "BUCKS",
                        "cust_a": {
                            "val": 123,
                        },
                        "percent_cust_a": {
                            "val": 1.23,
                        },
                        "n_out": 456,
                        "cust_s": 789,
                    }
                ]
            }
        },
    )

    config_entry = MockConfigEntry(domain=DOMAIN, data=COUNTY_ENTRY_DATA)
    config_entry.add_to_hass(hass)

    assert await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()
    assert hass.data[DOMAIN]

    entries = hass.config_entries.async_entries(DOMAIN)
    assert len(entries) == 2
    assert config_entry.state == ConfigEntryState.LOADED

    sensors_to_get = [
        "bucks_customers_out",
        "bucks_percent_customers_out",
        "bucks_outage_count",
        "bucks_customers_served",
    ]

    for sensor in sensors_to_get:
        sensor_entity = hass.states.get(f"sensor.{sensor}")
        assert sensor_entity is not None
        assert sensor_entity.state != "unavailable"

        if sensor == "bucks_customers_out":
            assert sensor_entity.state == "123"
        elif sensor == "bucks_percent_customers_out":
            assert sensor_entity.state == "15.589"
        elif sensor == "bucks_outage_count":
            assert sensor_entity.state == "456"
        elif sensor == "bucks_customers_served":
            assert sensor_entity.state == "789"
Esempio n. 17
0
async def test_alerts_change(
    hass: HomeAssistant,
    hass_ws_client,
    aioclient_mock: AiohttpClientMocker,
    ha_version: str,
    fixture_1: str,
    expected_alerts_1: list[tuple(str, str)],
    fixture_2: str,
    expected_alerts_2: list[tuple(str, str)],
) -> None:
    """Test creating issues based on alerts."""
    fixture_1_content = load_fixture(fixture_1, "homeassistant_alerts")
    aioclient_mock.clear_requests()
    aioclient_mock.get(
        "https://alerts.home-assistant.io/alerts.json",
        text=fixture_1_content,
    )
    for alert in json.loads(fixture_1_content):
        stub_alert(aioclient_mock, alert["filename"])

    activated_components = (
        "aladdin_connect",
        "darksky",
        "hikvision",
        "hikvisioncam",
        "hive",
        "homematicip_cloud",
        "logi_circle",
        "neato",
        "nest",
        "senseme",
        "sochain",
    )
    for domain in activated_components:
        hass.config.components.add(domain)

    with patch(
            "homeassistant.components.homeassistant_alerts.__version__",
            ha_version,
    ):
        assert await async_setup_component(hass, DOMAIN, {})

    now = dt_util.utcnow()

    client = await hass_ws_client(hass)

    await client.send_json({"id": 1, "type": "repairs/list_issues"})
    msg = await client.receive_json()
    assert msg["success"]
    assert_lists_same(
        msg["result"]["issues"],
        [{
            "breaks_in_ha_version": None,
            "created": ANY,
            "dismissed_version": None,
            "domain": "homeassistant_alerts",
            "ignored": False,
            "is_fixable": False,
            "issue_id": f"{alert}_{integration}",
            "issue_domain": integration,
            "learn_more_url": None,
            "severity": "warning",
            "translation_key": "alert",
            "translation_placeholders": {
                "title": f"Title for {alert}",
                "description": f"Content for {alert}",
            },
        } for alert, integration in expected_alerts_1],
    )

    fixture_2_content = load_fixture(fixture_2, "homeassistant_alerts")
    aioclient_mock.clear_requests()
    aioclient_mock.get(
        "https://alerts.home-assistant.io/alerts.json",
        text=fixture_2_content,
    )
    for alert in json.loads(fixture_2_content):
        stub_alert(aioclient_mock, alert["filename"])

    future = now + UPDATE_INTERVAL + timedelta(seconds=1)
    async_fire_time_changed(hass, future)
    await hass.async_block_till_done()

    await client.send_json({"id": 2, "type": "repairs/list_issues"})
    msg = await client.receive_json()
    assert msg["success"]
    assert_lists_same(
        msg["result"]["issues"],
        [{
            "breaks_in_ha_version": None,
            "created": ANY,
            "dismissed_version": None,
            "domain": "homeassistant_alerts",
            "ignored": False,
            "is_fixable": False,
            "issue_id": f"{alert}_{integration}",
            "issue_domain": integration,
            "learn_more_url": None,
            "severity": "warning",
            "translation_key": "alert",
            "translation_placeholders": {
                "title": f"Title for {alert}",
                "description": f"Content for {alert}",
            },
        } for alert, integration in expected_alerts_2],
    )