async def test_trigger_entity_restore_state(hass, count, domain, config,
                                            restored_state, initial_state):
    """Test restoring trigger template binary sensor."""

    fake_state = State(
        "binary_sensor.test",
        restored_state,
        {},
    )
    fake_extra_data = {
        "auto_off_time": None,
    }
    mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data), ))
    with assert_setup_component(count, domain):
        assert await async_setup_component(
            hass,
            domain,
            config,
        )

        await hass.async_block_till_done()
        await hass.async_start()
        await hass.async_block_till_done()

    state = hass.states.get("binary_sensor.test")
    assert state.state == initial_state
Example #2
0
async def test_trigger_entity_restore_state_auto_off_expired(
        hass, count, domain, config, freezer):
    """Test restoring trigger template binary sensor."""

    freezer.move_to("2022-02-02 12:02:00+00:00")
    fake_state = State(
        "binary_sensor.test",
        ON,
        {},
    )
    fake_extra_data = {
        "auto_off_time": {
            "__type":
            "<class 'datetime.datetime'>",
            "isoformat":
            datetime(2022, 2, 2, 12, 2, 0, tzinfo=timezone.utc).isoformat(),
        },
    }
    mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data), ))
    with assert_setup_component(count, domain):
        assert await async_setup_component(
            hass,
            domain,
            config,
        )

        await hass.async_block_till_done()
        await hass.async_start()
        await hass.async_block_till_done()

    state = hass.states.get("binary_sensor.test")
    assert state.state == OFF
Example #3
0
async def test_restore_state(hass: ha.HomeAssistant, entity_id, delta, freezer):
    """Test energy sensors restore state."""
    fake_state = ha.State(
        entity_id,
        "",
    )
    fake_extra_data = {
        "native_value": 2**20,
        "native_unit_of_measurement": None,
    }
    mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data),))

    assert await async_setup_component(
        hass, SENSOR_DOMAIN, {SENSOR_DOMAIN: {"platform": DOMAIN}}
    )
    await hass.async_block_till_done()

    state = hass.states.get(entity_id)
    assert state.state == str(2**20)

    freezer.tick(timedelta(minutes=5, seconds=1))
    await hass.async_block_till_done()
    await hass.async_block_till_done()

    state = hass.states.get(entity_id)
    assert state.state == str(2**20 + delta)
Example #4
0
async def test_restore_sensor_restore_state(
    hass,
    enable_custom_integrations,
    hass_storage,
    native_value,
    native_value_type,
    extra_data,
    device_class,
    uom,
):
    """Test RestoreSensor."""
    mock_restore_cache_with_extra_data(hass, ((State("sensor.test", ""), extra_data),))

    platform = getattr(hass.components, "test.sensor")
    platform.init(empty=True)
    platform.ENTITIES["0"] = platform.MockRestoreSensor(
        name="Test",
        device_class=device_class,
    )

    entity0 = platform.ENTITIES["0"]
    assert await async_setup_component(hass, "sensor", {"sensor": {"platform": "test"}})
    await hass.async_block_till_done()

    assert hass.states.get(entity0.entity_id)

    assert entity0.native_value == native_value
    assert type(entity0.native_value) == native_value_type
    assert entity0.native_unit_of_measurement == uom
Example #5
0
async def test_restore_native_value(hass, mqtt_mock_entry_with_yaml_config):
    """Test that the stored native_value is restored."""
    topic = "test/number"

    RESTORE_DATA = {
        "native_max_value": None,  # Ignored by MQTT number
        "native_min_value": None,  # Ignored by MQTT number
        "native_step": None,  # Ignored by MQTT number
        "native_unit_of_measurement": None,  # Ignored by MQTT number
        "native_value": 100.0,
    }

    mock_restore_cache_with_extra_data(
        hass, ((ha.State("number.test_number", "abc"), RESTORE_DATA), ))
    assert await async_setup_component(
        hass,
        number.DOMAIN,
        {
            "number": {
                "platform": "mqtt",
                "command_topic": topic,
                "device_class": "temperature",
                "unit_of_measurement": TEMP_FAHRENHEIT,
                "name": "Test Number",
            }
        },
    )
    await hass.async_block_till_done()
    await mqtt_mock_entry_with_yaml_config()

    state = hass.states.get("number.test_number")
    assert state.state == "37.8"
    assert state.attributes.get(ATTR_ASSUMED_STATE)
async def test_trigger_entity_restore_state(
    hass,
    count,
    domain,
    config,
    restored_state,
    restored_native_value,
    initial_state,
    initial_attributes,
):
    """Test restoring trigger template binary sensor."""

    restored_attributes = {
        "entity_picture": "/local/cats.png",
        "icon": "mdi:ship",
        "plus_one": 55,
    }

    fake_state = State(
        "sensor.test",
        restored_state,
        restored_attributes,
    )
    fake_extra_data = {
        "native_value": restored_native_value,
        "native_unit_of_measurement": None,
    }
    mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data), ))
    with assert_setup_component(count, domain):
        assert await async_setup_component(
            hass,
            domain,
            config,
        )

        await hass.async_block_till_done()
        await hass.async_start()
        await hass.async_block_till_done()

    state = hass.states.get("sensor.test")
    assert state.state == initial_state
    for attr in restored_attributes:
        if attr in initial_attributes:
            assert state.attributes[attr] == restored_attributes[attr]
        else:
            assert attr not in state.attributes
    assert "another" not in state.attributes

    hass.bus.async_fire("test_event", {"beer": 2})
    await hass.async_block_till_done()

    state = hass.states.get("sensor.test")
    assert state.state == "2"
    assert state.attributes["icon"] == "mdi:pirate"
    assert state.attributes["entity_picture"] == "/local/dogs.png"
    assert state.attributes["plus_one"] == 3
    assert state.attributes["another"] == 1
Example #7
0
async def test_number_restore_and_respond(hass: HomeAssistant,
                                          knx: KNXTestKit):
    """Test KNX number with passive_address and respond_to_read restoring state."""
    test_address = "1/1/1"
    test_passive_address = "3/3/3"

    RESTORE_DATA = {
        "native_max_value": None,  # Ignored by KNX number
        "native_min_value": None,  # Ignored by KNX number
        "native_step": None,  # Ignored by KNX number
        "native_unit_of_measurement": None,  # Ignored by KNX number
        "native_value": 160.0,
    }

    mock_restore_cache_with_extra_data(
        hass, ((State("number.test", "abc"), RESTORE_DATA), ))
    await knx.setup_integration({
        NumberSchema.PLATFORM: {
            CONF_NAME: "test",
            KNX_ADDRESS: [test_address, test_passive_address],
            CONF_RESPOND_TO_READ: True,
            CONF_TYPE: "illuminance",
        }
    })
    # restored state - doesn't send telegram
    state = hass.states.get("number.test")
    assert state.state == "160.0"
    assert state.attributes.get("unit_of_measurement") == "lx"
    await knx.assert_telegram_count(0)

    # respond with restored state
    await knx.receive_read(test_address)
    await knx.assert_response(test_address, (0x1F, 0xD0))

    # don't respond to passive address
    await knx.receive_read(test_passive_address)
    await knx.assert_no_telegram()

    # update from KNX passive address
    await knx.receive_write(test_passive_address, (0x4E, 0xDE))
    state = hass.states.get("number.test")
    assert state.state == "9000.96"
Example #8
0
async def test_skip_restoring_state_with_over_due_expire_trigger(
        hass, mqtt_mock_entry_with_yaml_config, caplog, freezer):
    """Test restoring a state with over due expire timer."""

    freezer.move_to("2022-02-02 12:02:00+01:00")
    domain = sensor.DOMAIN
    config3 = copy.deepcopy(DEFAULT_CONFIG[domain])
    config3["name"] = "test3"
    config3["expire_after"] = 10
    config3["state_topic"] = "test-topic3"
    fake_state = ha.State(
        "sensor.test3",
        "300",
        {},
        last_changed=datetime.fromisoformat("2022-02-02 12:01:35+01:00"),
    )
    fake_extra_data = MagicMock()
    mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data), ))

    with assert_setup_component(1, domain):
        assert await async_setup_component(hass, domain, {domain: config3})
        await hass.async_block_till_done()
        await mqtt_mock_entry_with_yaml_config()
    assert "Skip state recovery after reload for sensor.test3" in caplog.text
Example #9
0
async def test_restore_state(mock_heat_meter, hass):
    """Test sensor restore state."""
    # Home assistant is not running yet
    hass.state = CoreState.not_running
    last_reset = "2022-07-01T00:00:00.000000+00:00"
    mock_restore_cache_with_extra_data(
        hass,
        [
            (
                State(
                    "sensor.heat_meter_heat_usage",
                    "34167",
                    attributes={
                        ATTR_LAST_RESET: last_reset,
                        ATTR_UNIT_OF_MEASUREMENT: ENERGY_MEGA_WATT_HOUR,
                        ATTR_STATE_CLASS: SensorStateClass.TOTAL,
                    },
                ),
                {
                    "native_value": 34167,
                    "native_unit_of_measurement": ENERGY_MEGA_WATT_HOUR,
                    "icon": "mdi:fire",
                    "last_reset": last_reset,
                },
            ),
            (
                State(
                    "sensor.heat_meter_volume_usage",
                    "456",
                    attributes={
                        ATTR_LAST_RESET: last_reset,
                        ATTR_UNIT_OF_MEASUREMENT: VOLUME_CUBIC_METERS,
                        ATTR_STATE_CLASS: SensorStateClass.TOTAL,
                    },
                ),
                {
                    "native_value": 456,
                    "native_unit_of_measurement": VOLUME_CUBIC_METERS,
                    "icon": "mdi:fire",
                    "last_reset": last_reset,
                },
            ),
            (
                State(
                    "sensor.heat_meter_device_number",
                    "devicenr_789",
                    attributes={
                        ATTR_LAST_RESET: last_reset,
                    },
                ),
                {
                    "native_value": "devicenr_789",
                    "native_unit_of_measurement": None,
                    "last_reset": last_reset,
                },
            ),
        ],
    )
    entry_data = {
        "device": "/dev/USB0",
        "model": "LUGCUH50",
        "device_number": "123456789",
    }

    # create and add entry
    mock_entry = MockConfigEntry(domain=DOMAIN,
                                 unique_id=DOMAIN,
                                 data=entry_data)
    mock_entry.add_to_hass(hass)

    await hass.config_entries.async_setup(mock_entry.entry_id)
    await async_setup_component(hass, HA_DOMAIN, {})
    await hass.async_block_till_done()

    # restore from cache
    state = hass.states.get("sensor.heat_meter_heat_usage")
    assert state
    assert state.state == "34167"
    assert state.attributes.get(
        ATTR_UNIT_OF_MEASUREMENT) == ENERGY_MEGA_WATT_HOUR
    assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.TOTAL

    state = hass.states.get("sensor.heat_meter_volume_usage")
    assert state
    assert state.state == "456"
    assert state.attributes.get(
        ATTR_UNIT_OF_MEASUREMENT) == VOLUME_CUBIC_METERS
    assert state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.TOTAL

    state = hass.states.get("sensor.heat_meter_device_number")
    assert state
    print("STATE IS: ", state)
    assert state.state == "devicenr_789"
    assert state.attributes.get(ATTR_STATE_CLASS) is None
Example #10
0
async def test_restore_state(hass, yaml_config, config_entry_config):
    """Test utility sensor restore state."""
    # Home assistant is not runnit yet
    hass.state = CoreState.not_running

    last_reset = "2020-12-21T00:00:00.013073+00:00"

    mock_restore_cache_with_extra_data(
        hass,
        [
            (
                State(
                    "sensor.energy_bill_onpeak",
                    "3",
                    attributes={
                        ATTR_STATUS: PAUSED,
                        ATTR_LAST_RESET: last_reset,
                        ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR,
                    },
                ),
                {
                    "native_value": {
                        "__type": "<class 'decimal.Decimal'>",
                        "decimal_str": "3",
                    },
                    "native_unit_of_measurement": "kWh",
                    "last_reset": last_reset,
                    "last_period": "7",
                    "status": "paused",
                },
            ),
            (
                State(
                    "sensor.energy_bill_midpeak",
                    "5",
                    attributes={
                        ATTR_STATUS: PAUSED,
                        ATTR_LAST_RESET: last_reset,
                        ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR,
                    },
                ),
                {
                    "native_value": {
                        "__type": "<class 'decimal.Decimal'>",
                        "decimal_str": "3",
                    },
                    "native_unit_of_measurement": "kWh",
                },
            ),
            (
                State(
                    "sensor.energy_bill_offpeak",
                    "6",
                    attributes={
                        ATTR_STATUS: COLLECTING,
                        ATTR_LAST_RESET: last_reset,
                        ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR,
                    },
                ),
                {
                    "native_value": {
                        "__type": "<class 'decimal.Decimal'>",
                        "decimal_str": "3f",
                    },
                    "native_unit_of_measurement": "kWh",
                },
            ),
            (
                State(
                    "sensor.energy_bill_superpeak",
                    "error",
                    attributes={
                        ATTR_STATUS: COLLECTING,
                        ATTR_LAST_RESET: last_reset,
                        ATTR_UNIT_OF_MEASUREMENT: ENERGY_KILO_WATT_HOUR,
                    },
                ),
                {},
            ),
        ],
    )

    if yaml_config:
        assert await async_setup_component(hass, DOMAIN, yaml_config)
        await hass.async_block_till_done()
    else:
        config_entry = MockConfigEntry(
            data={},
            domain=DOMAIN,
            options=config_entry_config,
            title=config_entry_config["name"],
        )
        config_entry.add_to_hass(hass)
        assert await hass.config_entries.async_setup(config_entry.entry_id)
        await hass.async_block_till_done()

    # restore from cache
    state = hass.states.get("sensor.energy_bill_onpeak")
    assert state.state == "3"
    assert state.attributes.get("status") == PAUSED
    assert state.attributes.get("last_reset") == last_reset
    assert state.attributes.get(
        ATTR_UNIT_OF_MEASUREMENT) == ENERGY_KILO_WATT_HOUR

    state = hass.states.get("sensor.energy_bill_midpeak")
    assert state.state == "5"

    state = hass.states.get("sensor.energy_bill_offpeak")
    assert state.state == "6"
    assert state.attributes.get("status") == COLLECTING
    assert state.attributes.get("last_reset") == last_reset
    assert state.attributes.get(
        ATTR_UNIT_OF_MEASUREMENT) == ENERGY_KILO_WATT_HOUR

    state = hass.states.get("sensor.energy_bill_superpeak")
    assert state.state == STATE_UNKNOWN

    # utility_meter is loaded, now set sensors according to utility_meter:
    hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
    await hass.async_block_till_done()

    state = hass.states.get("select.energy_bill")
    assert state.state == "onpeak"

    state = hass.states.get("sensor.energy_bill_onpeak")
    assert state.attributes.get("status") == COLLECTING

    state = hass.states.get("sensor.energy_bill_offpeak")
    assert state.attributes.get("status") == PAUSED
Example #11
0
async def test_run_number_service_optimistic_with_command_template(
        hass, mqtt_mock_entry_with_yaml_config):
    """Test that set_value service works in optimistic mode and with a command_template."""
    topic = "test/number"

    RESTORE_DATA = {
        "native_max_value": None,  # Ignored by MQTT number
        "native_min_value": None,  # Ignored by MQTT number
        "native_step": None,  # Ignored by MQTT number
        "native_unit_of_measurement": None,  # Ignored by MQTT number
        "native_value": 3,
    }

    mock_restore_cache_with_extra_data(
        hass, ((ha.State("number.test_number", "abc"), RESTORE_DATA), ))
    assert await async_setup_component(
        hass,
        number.DOMAIN,
        {
            "number": {
                "platform": "mqtt",
                "command_topic": topic,
                "name": "Test Number",
                "command_template": '{"number": {{ value }} }',
            }
        },
    )
    await hass.async_block_till_done()
    mqtt_mock = await mqtt_mock_entry_with_yaml_config()

    state = hass.states.get("number.test_number")
    assert state.state == "3"
    assert state.attributes.get(ATTR_ASSUMED_STATE)

    # Integer
    await hass.services.async_call(
        NUMBER_DOMAIN,
        SERVICE_SET_VALUE,
        {
            ATTR_ENTITY_ID: "number.test_number",
            ATTR_VALUE: 30
        },
        blocking=True,
    )

    mqtt_mock.async_publish.assert_called_once_with(topic, '{"number": 30 }',
                                                    0, False)
    mqtt_mock.async_publish.reset_mock()
    state = hass.states.get("number.test_number")
    assert state.state == "30"

    # Float with no decimal -> integer
    await hass.services.async_call(
        NUMBER_DOMAIN,
        SERVICE_SET_VALUE,
        {
            ATTR_ENTITY_ID: "number.test_number",
            ATTR_VALUE: 42.0
        },
        blocking=True,
    )

    mqtt_mock.async_publish.assert_called_once_with(topic, '{"number": 42 }',
                                                    0, False)
    mqtt_mock.async_publish.reset_mock()
    state = hass.states.get("number.test_number")
    assert state.state == "42"

    # Float with decimal -> float
    await hass.services.async_call(
        NUMBER_DOMAIN,
        SERVICE_SET_VALUE,
        {
            ATTR_ENTITY_ID: "number.test_number",
            ATTR_VALUE: 42.1
        },
        blocking=True,
    )

    mqtt_mock.async_publish.assert_called_once_with(topic, '{"number": 42.1 }',
                                                    0, False)
    mqtt_mock.async_publish.reset_mock()
    state = hass.states.get("number.test_number")
    assert state.state == "42.1"