Exemple #1
0
async def test_remove_entry_app_api_error(hass, config_entry, smartthings_mock):
    """Test raises exceptions removing the app."""
    # Arrange
    request_info = Mock(real_url="http://example.com")
    smartthings_mock.delete_app.side_effect = ClientResponseError(
        request_info=request_info, history=None, status=HTTP_INTERNAL_SERVER_ERROR
    )
    # Act
    with pytest.raises(ClientResponseError):
        await smartthings.async_remove_entry(hass, config_entry)
    # Assert
    assert smartthings_mock.delete_installed_app.call_count == 1
    assert smartthings_mock.delete_app.call_count == 1
Exemple #2
0
async def test_async_setup_raises_fails_if_auth_fails(hass: HomeAssistant):
    """Test that setup fails if auth fails during setup."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"},
    )
    config_entry.add_to_hass(hass)

    with patch_bond_version(
        side_effect=ClientResponseError(MagicMock(), MagicMock(), status=401)
    ):
        await hass.config_entries.async_setup(config_entry.entry_id)
    assert config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_unknown_api_error(hass, smartthings_mock):
    """Test an error is shown when there is an unknown API error."""
    flow = SmartThingsFlowHandler()
    flow.hass = hass

    smartthings_mock.return_value.apps.return_value = mock_coro(
        exception=ClientResponseError(None, None, status=404))

    result = await flow.async_step_user({'access_token': str(uuid4())})

    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'user'
    assert result['errors'] == {'base': 'app_setup_error'}
async def test_token_unauthorized(hass, smartthings_mock):
    """Test an error is shown when the token is not authorized."""
    flow = SmartThingsFlowHandler()
    flow.hass = hass

    smartthings_mock.return_value.apps.return_value = mock_coro(
        exception=ClientResponseError(None, None, status=401))

    result = await flow.async_step_user({'access_token': str(uuid4())})

    assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
    assert result['step_id'] == 'user'
    assert result['errors'] == {'access_token': 'token_unauthorized'}
async def test_scenes_api_errors_raise_not_ready(
    hass, config_entry, app, installed_app, smartthings_mock
):
    """Test if scenes are unauthorized we continue to load platforms."""
    config_entry.add_to_hass(hass)
    request_info = Mock(real_url="http://example.com")
    smartthings_mock.app.return_value = app
    smartthings_mock.installed_app.return_value = installed_app
    smartthings_mock.scenes.side_effect = ClientResponseError(
        request_info=request_info, history=None, status=HTTP_INTERNAL_SERVER_ERROR
    )
    with pytest.raises(ConfigEntryNotReady):
        await smartthings.async_setup_entry(hass, config_entry)
async def test_zeroconf_already_configured_refresh_token(
        hass: core.HomeAssistant):
    """Test starting a flow from zeroconf when already configured and the token is out of date."""
    entry2 = MockConfigEntry(
        domain=DOMAIN,
        unique_id="not-the-same-bond-id",
        data={
            CONF_HOST: "stored-host",
            CONF_ACCESS_TOKEN: "correct-token"
        },
    )
    entry2.add_to_hass(hass)
    entry = MockConfigEntry(
        domain=DOMAIN,
        unique_id="already-registered-bond-id",
        data={
            CONF_HOST: "stored-host",
            CONF_ACCESS_TOKEN: "incorrect-token"
        },
    )
    entry.add_to_hass(hass)

    with patch_bond_version(side_effect=ClientResponseError(
            MagicMock(), MagicMock(), status=401)):
        await hass.config_entries.async_setup(entry.entry_id)
    assert entry.state is ConfigEntryState.SETUP_ERROR

    with _patch_async_setup_entry() as mock_setup_entry, patch_bond_token(
            return_value={"token": "discovered-token"}):
        result = await hass.config_entries.flow.async_init(
            DOMAIN,
            context={"source": config_entries.SOURCE_ZEROCONF},
            data=zeroconf.ZeroconfServiceInfo(
                host="updated-host",
                addresses=["updated-host"],
                hostname="mock_hostname",
                name="already-registered-bond-id.some-other-tail-info",
                port=None,
                properties={},
                type="mock_type",
            ),
        )
        await hass.async_block_till_done()

    assert result["type"] == "abort"
    assert result["reason"] == "already_configured"
    assert entry.data["host"] == "updated-host"
    assert entry.data[CONF_ACCESS_TOKEN] == "discovered-token"
    # entry2 should not get changed
    assert entry2.data[CONF_ACCESS_TOKEN] == "correct-token"
    assert len(mock_setup_entry.mock_calls) == 1
async def test_remove_entry_installedapp_api_error(
    hass, config_entry, smartthings_mock
):
    """Test raises exceptions removing the installed app."""
    # Arrange
    smartthings_mock.delete_installed_app.side_effect = ClientResponseError(
        None, None, status=500
    )
    # Act
    with pytest.raises(ClientResponseError):
        await smartthings.async_remove_entry(hass, config_entry)
    # Assert
    assert smartthings_mock.delete_installed_app.call_count == 1
    assert smartthings_mock.delete_app.call_count == 0
Exemple #8
0
async def test_remove_entry_app_api_error(hass, config_entry,
                                          smartthings_mock):
    """Test raises exceptions removing the app."""
    # Arrange
    api = smartthings_mock.return_value
    api.delete_installed_app.side_effect = lambda _: mock_coro()
    api.delete_app.side_effect = lambda _: mock_coro(
        exception=ClientResponseError(None, None, status=500))
    # Act
    with pytest.raises(ClientResponseError):
        await smartthings.async_remove_entry(hass, config_entry)
    # Assert
    assert api.delete_installed_app.call_count == 1
    assert api.delete_app.call_count == 1
Exemple #9
0
async def test_recoverable_api_errors_raise_not_ready(
    hass, config_entry, smartthings_mock
):
    """Test config entry not ready raised for recoverable API errors."""
    config_entry.add_to_hass(hass)
    request_info = Mock(real_url="http://example.com")
    smartthings_mock.app.side_effect = ClientResponseError(
        request_info=request_info,
        history=None,
        status=HTTPStatus.INTERNAL_SERVER_ERROR,
    )

    with pytest.raises(ConfigEntryNotReady):
        await smartthings.async_setup_entry(hass, config_entry)
async def test_form_response_errors(
    opp, mock_login, mock_get_devices, mock_request_info, error, message
):
    """Test we handle response errors."""
    mock_login.side_effect = ClientResponseError(mock_request_info(), (), status=error)

    result = await opp.config_entries.flow.async_init(
        DOMAIN,
        context={"source": config_entries.SOURCE_USER},
        data={"username": "******", "password": "******"},
    )

    assert result["type"] == "abort"
    assert result["reason"] == message
async def test_token_forbidden(hass, smartthings_mock):
    """Test an error is shown when the token is forbidden."""
    flow = SmartThingsFlowHandler()
    flow.hass = hass

    request_info = Mock(real_url="http://example.com")
    smartthings_mock.apps.side_effect = ClientResponseError(
        request_info=request_info, history=None, status=403)

    result = await flow.async_step_user({"access_token": str(uuid4())})

    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "user"
    assert result["errors"] == {"access_token": "token_forbidden"}
Exemple #12
0
async def test_step_pat_unknown_api_error(hass, smartthings_mock):
    """Test an error is shown when there is an unknown API error."""
    flow = SmartThingsFlowHandler()
    flow.hass = hass
    request_info = Mock(real_url="http://example.com")
    smartthings_mock.apps.side_effect = ClientResponseError(
        request_info=request_info, history=None, status=HTTP_NOT_FOUND)
    token = str(uuid4())

    result = await flow.async_step_pat({CONF_ACCESS_TOKEN: token})

    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "pat"
    assert result["errors"] == {"base": "app_setup_error"}
    assert result["data_schema"]({}) == {CONF_ACCESS_TOKEN: token}
Exemple #13
0
 async def test_if_same_site_and_not_html_head_not_supported(self,  m):
     exception = ClientResponseError(None, None, status=405)
     self._prep_request(
         m,
         TEST_HOME_URL,
         headexception=exception,
         content_type=TYPE_JSON)
     async with ClientSession() as session:
         response = await self.testobj.fetch_response(
                 session, self.urltarget)
         self.assertIs(self.urltarget, response.urltarget)
         self.assertEqual(200, response.status)
         self.assertIsNone(response.html)
         self.assertIsNone(response.error)
         self.assertEqual(TEST_EXPECTED_ELAPSED, response.elapsed)
Exemple #14
0
async def test_step_pat_forbidden(hass, smartthings_mock):
    """Test an error is shown when the token is forbidden."""
    flow = SmartThingsFlowHandler()
    flow.hass = hass
    request_info = Mock(real_url="http://example.com")
    smartthings_mock.apps.side_effect = ClientResponseError(
        request_info=request_info, history=None, status=HTTP_FORBIDDEN)
    token = str(uuid4())

    result = await flow.async_step_pat({CONF_ACCESS_TOKEN: token})

    assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result["step_id"] == "pat"
    assert result["errors"] == {CONF_ACCESS_TOKEN: "token_forbidden"}
    assert result["data_schema"]({}) == {CONF_ACCESS_TOKEN: token}
Exemple #15
0
    async def update(self):
        resp = await self.session.get(self.url)
        if resp.status == 200:
            data = await resp.json()
        else:
            raise ClientResponseError(resp.request_info, resp.history)
        self.count = data['status']['count']

        for gd in data['GroundDelays']['groundDelay']:
            # Define a ground delay object and append that to the list of nationwide ground delays
            gdelay = GroundDelay(gd['airport'], True, gd['avgTime'],
                                 gd['reason'])

            self.ground_delays.append(gdelay)

        self.ground_delay_count = data['GroundDelays']['count']
        for gs in data['GroundStops']['groundStop']:
            # Define a ground stop object and append that to the list of nationwide ground stops
            stop = GroundStop(gs['airport'], True, gs['endTime'], gs['reason'])

            self.ground_stops.append(stop)

        self.ground_stop_count = data['GroundStops']['count']
        for ad in data['ArriveDepartDelays']['arriveDepart']:
            # Define an Arrival/Departure object and append that to the list of nationwide arrival/departure delays
            ardp = ArriveDepartDelay(
                ad['airport'],
                True,
                ad['minTime'],
                ad['maxTime'],
                None,  # The API does not provide a trend for Arrival/Departure delays from the nationwide call so none will be passed through.
                ad['reason'])

            self.arrive_depart_delays.append(ardp)

        self.arrive_depart_count = data['ArriveDepartDelays']['count']
        for cl in data['Closures']['closure']:
            # Define a closure object and append that to the list of nationwide closures
            close = Closure(
                cl['airport'],
                True,
                None,  # The API does not provide a beginning time for a closure from the nationwide call so none will be passed through.
                cl['reopen'],
                cl['reason'])

            self.closures.append(close)

        self.closure_count = data['Closures']['count']
Exemple #16
0
async def test_server_error(hass: HomeAssistant, mock_get_regions) -> None:
    """Test we can create entry for just region."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER})
    assert result["type"] == RESULT_TYPE_FORM

    mock_get_regions.side_effect = ClientResponseError(None, None, status=500)

    result2 = await hass.config_entries.flow.async_configure(
        result["flow_id"],
        {
            "api_key": MOCK_API_KEY,
        },
    )
    assert result2["type"] == RESULT_TYPE_FORM
    assert result2["step_id"] == "user"
    assert result2["errors"] == {"base": "unknown"}
Exemple #17
0
 async def load_resource(cls, ticker) -> str:
     res = await cls.SESSION.get(
         f"{cls.BASE_URL}{ticker}",
         headers={
             "User-Agent": cls.USER_AGENT,
             "Accept": "text/html",
             "Accept-Language": "en,ru;q=0.9,cs;q=0.8,la;q=0.7",
             "Accept-Encoding": "gzip, deflate",
         },
     )
     if res.status != 200 or "lookup" in res.url.path:
         raise ClientResponseError(res.request_info,
                                   res.history,
                                   status=res.status,
                                   message=res.reason,
                                   headers=res.headers)
     return await res.text(encoding="utf-8")
    async def _get_power_log(self, device):
        """Get power log from the device."""
        headers = {
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache',
            'Expires': '-1',
            'auth': device['auth'],
            'Origin': 'file://',
            'CPToken': self.CPToken,
            'Content-Type': 'application/json',
            'Charset': 'utf-8',
            'User-Agent': USERAGENT,
            'Host': self.host,
            'Connection': 'Keep-Alive'
        }

        payload = {
            'gw_id': device['GWID'],
            'aread_ids': [0],
            'from': datetime.datetime.now().strftime('%Y/%m/%d'),
            'unit': 'hour',
            'max_num': 24
        }
        print(payload)
        print('url:' + 'https://' + self.host + '/api/PowerGetCTAreaLog')
        async with self.session.post('https://' + self.host +
                                     '/api/PowerGetCTAreaLog',
                                     data=json.dumps(payload),
                                     headers=headers) as response:

            if response.status != 200:
                raise ClientResponseError(
                    request_info=None,
                    history=None,
                    status=response.status,
                    message=('Get power log error. '
                             'status = ' + str(response.status) + ', '
                             'data = ' + json.dumps(payload) + ', '
                             'headers = ' + json.dumps(headers) + '.'))
            response_json = await response.json()
            print(response_json)
            info = response_json.get('Areas')[0].get('kwh')
            if response_json.get('status') == 'success':
                return info
            else:
                return None
Exemple #19
0
async def test_form_unexpected_error(hass: core.HomeAssistant):
    """Test we handle unexpected error gracefully."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER})

    with patch_bond_device_ids(
            side_effect=ClientResponseError(Mock(), Mock(), status=500)):
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {
                CONF_HOST: "some host",
                CONF_ACCESS_TOKEN: "test-token"
            },
        )

    assert result2["type"] == "form"
    assert result2["errors"] == {"base": "unknown"}
    async def _device_status(self, device, commands):
        """Get device status."""
        headers = {
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache',
            'Expires': '-1',
            'CPToken': self.CPToken,
            'auth': device['auth'],
            'Content-Type': 'application/json',
            'Charset': 'utf-8',
            'User-Agent': USERAGENT,
            'Host': self.host,
            'Connection': 'Keep-Alive'
        }

        command_list = []
        for command in commands:
            command_list.append(
                {'CommandType': '{0:#0{1}x}'.format(command, 4)})

        payload = [{
            'CommandTypes': command_list,
            'DeviceID': int(device['DeviceID'])
        }]

        async with self.session.post('https://' + self.host +
                                     '/api/DeviceGetInfo',
                                     data=json.dumps(payload),
                                     headers=headers) as response:

            if response.status != 200:
                raise ClientResponseError(
                    request_info=None,
                    history=None,
                    status=response.status,
                    message=('Get device status error. '
                             'status = ' + str(response.status) + ', '
                             'data = ' + json.dumps(payload) + ', '
                             'headers = ' + json.dumps(headers) + '.'))
            response_json = await response.json()
            info = response_json.get('devices')[0].get('Info')
            if response_json.get('status') == 'success':
                return info
            else:
                return None
Exemple #21
0
async def test_user_form_invalid_auth(hass: core.HomeAssistant):
    """Test we handle invalid auth."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER})

    with patch_bond_version(
            return_value={"bond_id": "test-bond-id"}), patch_bond_device_ids(
                side_effect=ClientResponseError(Mock(), Mock(), status=401), ):
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {
                CONF_HOST: "some host",
                CONF_ACCESS_TOKEN: "test-token"
            },
        )

    assert result2["type"] == "form"
    assert result2["errors"] == {"base": "invalid_auth"}
Exemple #22
0
async def test_august_api_is_failing(hass):
    """Config entry state is SETUP_RETRY when august api is failing."""

    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data=_mock_get_config()[DOMAIN],
        title="August august",
    )
    config_entry.add_to_hass(hass)

    with patch(
            "yalexs.authenticator_async.AuthenticatorAsync.async_authenticate",
            side_effect=ClientResponseError(None, None, status=500),
    ):
        await hass.config_entries.async_setup(config_entry.entry_id)
        await hass.async_block_till_done()

    assert config_entry.state is ConfigEntryState.SETUP_RETRY
Exemple #23
0
async def test_user_form_api_key_required(opp):
    """Test we handle an unauthorized error."""
    result = await opp.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER})

    with patch(
            "openpeerpower.components.nightscout.NightscoutAPI.get_server_status",
            return_value=SERVER_STATUS_STATUS_ONLY,
    ), patch(
            "openpeerpower.components.nightscout.NightscoutAPI.get_sgvs",
            side_effect=ClientResponseError(None, None, status=401),
    ):
        result2 = await opp.config_entries.flow.async_configure(
            result["flow_id"],
            {CONF_URL: "https://some.url:1234"},
        )

    assert result2["type"] == data_entry_flow.RESULT_TYPE_FORM
    assert result2["errors"] == {"base": "invalid_auth"}
Exemple #24
0
async def test_form_cannot_connect(hass):
    """Test we handle cannot connect error."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER})

    with patch(
            "homeassistant.components.rituals_perfume_genie.config_flow.Account.authenticate",
            side_effect=ClientResponseError(None, None, status=500),
    ):
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {
                CONF_EMAIL: TEST_EMAIL,
                CONF_PASSWORD: VALID_PASSWORD,
            },
        )

    assert result2["type"] == "form"
    assert result2["errors"] == {"base": "cannot_connect"}
async def test_form_invalid_auth(hass):
    """Test we handle invalid auth."""
    result = await hass.config_entries.flow.async_init(
        DOMAIN, context={"source": config_entries.SOURCE_USER})

    with patch(
            "homeassistant.components.kmtronic.config_flow.KMTronicHubAPI.async_get_status",
            side_effect=ClientResponseError(None, None, status=401),
    ):
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {
                "host": "1.1.1.1",
                "username": "******",
                "password": "******",
            },
        )

    assert result2["type"] == "form"
    assert result2["errors"] == {"base": "invalid_auth"}
Exemple #26
0
async def test_smart_by_bond_device_suggested_area(hass: HomeAssistant):
    """Test we can setup a smart by bond device and get the suggested area."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data={CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"},
    )

    config_entry.add_to_hass(hass)

    with patch_bond_bridge(
        side_effect=ClientResponseError(Mock(), Mock(), status=404)
    ), patch_bond_version(
        return_value={
            "bondid": "test-bond-id",
            "target": "test-model",
            "fw_ver": "test-version",
        }
    ), patch_start_bpup(), patch_bond_device_ids(
        return_value=["bond-device-id", "device_id"]
    ), patch_bond_device(
        return_value={
            "name": "test1",
            "type": DeviceType.GENERIC_DEVICE,
            "location": "Den",
        }
    ), patch_bond_device_properties(
        return_value={}
    ), patch_bond_device_state(
        return_value={}
    ):
        assert await hass.config_entries.async_setup(config_entry.entry_id) is True
        await hass.async_block_till_done()

    assert config_entry.entry_id in hass.data[DOMAIN]
    assert config_entry.state is ConfigEntryState.LOADED
    assert config_entry.unique_id == "test-bond-id"

    device_registry = dr.async_get(hass)
    device = device_registry.async_get_device(identifiers={(DOMAIN, "test-bond-id")})
    assert device is not None
    assert device.suggested_area == "Den"
Exemple #27
0
async def test_http_failure(opp):
    """Config entry state is SETUP_RETRY when august is offline."""

    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data=_mock_get_config()[DOMAIN],
        title="August august",
    )
    config_entry.add_to_opp(opp)
    assert opp.config_entries.flow.async_progress() == []

    await setup.async_setup_component(opp, "persistent_notification", {})
    with patch(
            "yalexs.authenticator_async.AuthenticatorAsync.async_authenticate",
            side_effect=ClientResponseError(None, None, status=500),
    ):
        await opp.config_entries.async_setup(config_entry.entry_id)
        await opp.async_block_till_done()

    assert config_entry.state is ConfigEntryState.SETUP_RETRY

    assert opp.config_entries.flow.async_progress() == []
Exemple #28
0
 async def request(self, method, url, data, headers, **kwargs):
     try:
         # print(url)
         with async_timeout.timeout(TIMEOUT):
             async with self._session.request(method,
                                              url,
                                              headers=headers,
                                              data=data) as response:
                 # print(response)
                 if response.status == 200 or response.status == 202:
                     return await response.json(loads=json_loads)
                 else:
                     raise ClientResponseError(
                         response.request_info,
                         response.history,
                         status=response.status,
                         message=response.reason,
                     )
     except TimeoutError:
         raise TimeoutError("Timeout error")
     except Exception:
         raise
Exemple #29
0
async def get_cases(session: ClientSession, *, source=DEFAULT_SOURCE):
    """Fetch Corona Virus cases."""
    resp = await session.get(source.URL)
    data = await resp.json(content_type=None)

    if 'error' in data:
        # API does not set correct status header so we manually check.
        raise ClientResponseError(resp.request_info,
                                  resp.history,
                                  status=data['error']['code'],
                                  message=data['error']['message'],
                                  headers=resp.headers)

    results = []

    for item in data["features"]:
        try:
            results.append(source.from_json(item))
        except KeyError:
            logging.getLogger(__name__).warning("Got wrong data: %s", item)

    return results
Exemple #30
0
async def test_zeroconf_form_with_token_available_name_unavailable(
    hass: core.HomeAssistant,
):
    """Test we get the discovery form when we can get the token but the name is unavailable."""

    with patch_bond_version(
        side_effect=ClientResponseError(Mock(), (), status=HTTPStatus.BAD_REQUEST)
    ), patch_bond_token(return_value={"token": "discovered-token"}):
        result = await hass.config_entries.flow.async_init(
            DOMAIN,
            context={"source": config_entries.SOURCE_ZEROCONF},
            data=zeroconf.ZeroconfServiceInfo(
                host="test-host",
                hostname="mock_hostname",
                name="test-bond-id.some-other-tail-info",
                port=None,
                properties={},
                type="mock_type",
            ),
        )
        await hass.async_block_till_done()
    assert result["type"] == "form"
    assert result["errors"] == {}

    with _patch_async_setup_entry() as mock_setup_entry:
        result2 = await hass.config_entries.flow.async_configure(
            result["flow_id"],
            {},
        )
        await hass.async_block_till_done()

    assert result2["type"] == "create_entry"
    assert result2["title"] == "test-bond-id"
    assert result2["data"] == {
        CONF_HOST: "test-host",
        CONF_ACCESS_TOKEN: "discovered-token",
    }
    assert len(mock_setup_entry.mock_calls) == 1