コード例 #1
0
async def test_unload(hass, mqtt_mock):
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            CONF_NAME: "Ferroamp",
            CONF_PREFIX: "extapi"
        },
        options={
            CONF_INTERVAL: 0
        },
        version=1,
        unique_id="ferroamp",
    )
    config_entry.add_to_hass(hass)
    await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()

    topic = "extapi/data/esm"
    msg = '{"id":{"val":"1"}}'
    async_fire_mqtt_message(hass, topic, msg)
    await hass.async_block_till_done()

    await config_entry.async_unload(hass)
    await hass.async_block_till_done()

    assert hass.data[DOMAIN][DATA_DEVICES].get(config_entry.unique_id) is None
    assert hass.data[DOMAIN][DATA_PREFIXES].get(config_entry.unique_id) is None
    assert hass.data[DOMAIN][DATA_LISTENERS].get(config_entry.unique_id) is None
    assert hass.data[DOMAIN].get(config_entry.unique_id) is None
コード例 #2
0
async def test_options_flow_path_change(input_1, title, data, hass, mock_get_entities):
    """Test config flow options."""
    _LOGGER.error(_get_schema(hass, CONFIG_DATA, KeyMasterFlowHandler.DEFAULTS))
    entry = MockConfigEntry(
        domain=DOMAIN,
        title="frontdoor",
        data=_get_schema(hass, CONFIG_DATA, KeyMasterFlowHandler.DEFAULTS)(CONFIG_DATA),
        version=2,
    )

    entry.add_to_hass(hass)
    assert await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    await setup.async_setup_component(hass, "persistent_notification", {})
    result = await hass.config_entries.options.async_init(entry.entry_id)

    assert result["type"] == "form"
    assert result["step_id"] == "init"
    assert result["errors"] == {}

    with patch(
        "custom_components.keymaster.async_setup", return_value=True
    ) as mock_setup, patch(
        "custom_components.keymaster.async_setup_entry",
        return_value=True,
    ) as mock_setup_entry:

        result2 = await hass.config_entries.options.async_configure(
            result["flow_id"], input_1
        )
        assert result2["type"] == "create_entry"

        await hass.async_block_till_done()
        assert entry.data.copy() == data
コード例 #3
0
async def test_options_flow_fails_when_connection_fails(mock_test, hass):
    mock_test.return_value = None

    config_entry = MockConfigEntry(
        domain=DOMAIN,
        version=7,
        unique_id="uniqueid",
        data={
            CONF_DEVICE_ID: "deviceid",
            CONF_HOST: "hostname",
            CONF_LOCAL_KEY: "localkey",
            CONF_NAME: "test",
            CONF_SWITCH: True,
            CONF_TYPE: "smartplugv1",
        },
    )
    config_entry.add_to_hass(hass)

    assert await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()
    # show initial form
    form = await hass.config_entries.options.async_init(config_entry.entry_id)
    # submit updated config
    result = await hass.config_entries.options.async_configure(
        form["flow_id"],
        user_input={
            CONF_HOST: "new_hostname",
            CONF_LOCAL_KEY: "new_key",
            CONF_SWITCH: False,
        },
    )
    assert "form" == result["type"]
    assert "user" == result["step_id"]
    assert {"base": "connection"} == result["errors"]
コード例 #4
0
async def setup_renault_integration(hass: HomeAssistant):
    """Create the Renault integration."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        source="user",
        data={
            CONF_LOCALE: "fr_FR",
            CONF_USERNAME: "******",
            CONF_PASSWORD: "******",
            CONF_KAMEREON_ACCOUNT_ID: "account_id_2",
        },
        unique_id="account_id_2",
        connection_class=CONN_CLASS_CLOUD_POLL,
        options={},
        entry_id="1",
    )
    config_entry.add_to_hass(hass)

    with patch(
        "custom_components.renault.RenaultHub.attempt_login", return_value=True
    ), patch("custom_components.renault.RenaultHub.async_initialise"):
        await hass.config_entries.async_setup(config_entry.entry_id)
        await hass.async_block_till_done()

    return config_entry
コード例 #5
0
async def test_options_flow(hass):
    """Test an options flow."""
    # Create a new MockConfigEntry and add to HASS (we're bypassing config
    # flow entirely)
    entry = MockConfigEntry(domain=DOMAIN, data=MOCK_CONFIG, entry_id="test")
    entry.add_to_hass(hass)

    # Initialize an options flow
    await hass.config_entries.async_setup(entry.entry_id)
    result = await hass.config_entries.options.async_init(entry.entry_id)

    # Verify that the first options step is a user form
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "user"

    # Enter some fake data into the form
    result = await hass.config_entries.options.async_configure(
        result["flow_id"],
        user_input={platform: platform != SENSOR
                    for platform in PLATFORMS},
    )

    # Verify that the flow finishes
    assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
    assert result["title"] == "test_username"

    # Verify that the options were updated
    assert entry.options == {BINARY_SENSOR: True, SENSOR: False, SWITCH: True}
コード例 #6
0
async def test_options_flow(hass):
    """Test config flow options."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        unique_id="kodi_recently_added_media",
        data={"kodi_entry_id": "abc"},
    )
    config_entry.add_to_hass(hass)
    assert await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()

    # show initial form
    result = await hass.config_entries.options.async_init(config_entry.entry_id
                                                          )
    assert "form" == result["type"]
    assert "init" == result["step_id"]

    # submit form with options
    result = await hass.config_entries.options.async_configure(
        result["flow_id"], user_input={CONF_HIDE_WATCHED: True})
    expected = {
        "data": {
            CONF_HIDE_WATCHED: True
        },
        "description": None,
        "description_placeholders": None,
        "flow_id": mock.ANY,
        "handler": mock.ANY,
        "result": True,
        "title": "",
        "type": "create_entry",
        "version": 1,
    }
    assert expected == result
コード例 #7
0
ファイル: common.py プロジェクト: joelmoses/keymaster
async def setup_ozw(hass, entry=None, fixture=None):
    """Set up OZW and load a dump."""
    hass.config.components.add("mqtt")

    if entry is None:
        entry = MockConfigEntry(
            domain=DOMAIN,
            title="Z-Wave",
            connection_class=config_entries.CONN_CLASS_LOCAL_PUSH,
        )

        entry.add_to_hass(hass)

    with patch(
            "homeassistant.components.mqtt.async_subscribe") as mock_subscribe:
        mock_subscribe.return_value = mock.Mock()
        assert await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()

    assert "ozw" in hass.config.components
    assert len(mock_subscribe.mock_calls) == 1
    receive_message = mock_subscribe.mock_calls[0][1][2]

    if fixture is not None:
        for line in fixture.split("\n"):
            line = line.strip()
            if not line:
                continue
            topic, payload = line.split(",", 1)
            receive_message(mock.Mock(topic=topic, payload=payload))

        await hass.async_block_till_done()

    return receive_message
コード例 #8
0
async def test_async_camera_image(
    hass,
    mock_imap_no_email,
    mock_osremove,
    mock_osmakedir,
    mock_listdir,
    mock_update_time,
    mock_copy_overlays,
    mock_hash_file,
    mock_getctime_today,
):
    """Test async_camera_image function."""

    with patch("os.path.isfile", return_value=True), patch("os.access",
                                                           return_value=False):
        entry = MockConfigEntry(
            domain=DOMAIN,
            title="imap.test.email",
            data=FAKE_CONFIG_DATA,
        )

        entry.add_to_hass(hass)
        assert await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()

        cameras = hass.data[DOMAIN][entry.entry_id][CAMERA]
        m_open = mock_open()
        with patch("builtins.open", m_open, create=True):
            image = await cameras[0].async_camera_image()

        assert m_open.call_count == 1
        assert ("custom_components/mail_and_packages/mail_none.gif"
                in m_open.call_args.args[0])
        assert m_open.call_args.args[1] == "rb"
コード例 #9
0
ファイル: test_init.py プロジェクト: colemamd/hass-truenas
async def test_config_flow_entry_migrate(hass):
    """Test that config flow entry is migrated correctly."""
    # Start with the config entry at Version 1.
    old_config_data = {
        CONF_NAME: "TrueNAS",
        CONF_USERNAME: "******",
        CONF_PASSWORD: "******",
    }
    expected_new_config_data = {
        CONF_NAME: "TrueNAS",
        CONF_USERNAME: "******",
        CONF_PASSWORD: "******",
        CONF_AUTH_MODE: CONF_AUTH_PASSWORD,
        CONF_API_KEY: None,
    }

    entry = MockConfigEntry(
        domain=DOMAIN,
        data=old_config_data,
        title="somehostname",
        version=1,
        source=SOURCE_USER,
    )

    entry.add_to_hass(hass)
    await truenas.async_migrate_entry(hass, entry)
    await hass.async_block_till_done()

    # Test that config entry is at the current version with new data
    assert entry.version == 2
    assert entry.data == expected_new_config_data
コード例 #10
0
async def test_async_camera_image_file_error(
    hass,
    mock_imap_no_email,
    mock_osremove,
    mock_osmakedir,
    mock_listdir,
    mock_update_time,
    mock_copy_overlays,
    mock_hash_file,
    mock_getctime_today,
    caplog,
):
    """Test async_camera_image function."""

    with patch("os.path.isfile", return_value=True), patch("os.access",
                                                           return_value=False):
        entry = MockConfigEntry(
            domain=DOMAIN,
            title="imap.test.email",
            data=FAKE_CONFIG_DATA,
        )

        entry.add_to_hass(hass)
        assert await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()

        cameras = hass.data[DOMAIN][entry.entry_id][CAMERA]
        m_open = mock_open()
        with patch("builtins.open", m_open, create=True):
            m_open.side_effect = FileNotFoundError
            image = await cameras[0].async_camera_image()

        assert "Could not read camera" in caplog.text
コード例 #11
0
async def test_check_file_path_access(
    hass,
    mock_imap_no_email,
    mock_osremove,
    mock_osmakedir,
    mock_listdir,
    mock_update_time,
    mock_copy_overlays,
    mock_hash_file,
    mock_getctime_today,
    caplog,
):
    """Test check_file_path_access function."""
    with patch("os.path.isfile", return_value=True), patch("os.access",
                                                           return_value=False):
        entry = MockConfigEntry(
            domain=DOMAIN,
            title="imap.test.email",
            data=FAKE_CONFIG_DATA,
        )

        entry.add_to_hass(hass)
        assert await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()
        assert "Could not read camera" in caplog.text
コード例 #12
0
async def test_restore_state(hass, mqtt_mock):
    mock_restore_cache(
        hass,
        (State("sensor.ferroamp_esm_1_state_of_charge", "11"), ),
    )

    hass.state = CoreState.starting

    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            CONF_NAME: "Ferroamp",
            CONF_PREFIX: "extapi"
        },
        options={CONF_INTERVAL: 0},
        version=1,
        unique_id="ferroamp",
    )
    config_entry.add_to_hass(hass)
    await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()
    topic = "extapi/data/esm"
    msg = '{"id":{"val":"1"}}'
    async_fire_mqtt_message(hass, topic, msg)
    await hass.async_block_till_done()

    state = hass.states.get("sensor.ferroamp_esm_1_state_of_charge")
    assert state.state == "0.0"
    assert state.attributes == {
        'friendly_name': 'Ferroamp ESM 1 State of Charge',
        'icon': 'mdi:battery-0',
        'unit_of_measurement': '%'
    }
コード例 #13
0
async def test_relay_status_precharge(hass, mqtt_mock):
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            CONF_NAME: "Ferroamp",
            CONF_PREFIX: "extapi"
        },
        options={CONF_INTERVAL: 0},
        version=1,
        unique_id="ferroamp",
    )
    config_entry.add_to_hass(hass)
    await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()

    topic = "extapi/data/eso"
    msg = """{
            "soc": {"val": 48.100003999999998},
            "temp": {"val": 20.379000000000001},
            "wbatcons": {"val": 2213535479518},
            "ubat": {"val": 622.601},
            "ibat": {"val": 1.5700000000000001},
            "relaystatus": {"val": "2"},
            "faultcode": {"val": "80"},
            "ts": {"val": "2021-03-07T19:21:04UTC"},
            "id": {"val": "1"},
            "wbatprod": {"val": 2465106122063}
            }"""
    async_fire_mqtt_message(hass, topic, msg)
    await hass.async_block_till_done()
    async_fire_mqtt_message(hass, topic, msg)
    await hass.async_block_till_done()

    state = hass.states.get("sensor.ferroamp_eso_1_relay_status")
    assert state.state == "precharge"
コード例 #14
0
async def test_service_charge_default_power(hass, mqtt_mock):
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            CONF_NAME: "Ferroamp",
            CONF_PREFIX: "extapi"
        },
        options={
            CONF_INTERVAL: 0
        },
        version=1,
        unique_id="ferroamp",
    )
    config_entry.add_to_hass(hass)
    await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()

    topic = "extapi/data/ehub"
    msg = '{}'
    async_fire_mqtt_message(hass, topic, msg)
    await hass.async_block_till_done()

    await hass.services.async_call(
        DOMAIN,
        "charge",
        {},
        blocking=True,
    )

    mqtt_mock.async_publish.assert_called_once_with(
        "extapi/control/request",
        '{"transId": "00000000-0000-0000-0000-000000000001", "cmd": {"name": "charge", "arg": 1000}}',
        0,
        False
    )
コード例 #15
0
async def test_delete_lock_and_base_folder(
    hass,
    mock_osremove,
    mock_osrmdir,
):
    """Test delete_lock_and_base_folder"""
    entry = MockConfigEntry(domain=DOMAIN,
                            title="frontdoor",
                            data=CONFIG_DATA,
                            version=2)

    entry.add_to_hass(hass)
    assert await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    delete_lock_and_base_folder(hass, entry)

    assert mock_osrmdir.called
    assert mock_osremove.called

    with patch("custom_components.keymaster.helpers.os",
               autospec=True) as mock_os:
        mock_os.listdir.return_value = False
        delete_lock_and_base_folder(hass, entry)
        mock_os.rmdir.assert_called_once
コード例 #16
0
async def test_notifications(hass, enable_custom_integrations):
    """Test that update works."""
    host = "1.2.3.4"
    entry = MockConfigEntry(domain=DOMAIN, data={dynalite.CONF_HOST: host})
    entry.add_to_hass(hass)
    with patch("custom_components.dynalite2.bridge.DynaliteDevices"
               ) as mock_dyn_dev:
        mock_dyn_dev().async_setup = AsyncMock(return_value=True)
        assert await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()
        notification_func = mock_dyn_dev.mock_calls[1][2]["notification_func"]
    event_listener1 = Mock()
    hass.bus.async_listen("dynalite_packet", event_listener1)
    packet = [5, 4, 3, 2]
    notification_func(
        DynaliteNotification(NOTIFICATION_PACKET,
                             {NOTIFICATION_PACKET: packet}))
    await hass.async_block_till_done()
    event_listener1.assert_called_once()
    my_event = event_listener1.mock_calls[0][1][0]
    assert my_event.data[ATTR_HOST] == host
    assert my_event.data[ATTR_PACKET] == packet
    event_listener2 = Mock()
    hass.bus.async_listen("dynalite_preset", event_listener2)
    notification_func(
        DynaliteNotification(NOTIFICATION_PRESET, {
            dyn_CONF_AREA: 7,
            dyn_CONF_PRESET: 2
        }))
    await hass.async_block_till_done()
    event_listener2.assert_called_once()
    my_event = event_listener2.mock_calls[0][1][0]
    assert my_event.data[ATTR_HOST] == host
    assert my_event.data[ATTR_AREA] == 7
    assert my_event.data[ATTR_PRESET] == 2
コード例 #17
0
ファイル: test_requirements.py プロジェクト: wsw70/pyscript
async def test_install_requirements_not_allowed(hass):
    """Test that install requirements will not work because 'allow_all_imports' is False."""
    with patch(
            "custom_components.pyscript.requirements.process_all_requirements"
    ) as process_requirements, patch(
            "custom_components.pyscript.requirements.async_process_requirements"
    ) as ha_install_requirements:
        entry = MockConfigEntry(domain=DOMAIN,
                                data={CONF_ALLOW_ALL_IMPORTS: False})
        entry.add_to_hass(hass)

        # Check that packages get installed correctly
        process_requirements.return_value = {
            "my-package-name": {
                ATTR_SOURCES: [
                    f"{PYSCRIPT_FOLDER}/requirements.txt",
                    f"{PYSCRIPT_FOLDER}/apps/app1/requirements.txt",
                ],
                ATTR_VERSION:
                "2.0.1",
                ATTR_INSTALLED_VERSION:
                None,
            },
            "my-package-name-alternate": {
                ATTR_SOURCES: [f"{PYSCRIPT_FOLDER}/requirements.txt"],
                ATTR_VERSION: "2.0.1",
                ATTR_INSTALLED_VERSION: None,
            },
        }
        assert await install_requirements(hass, entry, PYSCRIPT_FOLDER) is None
        await hass.async_block_till_done()

        assert not ha_install_requirements.called
コード例 #18
0
async def test_update_device(hass, enable_custom_integrations):
    """Test that update works."""
    host = "1.2.3.4"
    entry = MockConfigEntry(domain=DOMAIN, data={dynalite.CONF_HOST: host})
    entry.add_to_hass(hass)
    with patch("custom_components.dynalite2.bridge.DynaliteDevices"
               ) as mock_dyn_dev:
        mock_dyn_dev().async_setup = AsyncMock(return_value=True)
        assert await hass.config_entries.async_setup(entry.entry_id)
        # Not waiting so it add the devices before registration
        update_device_func = mock_dyn_dev.mock_calls[1][2][
            "update_device_func"]
    device = Mock()
    device.unique_id = "abcdef"
    wide_func = Mock()
    async_dispatcher_connect(hass, f"dynalite-update-{host}", wide_func)
    specific_func = Mock()
    async_dispatcher_connect(hass,
                             f"dynalite-update-{host}-{device.unique_id}",
                             specific_func)
    update_device_func()
    await hass.async_block_till_done()
    wide_func.assert_called_once()
    specific_func.assert_not_called()
    update_device_func(device)
    await hass.async_block_till_done()
    wide_func.assert_called_once()
    specific_func.assert_called_once()
コード例 #19
0
async def test_sensor_slots_before_units(
        hass, stream_reader_writer_slots_before_units):
    """Test that sensor works when slot info is received before unit info."""
    with patch("asyncio.StreamWriter.close", return_value=None), patch(
            "asyncio.open_connection",
            return_value=stream_reader_writer_slots_before_units,
    ), patch(
            "FoldingAtHomeControl.serialconnection.SerialConnection.send_async",
            return_value=AsyncMock(),
    ):
        entry = MockConfigEntry(
            domain=DOMAIN,
            data={
                CONF_ADDRESS: "localhost",
                CONF_PORT: 36330,
                CONF_PASSWORD: "******",
            },
        )
        entry.add_to_hass(hass)
        await hass.config_entries.async_setup(entry.entry_id)

        await hass.async_block_till_done()

        hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
        await hass.async_block_till_done()
        await asyncio.sleep(1)
        assert len(hass.states.async_all()) > 0
コード例 #20
0
async def test_add_devices_then_register(hass, enable_custom_integrations):
    """Test that add_devices work."""
    host = "1.2.3.4"
    entry = MockConfigEntry(domain=DOMAIN, data={dynalite.CONF_HOST: host})
    entry.add_to_hass(hass)
    with patch("custom_components.dynalite2.bridge.DynaliteDevices"
               ) as mock_dyn_dev:
        mock_dyn_dev().async_setup = AsyncMock(return_value=True)
        assert await hass.config_entries.async_setup(entry.entry_id)
        # Not waiting so it add the devices before registration
        new_device_func = mock_dyn_dev.mock_calls[1][2]["new_device_func"]
    # Now with devices
    device1 = Mock()
    device1.category = "light"
    device1.name = "NAME"
    device1.unique_id = "unique1"
    device2 = Mock()
    device2.category = "switch"
    device2.name = "NAME2"
    device2.unique_id = "unique2"
    new_device_func([device1, device2])
    device3 = Mock()
    device3.category = "switch"
    device3.name = "NAME3"
    device3.unique_id = "unique3"
    new_device_func([device3])
    await hass.async_block_till_done()
    assert hass.states.get("light.name")
    assert hass.states.get("switch.name2")
    assert hass.states.get("switch.name3")
コード例 #21
0
async def setup_lm_machine(hass, model):
    await async_setup_component(hass, DOMAIN, {})

    DATA = {
        CONF_HOST: "1.2.3.4",
        CONF_CLIENT_ID: "aabbcc",
        CONF_CLIENT_SECRET: "bbccdd",
        CONF_USERNAME: "******",
        CONF_PASSWORD: "******",
        CONF_SERIAL_NUMBER: SERIAL_NUMBER,
        CONF_MODEL_NAME: model,
        CONF_MACHINE_NAME: "bbbbb",
        CONF_KEY: "12345678901234567890123456789012",
    }

    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data=deepcopy(DATA),
        entry_id=ENTRY_ID,
    )

    config_entry.add_to_hass(hass)

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

    assert config_entry.entry_id in hass.data[DOMAIN]

    machine = hass.data[DOMAIN][config_entry.entry_id]
    assert machine is not None

    return machine
コード例 #22
0
async def test_form_repeat_identifier(hass):
    """Test we handle repeat identifiers."""
    entry = MockConfigEntry(domain=DOMAIN,
                            title=TEST_USERNAME,
                            data={},
                            options=None)
    entry.add_to_hass(hass)

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

    with patch(
            "custom_components.subaru.config_flow.SubaruAPI.connect",
            return_value=True,
    ):
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {
                CONF_USERNAME: TEST_USERNAME,
                CONF_PASSWORD: TEST_PASSWORD,
                CONF_PIN: TEST_PIN,
            },
        )

    assert result2["type"] == "abort"
    assert result2["reason"] == "already_configured"
コード例 #23
0
async def test_generate_package_files(hass, caplog):
    """Test generate_package_files"""
    entry = MockConfigEntry(
        domain=DOMAIN, title="frontdoor", data=CONFIG_DATA, version=2
    )

    entry.add_to_hass(hass)
    assert await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    servicedata = {
        "lockname": "backdoor",
    }
    with pytest.raises(ValueError):
        await hass.services.async_call(
            DOMAIN, SERVICE_GENERATE_PACKAGE, servicedata, blocking=True
        )
    await hass.async_block_till_done()

    # Check for exception when unable to create directory
    with patch(
        "custom_components.keymaster.services.os", autospec=True
    ) as mock_os, patch(
        "custom_components.keymaster.services.output_to_file_from_template"
    ):
        mock_os.path.isdir.return_value = False
        mock_os.makedirs.side_effect = OSError(errno.EEXIST, "error")
        servicedata = {
            "lockname": "frontdoor",
        }
        await hass.services.async_call(DOMAIN, SERVICE_GENERATE_PACKAGE, servicedata)
        await hass.async_block_till_done()
        mock_os.path.isdir.assert_called_once
        mock_os.makedirs.assert_called_once
        assert "Error creating directory:" in caplog.text
コード例 #24
0
ファイル: test_init.py プロジェクト: ksya/ha-nefiteasy
async def test_setup_entry(mock_class, hass: HomeAssistant):
    """Validate that setup entry also configure the client."""
    client = ClientMock(mock_class)
    mock_class.return_value = client

    config_entry = MockConfigEntry(
        domain="nefiteasy",
        data={
            "serial": "123456789",
            "accesskey": "myAccessKey",
            "password": "******",
            "min_temp": 10,
            "max_temp": 28,
            "temp_step": 0.5,
            "name": "Nefit",
        },
    )

    config_entry.add_to_hass(hass)

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

    await hass.async_block_till_done()

    assert config_entry.state == config_entries.ConfigEntryState.LOADED
コード例 #25
0
ファイル: test_init.py プロジェクト: wudwork/keymaster
async def test_unload_entry(
    hass,
    mock_delete_folder,
    mock_delete_lock_and_base_folder,
):
    """Test unloading entities."""

    await setup.async_setup_component(hass, "persistent_notification", {})
    entry = MockConfigEntry(domain=DOMAIN,
                            title="frontdoor",
                            data=CONFIG_DATA,
                            version=2)

    entry.add_to_hass(hass)
    assert await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    assert len(hass.states.async_entity_ids(SENSOR_DOMAIN)) == 6
    assert len(hass.config_entries.async_entries(DOMAIN)) == 1

    assert await hass.config_entries.async_unload(entry.entry_id)
    await hass.async_block_till_done()

    assert len(hass.states.async_entity_ids(SENSOR_DOMAIN)) == 6
    assert len(hass.states.async_entity_ids(DOMAIN)) == 0

    assert await hass.config_entries.async_remove(entry.entry_id)
    await hass.async_block_till_done()
    assert len(hass.states.async_entity_ids(SENSOR_DOMAIN)) == 0
コード例 #26
0
async def test_form_reauth(hass):
    """Test we handle reauth."""
    entry = MockConfigEntry(
        domain=DOMAIN,
        title=TEST_USERNAME,
        data={CONF_USERNAME: TEST_USERNAME, CONF_TOKEN: TEST_TOKEN},
        options=None,
    )
    entry.add_to_hass(hass)

    result = await hass.config_entries.flow.async_init(
        DOMAIN,
        context={"source": config_entries.SOURCE_REAUTH},
        data={CONF_USERNAME: TEST_USERNAME},
    )
    with patch(
        "custom_components.tesla_custom.config_flow.TeslaAPI.connect",
        return_value={
            "refresh_token": TEST_TOKEN,
            CONF_ACCESS_TOKEN: TEST_ACCESS_TOKEN,
            CONF_EXPIRATION: TEST_VALID_EXPIRATION,
        },
    ):
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {CONF_USERNAME: TEST_USERNAME, CONF_TOKEN: "new-password"},
        )

    assert result2["type"] == "abort"
    assert result2["reason"] == "reauth_successful"
コード例 #27
0
async def test_options_flow_init(hass):
    """Test config flow options."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        version=7,
        unique_id="uniqueid",
        data={
            CONF_DEVICE_ID: "deviceid",
            CONF_HOST: "hostname",
            CONF_LOCAL_KEY: "localkey",
            CONF_NAME: "test",
            CONF_SWITCH: True,
            CONF_TYPE: "smartplugv1",
        },
    )
    config_entry.add_to_hass(hass)

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

    # show initial form
    result = await hass.config_entries.options.async_init(config_entry.entry_id
                                                          )
    assert "form" == result["type"]
    assert "user" == result["step_id"]
    assert {} == result["errors"]
    assert result["data_schema"]({
        CONF_HOST: "hostname",
        CONF_LOCAL_KEY: "localkey",
        CONF_SWITCH: True,
    })
コード例 #28
0
async def test_existing_update(hass, enable_custom_integrations):
    """Test when the entry exists with a different config."""
    host = "1.2.3.4"
    port1 = 7777
    port2 = 8888
    entry = MockConfigEntry(
        domain=DOMAIN,
        data={
            dynalite.CONF_HOST: host,
            dynalite.CONF_PORT: port1
        },
        version=2,
    )
    entry.add_to_hass(hass)
    with patch("custom_components.dynalite2.bridge.DynaliteDevices"
               ) as mock_dyn_dev:
        mock_dyn_dev().async_setup = AsyncMock(return_value=True)
        assert await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()
        mock_dyn_dev().configure.assert_called_once()
        assert mock_dyn_dev().configure.mock_calls[0][1][0]["port"] == port1
        result = await hass.config_entries.flow.async_init(
            DOMAIN,
            context={"source": config_entries.SOURCE_IMPORT},
            data={
                dynalite.CONF_HOST: host,
                dynalite.CONF_PORT: port2
            },
        )
        await hass.async_block_till_done()
        assert mock_dyn_dev().configure.call_count == 2
        assert mock_dyn_dev().configure.mock_calls[1][1][0]["port"] == port2
    assert result["type"] == "abort"
    assert result["reason"] == "already_configured"
コード例 #29
0
async def test_options_flow_fails_when_config_is_missing(mock_test, hass):
    mock_device = MagicMock()
    mock_test.return_value = mock_device

    config_entry = MockConfigEntry(
        domain=DOMAIN,
        version=7,
        unique_id="uniqueid",
        data={
            CONF_DEVICE_ID: "deviceid",
            CONF_HOST: "hostname",
            CONF_LOCAL_KEY: "localkey",
            CONF_NAME: "test",
            CONF_SWITCH: True,
            CONF_TYPE: "non_existing",
        },
    )
    config_entry.add_to_hass(hass)

    await hass.config_entries.async_setup(config_entry.entry_id)
    await hass.async_block_till_done()
    # show initial form
    result = await hass.config_entries.options.async_init(config_entry.entry_id
                                                          )
    assert result["type"] == "abort"
    assert result["reason"] == "not_supported"
コード例 #30
0
async def test_refresh_codes(hass, lock_data, caplog):
    """Test refresh_codes"""
    await setup_ozw(hass, fixture=lock_data)

    state = hass.states.get("lock.smartcode_10_touchpad_electronic_deadbolt_locked")
    assert state is not None
    assert state.state == "locked"
    assert state.attributes["node_id"] == 14

    entry = MockConfigEntry(
        domain=DOMAIN, title="frontdoor", data=CONFIG_DATA, version=2
    )

    entry.add_to_hass(hass)
    assert await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    servicedata = {"entity_id": "lock.kwikset_touchpad_electronic_deadbolt_frontdoor"}
    await hass.services.async_call(DOMAIN, SERVICE_REFRESH_CODES, servicedata)
    await hass.async_block_till_done()

    assert (
        "Problem retrieving node_id from entity lock.kwikset_touchpad_electronic_deadbolt_frontdoor because the entity doesn't exist."
        in caplog.text
    )

    servicedata = {"entity_id": "lock.smartcode_10_touchpad_electronic_deadbolt_locked"}
    await hass.services.async_call(DOMAIN, SERVICE_REFRESH_CODES, servicedata)
    await hass.async_block_till_done()

    assert "DEBUG: Index found valueIDKey: 71776119310303256" in caplog.text