async def test_handling_core_messages_remote_disconnect(cloud_mock_iot):
    """Test handling core messages."""
    cloud_mock_iot.remote.disconnect = AsyncMock()

    await iot.async_handle_cloud(
        cloud_mock_iot,
        {"action": "disconnect_remote"},
    )
    assert len(cloud_mock_iot.remote.disconnect.mock_calls) == 1
Beispiel #2
0
async def test_retry_update():
    """Test retry function of refresh forecast."""
    hass = Mock()
    weather = weather_smhi.SmhiWeather("name", "17.0022", "62.0022")
    weather.hass = hass

    with patch.object(weather, "async_update", AsyncMock()) as update:
        await weather.retry_update(None)
        assert len(update.mock_calls) == 1
Beispiel #3
0
async def test_connect_timeout():
    """Test that a timeout during connection throws an exception."""
    with patch("asyncio_dgram.connect",
               AsyncMock(side_effect=asyncio.TimeoutError)):
        with pytest.raises(SocketError) as err:
            async with Client("192.168.1.100") as client:
                await client.system.ping()

        assert str(err.value) == "Connection to device timed out"
Beispiel #4
0
async def test_connect_sync_success():
    """Test connecting to the socket with a sync handler."""
    websocket = Websocket(TEST_API_KEY, TEST_APP_KEY)
    websocket._sio.connect = AsyncMock()
    websocket._sio.eio._trigger_event = AsyncMock()
    websocket._sio.namespaces = {"/": 1}

    async_on_connect = AsyncMock()
    websocket.async_on_connect(async_on_connect)

    await websocket.connect()
    websocket._sio.connect.assert_called_once_with(
        f"https://rt2.ambientweather.net/?api=1&applicationKey={TEST_APP_KEY}",
        transports=["websocket"],
    )

    await websocket._sio._trigger_event("connect", "/")
    async_on_connect.assert_called_once()
Beispiel #5
0
async def test_controller_fail_setup(hass):
    """Test that a failed setup still stores controller."""
    with patch("homeassistant.components.unifi.UniFiController"
               ) as mock_controller:
        mock_controller.return_value.async_setup = AsyncMock(
            return_value=False)
        await setup_unifi_integration(hass)

    assert hass.data[UNIFI_DOMAIN] == {}
Beispiel #6
0
async def test_reconnect():
    """Test that reconnecting to the websocket does the right thing."""
    websocket = Websocket(TEST_API_KEY, TEST_APP_KEY)
    websocket._sio.connect = AsyncMock()
    websocket._sio.eio._trigger_event = AsyncMock()
    websocket._sio.namespaces = {"/": 1}

    async_on_connect = AsyncMock()
    async_on_disconnect = AsyncMock()

    websocket.async_on_connect(async_on_connect)
    websocket.async_on_disconnect(async_on_disconnect)

    await websocket.reconnect()
    await websocket._sio._trigger_event("disconnect", "/")
    async_on_disconnect.assert_called_once()
    await websocket._sio._trigger_event("connect", "/")
    async_on_connect.assert_called_once()
Beispiel #7
0
async def test_reconnect(event_loop):
    """Test that reconnecting to the websocket does the right thing."""
    async with aiohttp.ClientSession(loop=event_loop) as session:
        client = Client(TEST_API_KEY, TEST_APP_KEY, session=session)
        client.websocket._sio.eio._trigger_event = AsyncMock()
        client.websocket._sio.eio.connect = AsyncMock()

        async_on_connect = AsyncMock()
        async_on_disconnect = AsyncMock()

        client.websocket.async_on_connect(async_on_connect)
        client.websocket.async_on_disconnect(async_on_disconnect)

        await client.websocket.reconnect()
        await client.websocket._sio._trigger_event("disconnect", "/")
        async_on_disconnect.assert_called_once()
        await client.websocket._sio._trigger_event("connect", "/")
        async_on_connect.assert_called_once()
Beispiel #8
0
async def test_logout_view(hass, cloud_client):
    """Test logging out."""
    cloud = hass.data["cloud"] = MagicMock()
    cloud.logout = AsyncMock(return_value=None)
    req = await cloud_client.post("/api/cloud/logout")
    assert req.status == 200
    data = await req.json()
    assert data == {"message": "ok"}
    assert len(cloud.logout.mock_calls) == 1
async def test_watchdog_firing():
    """Test that the watchdog expiring fires the provided coroutine."""
    mock_coro = AsyncMock()
    mock_coro.__name__ = "mock_coro"

    watchdog = WebsocketWatchdog(mock_coro)

    await watchdog.on_expire()
    mock_coro.assert_called_once()
Beispiel #10
0
async def test_version_log_warning(
        caplog,
        hass: HomeAssistantType) -> None:  # type: ignore[no-untyped-def]
    """Test warning on old version."""
    client = create_mock_client()
    client.async_sysinfo_version = AsyncMock(return_value="2.0.0-alpha.7")
    await setup_test_config_entry(hass, hyperion_client=client)
    assert hass.states.get(TEST_ENTITY_ID_1) is not None
    assert "Please consider upgrading" in caplog.text
Beispiel #11
0
def init_config_flow(hass, side_effect=None):
    """Init a configuration flow."""
    config_flow.register_flow_implementation(hass, DOMAIN, "id", "secret")
    flow = config_flow.PointFlowHandler()
    flow._get_authorization_url = AsyncMock(  # pylint: disable=protected-access
        return_value="https://example.com",
        side_effect=side_effect)
    flow.hass = hass
    return flow
Beispiel #12
0
async def test_handler_remote_sni(cloud_mock):
    """Test handler Webhook."""
    cloud_mock.remote.handle_connection_requests = AsyncMock()
    cloud_mock.remote.snitun_server = "1.1.1.1"
    resp = await iot.async_handle_remote_sni(cloud_mock, {"ip_address": "8.8.8.8"})

    assert cloud_mock.remote.handle_connection_requests.called
    assert cloud_mock.remote.handle_connection_requests.mock_calls[0][1][0] == "8.8.8.8"
    assert resp == {"server": "1.1.1.1"}
def patch_product_identify(path=None, **kwargs):
    """Patch the blebox_uniapi Products class."""
    if path is None:
        path = "homeassistant.components.blebox.Products"
    patcher = patch(path, mock.DEFAULT, blebox_uniapi.products.Products, True,
                    True)
    products_class = patcher.start()
    products_class.async_from_host = AsyncMock(**kwargs)
    return products_class
Beispiel #14
0
async def test_form_auth(hass):
    """Test manual configuration if auth is required."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER})
    assert result["type"] == "form"
    assert result["errors"] == {}

    with patch(
            "aioshelly.get_info",
            return_value={
                "mac": "test-mac",
                "type": "SHSW-1",
                "auth": True
            },
    ):
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {"host": "1.1.1.1"},
        )

    assert result2["type"] == "form"
    assert result["errors"] == {}

    with patch(
            "aioshelly.Device.create",
            return_value=Mock(
                shutdown=AsyncMock(),
                settings={
                    "name": "Test name",
                    "device": {
                        "mac": "test-mac"
                    }
                },
            ),
    ), patch("homeassistant.components.shelly.async_setup",
             return_value=True) as mock_setup, patch(
                 "homeassistant.components.shelly.async_setup_entry",
                 return_value=True,
             ) as mock_setup_entry:
        result3 = await hass.config_entries.flow.async_configure(
            result2["flow_id"],
            {
                "username": "******",
                "password": "******"
            },
        )

    assert result3["type"] == "create_entry"
    assert result3["title"] == "Test name"
    assert result3["data"] == {
        "host": "1.1.1.1",
        "username": "******",
        "password": "******",
    }
    await hass.async_block_till_done()
    assert len(mock_setup.mock_calls) == 1
    assert len(mock_setup_entry.mock_calls) == 1
async def test_ptvsd_bootstrap(hass):
    """Test loading ptvsd component with wait."""
    config = {ptvsd_component.DOMAIN: {ptvsd_component.CONF_WAIT: True}}

    with patch("homeassistant.components.ptvsd.async_setup", AsyncMock()) as setup_mock:
        setup_mock.return_value = True
        await _async_set_up_integrations(hass, config)

        assert setup_mock.call_count == 1
async def test_refresh_known_errors(err_msg, crd, caplog):
    """Test raising known errors."""
    crd.update_method = AsyncMock(side_effect=err_msg[0])

    await crd.async_refresh()

    assert crd.data is None
    assert crd.last_update_success is False
    assert err_msg[1] in caplog.text
def setup_mock_device(mock_device):
    """Prepare mock ONVIFDevice."""
    mock_device.async_setup = AsyncMock(return_value=True)

    def mock_constructor(hass, config):
        """Fake the controller constructor."""
        return mock_device

    mock_device.side_effect = mock_constructor
async def test_password_or_pub_key_required(hass):
    """Test creating an AsusWRT scanner without a pass or pubkey."""
    with patch("homeassistant.components.asuswrt.AsusWrt") as AsusWrt:
        AsusWrt().connection.async_connect = AsyncMock()
        AsusWrt().is_connected = False
        result = await async_setup_component(
            hass, DOMAIN, {DOMAIN: {CONF_HOST: "fake_host", CONF_USERNAME: "******"}}
        )
        assert not result
async def create_helper_instance(
        aiohttp_client, handle_server_msgs,
        service) -> account_link.AuthorizeAccountHelper:
    """Create a auth helper instance."""
    client = await create_account_link_server(aiohttp_client,
                                              handle_server_msgs)
    mock_cloud = Mock(client=Mock(websession=Mock(ws_connect=AsyncMock(
        return_value=client))))
    return account_link.AuthorizeAccountHelper(mock_cloud, service)
Beispiel #20
0
def mock_smile_notconnect():
    """Mock the Plugwise Smile general connection failure for Home Assistant."""
    with patch("homeassistant.components.plugwise.Smile") as smile_mock:
        smile_mock.InvalidAuthentication = Smile.InvalidAuthentication
        smile_mock.ConnectionFailedError = Smile.ConnectionFailedError
        smile_mock.PlugwiseError = Smile.PlugwiseError
        smile_mock.return_value.connect.side_effect = AsyncMock(
            return_value=False)
        yield smile_mock.return_value
Beispiel #21
0
async def test_cloud_receiving_bytes(mock_iot_client, caplog, cloud_mock_iot):
    """Test server disconnecting instance."""
    conn = MockIoT(cloud_mock_iot)
    mock_iot_client.receive = AsyncMock(return_value=MagicMock(
        type=WSMsgType.BINARY))

    await conn.connect()

    assert "Connection closed: Received non-Text message" in caplog.text
Beispiel #22
0
async def test_auth_create_token_when_issued_token_fails(
    hass: HomeAssistantType,
) -> None:
    """Verify correct behaviour when a token is granted by fails to authenticate."""
    result = await _init_flow(hass)

    client = create_mock_client()
    client.async_is_auth_required = AsyncMock(return_value=TEST_AUTH_REQUIRED_RESP)

    with patch(
        "homeassistant.components.hyperion.client.HyperionClient", return_value=client
    ):
        result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "auth"

    client.async_request_token = AsyncMock(return_value=TEST_REQUEST_TOKEN_SUCCESS)
    with patch(
        "homeassistant.components.hyperion.client.HyperionClient", return_value=client
    ), patch(
        "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
        return_value=TEST_AUTH_ID,
    ):
        result = await _configure_flow(
            hass, result, user_input={CONF_CREATE_TOKEN: True}
        )
        assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
        assert result["step_id"] == "create_token"
        assert result["description_placeholders"] == {
            CONF_AUTH_ID: TEST_AUTH_ID,
        }

        result = await _configure_flow(hass, result)
        assert result["type"] == data_entry_flow.RESULT_TYPE_EXTERNAL_STEP
        assert result["step_id"] == "create_token_external"

        # The flow will be automatically advanced by the auth token response.

        # Make the last verification fail.
        client.async_client_connect = AsyncMock(return_value=False)

        result = await _configure_flow(hass, result)
        assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
        assert result["reason"] == "cannot_connect"
async def test_step_user_mfa(hass):
    """Test that the user step works when MFA is in the middle."""
    conf = {
        CONF_USERNAME: "******",
        CONF_PASSWORD: "******",
        CONF_CODE: "1234",
    }

    with patch(
        "simplipy.API.login_via_credentials",
        new=AsyncMock(side_effect=PendingAuthorizationError),
    ):
        result = await hass.config_entries.flow.async_init(
            DOMAIN, context={"source": SOURCE_USER}, data=conf
        )
        assert result["step_id"] == "mfa"

    with patch(
        "simplipy.API.login_via_credentials",
        new=AsyncMock(side_effect=PendingAuthorizationError),
    ):
        # Simulate the user pressing the MFA submit button without having clicked
        # the link in the MFA email:
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )
        assert result["step_id"] == "mfa"

    with patch(
        "homeassistant.components.simplisafe.async_setup_entry", return_value=True
    ), patch(
        "simplipy.API.login_via_credentials", new=AsyncMock(return_value=mock_api())
    ):
        result = await hass.config_entries.flow.async_configure(
            result["flow_id"], user_input={}
        )

        assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
        assert result["title"] == "*****@*****.**"
        assert result["data"] == {
            CONF_USERNAME: "******",
            CONF_TOKEN: "12345abc",
            CONF_CODE: "1234",
        }
async def test_auth_create_token_approval_declined(
        hass: HomeAssistantType) -> None:
    """Verify correct behaviour when a token request is declined."""
    result = await _init_flow(hass)

    client = create_mock_client()
    client.async_is_auth_required = AsyncMock(
        return_value=TEST_AUTH_REQUIRED_RESP)

    with patch("homeassistant.components.hyperion.client.HyperionClient",
               return_value=client):
        result = await _configure_flow(hass, result, user_input=TEST_HOST_PORT)
    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "auth"

    client.async_request_token = AsyncMock(
        return_value=TEST_REQUEST_TOKEN_FAIL)
    with patch(
            "homeassistant.components.hyperion.client.HyperionClient",
            return_value=client
    ), patch(
            "homeassistant.components.hyperion.config_flow.client.generate_random_auth_id",
            return_value=TEST_AUTH_ID,
    ):
        result = await _configure_flow(hass,
                                       result,
                                       user_input={CONF_CREATE_TOKEN: True})

        assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
        assert result["step_id"] == "create_token"
        assert result["description_placeholders"] == {
            CONF_AUTH_ID: TEST_AUTH_ID,
        }

        result = await _configure_flow(hass, result)
        await hass.async_block_till_done()
        assert result["type"] == data_entry_flow.RESULT_TYPE_EXTERNAL_STEP
        assert result["step_id"] == "create_token_external"

        # The flow will be automatically advanced by the auth token response.

        result = await _configure_flow(hass, result)
        assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
        assert result["reason"] == "auth_new_token_not_granted_error"
Beispiel #25
0
async def test_form(hass):
    """Test we get the form."""
    await setup.async_setup_component(hass, "persistent_notification", {})
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER})
    assert result["type"] == "form"
    assert result["errors"] == {}

    with patch(
            "aioshelly.get_info",
            return_value={
                "mac": "test-mac",
                "type": "SHSW-1",
                "auth": False
            },
    ), patch(
            "aioshelly.Device.create",
            new=AsyncMock(return_value=Mock(
                shutdown=AsyncMock(),
                settings={
                    "name": "Test name",
                    "device": {
                        "mac": "test-mac"
                    }
                },
            )),
    ), patch("homeassistant.components.shelly.async_setup",
             return_value=True) as mock_setup, patch(
                 "homeassistant.components.shelly.async_setup_entry",
                 return_value=True,
             ) as mock_setup_entry:
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {"host": "1.1.1.1"},
        )

    assert result2["type"] == "create_entry"
    assert result2["title"] == "Test name"
    assert result2["data"] == {
        "host": "1.1.1.1",
    }
    await hass.async_block_till_done()
    assert len(mock_setup.mock_calls) == 1
    assert len(mock_setup_entry.mock_calls) == 1
async def test_subscription_not_owned(authenticated_plugin):
    authenticated_plugin.client.get_subscription = AsyncMock()
    authenticated_plugin.client.get_subscription.return_value = None

    sub_status = await authenticated_plugin.get_subscriptions()

    exp_result = [Subscription(subscription_name="Uplay+", end_time=None, owned=False,
                               subscription_discovery=SubscriptionDiscovery.AUTOMATIC)]

    assert sub_status == exp_result
async def test_subscription_games(authenticated_plugin):
    authenticated_plugin.client.get_subscription = AsyncMock()
    authenticated_plugin.client.get_subscription.return_value = SUBSCRIPTION_RESPONSE_OK

    async for sub_games in authenticated_plugin.get_subscription_games('Uplay+', TEST_SUB_GAMES):
        result = sub_games

    exp_result = TEST_SUB_GAMES

    assert result == exp_result
async def test_switches_with_port_management(hass):
    """Test that switches are loaded properly using port management."""
    api_discovery = deepcopy(API_DISCOVERY_RESPONSE)
    api_discovery["data"]["apiList"].append(API_DISCOVERY_PORT_MANAGEMENT)

    with patch.dict(API_DISCOVERY_RESPONSE, api_discovery):
        device = await setup_axis_integration(hass)

    device.api.vapix.ports = {"0": AsyncMock(), "1": AsyncMock()}
    device.api.vapix.ports["0"].name = "Doorbell"
    device.api.vapix.ports["0"].open = AsyncMock()
    device.api.vapix.ports["0"].close = AsyncMock()
    device.api.vapix.ports["1"].name = ""

    for event in EVENTS:
        device.api.event.process_event(event)
    await hass.async_block_till_done()

    assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 2

    relay_0 = hass.states.get(f"switch.{NAME}_doorbell")
    assert relay_0.state == "off"
    assert relay_0.name == f"{NAME} Doorbell"

    relay_1 = hass.states.get(f"switch.{NAME}_relay_1")
    assert relay_1.state == "on"
    assert relay_1.name == f"{NAME} Relay 1"

    await hass.services.async_call(
        SWITCH_DOMAIN,
        "turn_on",
        {"entity_id": f"switch.{NAME}_doorbell"},
        blocking=True,
    )
    device.api.vapix.ports["0"].close.assert_called_once()

    await hass.services.async_call(
        SWITCH_DOMAIN,
        "turn_off",
        {"entity_id": f"switch.{NAME}_doorbell"},
        blocking=True,
    )
    device.api.vapix.ports["0"].open.assert_called_once()
Beispiel #29
0
async def test_logout_clears_info(cloud_client):
    """Test logging out disconnects and removes info."""
    cl = cloud.Cloud(cloud_client, cloud.MODE_DEV)

    assert len(cl._on_start) == 2
    cl._on_start.clear()
    assert len(cl._on_stop) == 3
    cl._on_stop.clear()

    info_file = MagicMock(exists=Mock(return_value=True),
                          unlink=Mock(return_value=True))

    cl.id_token = "id_token"
    cl.access_token = "access_token"
    cl.refresh_token = "refresh_token"

    cl.iot = MagicMock()
    cl.iot.disconnect = AsyncMock()

    cl.google_report_state = MagicMock()
    cl.google_report_state.disconnect = AsyncMock()

    cl.remote = MagicMock()
    cl.remote.disconnect = AsyncMock()

    cl._on_stop.extend([
        cl.iot.disconnect, cl.remote.disconnect,
        cl.google_report_state.disconnect
    ])

    with patch(
            "opp_net.Cloud.user_info_path",
            new_callable=PropertyMock(return_value=info_file),
    ):
        await cl.logout()

    assert len(cl.iot.disconnect.mock_calls) == 1
    assert len(cl.google_report_state.disconnect.mock_calls) == 1
    assert len(cl.remote.disconnect.mock_calls) == 1
    assert cl.id_token is None
    assert cl.access_token is None
    assert cl.refresh_token is None
    assert info_file.unlink.called
Beispiel #30
0
class FakeEndpoint:
    """Fake endpoint for moking zigpy."""
    def __init__(self, manufacturer, model, epid=1):
        """Init fake endpoint."""
        self.device = None
        self.endpoint_id = epid
        self.in_clusters = {}
        self.out_clusters = {}
        self._cluster_attr = {}
        self.member_of = {}
        self.status = 1
        self.manufacturer = manufacturer
        self.model = model
        self.profile_id = zigpy.profiles.zha.PROFILE_ID
        self.device_type = None
        self.request = AsyncMock(return_value=[0])

    def add_input_cluster(self, cluster_id):
        """Add an input cluster."""
        cluster = zigpy.zcl.Cluster.from_id(self, cluster_id, is_server=True)
        patch_cluster(cluster)
        self.in_clusters[cluster_id] = cluster
        if hasattr(cluster, "ep_attribute"):
            setattr(self, cluster.ep_attribute, cluster)

    def add_output_cluster(self, cluster_id):
        """Add an output cluster."""
        cluster = zigpy.zcl.Cluster.from_id(self, cluster_id, is_server=False)
        patch_cluster(cluster)
        self.out_clusters[cluster_id] = cluster

    reply = AsyncMock(return_value=[0])
    request = AsyncMock(return_value=[0])

    @property
    def __class__(self):
        """Fake being Zigpy endpoint."""
        return zigpy_ep

    @property
    def unique_id(self):
        """Return the unique id for the endpoint."""
        return self.device.ieee, self.endpoint_id