Merge pull request #27572 from home-assistant/rc

0.100.2
This commit is contained in:
Paulus Schoutsen 2019-10-12 23:33:53 -07:00 committed by GitHub
commit 71f73af535
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 180 additions and 134 deletions

View File

@ -67,6 +67,10 @@ class EcobeeBinarySensor(BinarySensorDevice):
"""Get the latest state of the sensor.""" """Get the latest state of the sensor."""
await self.data.update() await self.data.update()
for sensor in self.data.ecobee.get_remote_sensors(self.index): for sensor in self.data.ecobee.get_remote_sensors(self.index):
if sensor["name"] != self.sensor_name:
continue
for item in sensor["capability"]: for item in sensor["capability"]:
if item["type"] == "occupancy" and self.sensor_name == sensor["name"]: if item["type"] != "occupancy":
continue
self._state = item["value"] self._state = item["value"]
break

View File

@ -74,7 +74,7 @@ class EcobeeSensor(Entity):
@property @property
def state(self): def state(self):
"""Return the state of the sensor.""" """Return the state of the sensor."""
if self._state in [ECOBEE_STATE_CALIBRATING, ECOBEE_STATE_UNKNOWN]: if self._state in [ECOBEE_STATE_CALIBRATING, ECOBEE_STATE_UNKNOWN, "unknown"]:
return None return None
if self.type == "temperature": if self.type == "temperature":
@ -91,6 +91,10 @@ class EcobeeSensor(Entity):
"""Get the latest state of the sensor.""" """Get the latest state of the sensor."""
await self.data.update() await self.data.update()
for sensor in self.data.ecobee.get_remote_sensors(self.index): for sensor in self.data.ecobee.get_remote_sensors(self.index):
if sensor["name"] != self.sensor_name:
continue
for item in sensor["capability"]: for item in sensor["capability"]:
if item["type"] == self.type and self.sensor_name == sensor["name"]: if item["type"] != self.type:
continue
self._state = item["value"] self._state = item["value"]
break

View File

@ -1,15 +1,21 @@
"""Google Report State implementation.""" """Google Report State implementation."""
import logging
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.const import MATCH_ALL from homeassistant.const import MATCH_ALL
from homeassistant.helpers.event import async_call_later from homeassistant.helpers.event import async_call_later
from .helpers import AbstractConfig, GoogleEntity, async_get_entities from .helpers import AbstractConfig, GoogleEntity, async_get_entities
from .error import SmartHomeError
# Time to wait until the homegraph updates # Time to wait until the homegraph updates
# https://github.com/actions-on-google/smart-home-nodejs/issues/196#issuecomment-439156639 # https://github.com/actions-on-google/smart-home-nodejs/issues/196#issuecomment-439156639
INITIAL_REPORT_DELAY = 60 INITIAL_REPORT_DELAY = 60
_LOGGER = logging.getLogger(__name__)
@callback @callback
def async_enable_report_state(hass: HomeAssistant, google_config: AbstractConfig): def async_enable_report_state(hass: HomeAssistant, google_config: AbstractConfig):
"""Enable state reporting.""" """Enable state reporting."""
@ -26,7 +32,11 @@ def async_enable_report_state(hass: HomeAssistant, google_config: AbstractConfig
if not entity.is_supported(): if not entity.is_supported():
return return
try:
entity_data = entity.query_serialize() entity_data = entity.query_serialize()
except SmartHomeError as err:
_LOGGER.debug("Not reporting state for %s: %s", changed_entity, err.code)
return
if old_state: if old_state:
old_entity = GoogleEntity(hass, google_config, old_state) old_entity = GoogleEntity(hass, google_config, old_state)

View File

@ -3,7 +3,7 @@ import asyncio
from functools import wraps from functools import wraps
import logging import logging
from aiohttp import CookieJar from aiohttp import ClientTimeout
import voluptuous as vol import voluptuous as vol
from iaqualink import ( from iaqualink import (
@ -85,7 +85,7 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> None
sensors = hass.data[DOMAIN][SENSOR_DOMAIN] = [] sensors = hass.data[DOMAIN][SENSOR_DOMAIN] = []
switches = hass.data[DOMAIN][SWITCH_DOMAIN] = [] switches = hass.data[DOMAIN][SWITCH_DOMAIN] = []
session = async_create_clientsession(hass, cookie_jar=CookieJar(unsafe=True)) session = async_create_clientsession(hass, timeout=ClientTimeout(total=5))
aqualink = AqualinkClient(username, password, session) aqualink = AqualinkClient(username, password, session)
try: try:
await aqualink.login() await aqualink.login()

View File

@ -7,6 +7,7 @@
"PyNaCl==1.3.0" "PyNaCl==1.3.0"
], ],
"dependencies": [ "dependencies": [
"cloud",
"http", "http",
"webhook" "webhook"
], ],

View File

@ -34,9 +34,9 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
name = discovery_info["client_name"] name = discovery_info["client_name"]
devices = [] devices = []
for sensor_type, sensor_config in SENSOR_TYPES.items(): for sensor_config in SENSOR_TYPES.values():
new_sensor = NZBGetSensor( new_sensor = NZBGetSensor(
nzbget_data, sensor_type, name, sensor_config[0], sensor_config[1] nzbget_data, sensor_config[0], name, sensor_config[1], sensor_config[2]
) )
devices.append(new_sensor) devices.append(new_sensor)
@ -50,8 +50,8 @@ class NZBGetSensor(Entity):
self, nzbget_data, sensor_type, client_name, sensor_name, unit_of_measurement self, nzbget_data, sensor_type, client_name, sensor_name, unit_of_measurement
): ):
"""Initialize a new NZBGet sensor.""" """Initialize a new NZBGet sensor."""
self._name = f"{client_name} {sensor_type}" self._name = f"{client_name} {sensor_name}"
self.type = sensor_name self.type = sensor_type
self.client_name = client_name self.client_name = client_name
self.nzbget_data = nzbget_data self.nzbget_data = nzbget_data
self._state = None self._state = None

View File

@ -3,7 +3,7 @@
"name": "Songpal", "name": "Songpal",
"documentation": "https://www.home-assistant.io/integrations/songpal", "documentation": "https://www.home-assistant.io/integrations/songpal",
"requirements": [ "requirements": [
"python-songpal==0.0.9.1" "python-songpal==0.11.1"
], ],
"dependencies": [], "dependencies": [],
"codeowners": [ "codeowners": [

View File

@ -4,7 +4,7 @@ import logging
import re import re
import time import time
import nokia import withings_api as withings
from oauthlib.oauth2.rfc6749.errors import MissingTokenError from oauthlib.oauth2.rfc6749.errors import MissingTokenError
from requests_oauthlib import TokenUpdated from requests_oauthlib import TokenUpdated
@ -68,7 +68,9 @@ class WithingsDataManager:
service_available = None service_available = None
def __init__(self, hass: HomeAssistantType, profile: str, api: nokia.NokiaApi): def __init__(
self, hass: HomeAssistantType, profile: str, api: withings.WithingsApi
):
"""Constructor.""" """Constructor."""
self._hass = hass self._hass = hass
self._api = api self._api = api
@ -253,7 +255,7 @@ def create_withings_data_manager(
"""Set up the sensor config entry.""" """Set up the sensor config entry."""
entry_creds = entry.data.get(const.CREDENTIALS) or {} entry_creds = entry.data.get(const.CREDENTIALS) or {}
profile = entry.data[const.PROFILE] profile = entry.data[const.PROFILE]
credentials = nokia.NokiaCredentials( credentials = withings.WithingsCredentials(
entry_creds.get("access_token"), entry_creds.get("access_token"),
entry_creds.get("token_expiry"), entry_creds.get("token_expiry"),
entry_creds.get("token_type"), entry_creds.get("token_type"),
@ -266,7 +268,7 @@ def create_withings_data_manager(
def credentials_saver(credentials_param): def credentials_saver(credentials_param):
_LOGGER.debug("Saving updated credentials of type %s", type(credentials_param)) _LOGGER.debug("Saving updated credentials of type %s", type(credentials_param))
# Sanitizing the data as sometimes a NokiaCredentials object # Sanitizing the data as sometimes a WithingsCredentials object
# is passed through from the API. # is passed through from the API.
cred_data = credentials_param cred_data = credentials_param
if not isinstance(credentials_param, dict): if not isinstance(credentials_param, dict):
@ -275,8 +277,8 @@ def create_withings_data_manager(
entry.data[const.CREDENTIALS] = cred_data entry.data[const.CREDENTIALS] = cred_data
hass.config_entries.async_update_entry(entry, data={**entry.data}) hass.config_entries.async_update_entry(entry, data={**entry.data})
_LOGGER.debug("Creating nokia api instance") _LOGGER.debug("Creating withings api instance")
api = nokia.NokiaApi( api = withings.WithingsApi(
credentials, refresh_cb=(lambda token: credentials_saver(api.credentials)) credentials, refresh_cb=(lambda token: credentials_saver(api.credentials))
) )

View File

@ -4,7 +4,7 @@ import logging
from typing import Optional from typing import Optional
import aiohttp import aiohttp
import nokia import withings_api as withings
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries, data_entry_flow from homeassistant import config_entries, data_entry_flow
@ -75,7 +75,7 @@ class WithingsFlowHandler(config_entries.ConfigFlow):
profile, profile,
) )
return nokia.NokiaAuth( return withings.WithingsAuth(
client_id, client_id,
client_secret, client_secret,
callback_uri, callback_uri,

View File

@ -4,7 +4,7 @@
"config_flow": true, "config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/withings", "documentation": "https://www.home-assistant.io/integrations/withings",
"requirements": [ "requirements": [
"nokia==1.2.0" "withings-api==2.0.0b8"
], ],
"dependencies": [ "dependencies": [
"api", "api",

View File

@ -1,7 +1,7 @@
"""Constants used by Home Assistant components.""" """Constants used by Home Assistant components."""
MAJOR_VERSION = 0 MAJOR_VERSION = 0
MINOR_VERSION = 100 MINOR_VERSION = 100
PATCH_VERSION = "1" PATCH_VERSION = "2"
__short_version__ = "{}.{}".format(MAJOR_VERSION, MINOR_VERSION) __short_version__ = "{}.{}".format(MAJOR_VERSION, MINOR_VERSION)
__version__ = "{}.{}".format(__short_version__, PATCH_VERSION) __version__ = "{}.{}".format(__short_version__, PATCH_VERSION)
REQUIRED_PYTHON_VER = (3, 6, 0) REQUIRED_PYTHON_VER = (3, 6, 0)

View File

@ -865,9 +865,6 @@ niko-home-control==0.2.1
# homeassistant.components.nilu # homeassistant.components.nilu
niluclient==0.1.2 niluclient==0.1.2
# homeassistant.components.withings
nokia==1.2.0
# homeassistant.components.nederlandse_spoorwegen # homeassistant.components.nederlandse_spoorwegen
nsapi==2.7.4 nsapi==2.7.4
@ -1558,7 +1555,7 @@ python-ripple-api==0.0.3
python-sochain-api==0.0.2 python-sochain-api==0.0.2
# homeassistant.components.songpal # homeassistant.components.songpal
python-songpal==0.0.9.1 python-songpal==0.11.1
# homeassistant.components.synologydsm # homeassistant.components.synologydsm
python-synology==0.2.0 python-synology==0.2.0
@ -1973,6 +1970,9 @@ websockets==6.0
# homeassistant.components.wirelesstag # homeassistant.components.wirelesstag
wirelesstagpy==0.4.0 wirelesstagpy==0.4.0
# homeassistant.components.withings
withings-api==2.0.0b8
# homeassistant.components.wunderlist # homeassistant.components.wunderlist
wunderpy2==0.1.6 wunderpy2==0.1.6

View File

@ -228,9 +228,6 @@ minio==4.0.9
# homeassistant.components.ssdp # homeassistant.components.ssdp
netdisco==2.6.0 netdisco==2.6.0
# homeassistant.components.withings
nokia==1.2.0
# homeassistant.components.iqvia # homeassistant.components.iqvia
# homeassistant.components.opencv # homeassistant.components.opencv
# homeassistant.components.tensorflow # homeassistant.components.tensorflow
@ -448,6 +445,9 @@ vultr==0.1.2
# homeassistant.components.wake_on_lan # homeassistant.components.wake_on_lan
wakeonlan==1.1.6 wakeonlan==1.1.6
# homeassistant.components.withings
withings-api==2.0.0b8
# homeassistant.components.zeroconf # homeassistant.components.zeroconf
zeroconf==0.23.0 zeroconf==0.23.0

View File

@ -185,6 +185,7 @@ TEST_REQUIREMENTS = (
"YesssSMS", "YesssSMS",
"zeroconf", "zeroconf",
"zigpy-homeassistant", "zigpy-homeassistant",
"withings-api",
) )
IGNORE_PIN = ("colorlog>2.1,<3", "keyring>=9.3,<10.0", "urllib3") IGNORE_PIN = ("colorlog>2.1,<3", "keyring>=9.3,<10.0", "urllib3")

View File

@ -1,7 +1,7 @@
"""Test Google report state.""" """Test Google report state."""
from unittest.mock import patch from unittest.mock import patch
from homeassistant.components.google_assistant import report_state from homeassistant.components.google_assistant import report_state, error
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
from . import BASIC_CONFIG from . import BASIC_CONFIG
@ -10,7 +10,7 @@ from . import BASIC_CONFIG
from tests.common import mock_coro, async_fire_time_changed from tests.common import mock_coro, async_fire_time_changed
async def test_report_state(hass): async def test_report_state(hass, caplog):
"""Test report state works.""" """Test report state works."""
hass.states.async_set("light.ceiling", "off") hass.states.async_set("light.ceiling", "off")
hass.states.async_set("switch.ac", "on") hass.states.async_set("switch.ac", "on")
@ -57,6 +57,19 @@ async def test_report_state(hass):
assert len(mock_report.mock_calls) == 0 assert len(mock_report.mock_calls) == 0
# Test that entities that we can't query don't report a state
with patch.object(
BASIC_CONFIG, "async_report_state", side_effect=mock_coro
) as mock_report, patch(
"homeassistant.components.google_assistant.report_state.GoogleEntity.query_serialize",
side_effect=error.SmartHomeError("mock-error", "mock-msg"),
):
hass.states.async_set("light.kitchen", "off")
await hass.async_block_till_done()
assert "Not reporting state for light.kitchen: mock-error"
assert len(mock_report.mock_calls) == 0
unsub() unsub()
with patch.object( with patch.object(

View File

@ -1,7 +1,7 @@
"""Common data for for the withings component tests.""" """Common data for for the withings component tests."""
import time import time
import nokia import withings_api as withings
import homeassistant.components.withings.const as const import homeassistant.components.withings.const as const
@ -92,7 +92,7 @@ def new_measure(type_str, value, unit):
} }
def nokia_sleep_response(states): def withings_sleep_response(states):
"""Create a sleep response based on states.""" """Create a sleep response based on states."""
data = [] data = []
for state in states: for state in states:
@ -104,10 +104,10 @@ def nokia_sleep_response(states):
) )
) )
return nokia.NokiaSleep(new_sleep_data("aa", data)) return withings.WithingsSleep(new_sleep_data("aa", data))
NOKIA_MEASURES_RESPONSE = nokia.NokiaMeasures( WITHINGS_MEASURES_RESPONSE = withings.WithingsMeasures(
{ {
"updatetime": "", "updatetime": "",
"timezone": "", "timezone": "",
@ -174,7 +174,7 @@ NOKIA_MEASURES_RESPONSE = nokia.NokiaMeasures(
) )
NOKIA_SLEEP_RESPONSE = nokia_sleep_response( WITHINGS_SLEEP_RESPONSE = withings_sleep_response(
[ [
const.MEASURE_TYPE_SLEEP_STATE_AWAKE, const.MEASURE_TYPE_SLEEP_STATE_AWAKE,
const.MEASURE_TYPE_SLEEP_STATE_LIGHT, const.MEASURE_TYPE_SLEEP_STATE_LIGHT,
@ -183,7 +183,7 @@ NOKIA_SLEEP_RESPONSE = nokia_sleep_response(
] ]
) )
NOKIA_SLEEP_SUMMARY_RESPONSE = nokia.NokiaSleepSummary( WITHINGS_SLEEP_SUMMARY_RESPONSE = withings.WithingsSleepSummary(
{ {
"series": [ "series": [
new_sleep_summary( new_sleep_summary(

View File

@ -3,7 +3,7 @@ import time
from typing import Awaitable, Callable, List from typing import Awaitable, Callable, List
import asynctest import asynctest
import nokia import withings_api as withings
import pytest import pytest
import homeassistant.components.api as api import homeassistant.components.api as api
@ -15,9 +15,9 @@ from homeassistant.const import CONF_UNIT_SYSTEM, CONF_UNIT_SYSTEM_METRIC
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from .common import ( from .common import (
NOKIA_MEASURES_RESPONSE, WITHINGS_MEASURES_RESPONSE,
NOKIA_SLEEP_RESPONSE, WITHINGS_SLEEP_RESPONSE,
NOKIA_SLEEP_SUMMARY_RESPONSE, WITHINGS_SLEEP_SUMMARY_RESPONSE,
) )
@ -34,17 +34,17 @@ class WithingsFactoryConfig:
measures: List[str] = None, measures: List[str] = None,
unit_system: str = None, unit_system: str = None,
throttle_interval: int = const.THROTTLE_INTERVAL, throttle_interval: int = const.THROTTLE_INTERVAL,
nokia_request_response="DATA", withings_request_response="DATA",
nokia_measures_response: nokia.NokiaMeasures = NOKIA_MEASURES_RESPONSE, withings_measures_response: withings.WithingsMeasures = WITHINGS_MEASURES_RESPONSE,
nokia_sleep_response: nokia.NokiaSleep = NOKIA_SLEEP_RESPONSE, withings_sleep_response: withings.WithingsSleep = WITHINGS_SLEEP_RESPONSE,
nokia_sleep_summary_response: nokia.NokiaSleepSummary = NOKIA_SLEEP_SUMMARY_RESPONSE, withings_sleep_summary_response: withings.WithingsSleepSummary = WITHINGS_SLEEP_SUMMARY_RESPONSE,
) -> None: ) -> None:
"""Constructor.""" """Constructor."""
self._throttle_interval = throttle_interval self._throttle_interval = throttle_interval
self._nokia_request_response = nokia_request_response self._withings_request_response = withings_request_response
self._nokia_measures_response = nokia_measures_response self._withings_measures_response = withings_measures_response
self._nokia_sleep_response = nokia_sleep_response self._withings_sleep_response = withings_sleep_response
self._nokia_sleep_summary_response = nokia_sleep_summary_response self._withings_sleep_summary_response = withings_sleep_summary_response
self._withings_config = { self._withings_config = {
const.CLIENT_ID: "my_client_id", const.CLIENT_ID: "my_client_id",
const.CLIENT_SECRET: "my_client_secret", const.CLIENT_SECRET: "my_client_secret",
@ -103,24 +103,24 @@ class WithingsFactoryConfig:
return self._throttle_interval return self._throttle_interval
@property @property
def nokia_request_response(self): def withings_request_response(self):
"""Request response.""" """Request response."""
return self._nokia_request_response return self._withings_request_response
@property @property
def nokia_measures_response(self) -> nokia.NokiaMeasures: def withings_measures_response(self) -> withings.WithingsMeasures:
"""Measures response.""" """Measures response."""
return self._nokia_measures_response return self._withings_measures_response
@property @property
def nokia_sleep_response(self) -> nokia.NokiaSleep: def withings_sleep_response(self) -> withings.WithingsSleep:
"""Sleep response.""" """Sleep response."""
return self._nokia_sleep_response return self._withings_sleep_response
@property @property
def nokia_sleep_summary_response(self) -> nokia.NokiaSleepSummary: def withings_sleep_summary_response(self) -> withings.WithingsSleepSummary:
"""Sleep summary response.""" """Sleep summary response."""
return self._nokia_sleep_summary_response return self._withings_sleep_summary_response
class WithingsFactoryData: class WithingsFactoryData:
@ -130,21 +130,21 @@ class WithingsFactoryData:
self, self,
hass, hass,
flow_id, flow_id,
nokia_auth_get_credentials_mock, withings_auth_get_credentials_mock,
nokia_api_request_mock, withings_api_request_mock,
nokia_api_get_measures_mock, withings_api_get_measures_mock,
nokia_api_get_sleep_mock, withings_api_get_sleep_mock,
nokia_api_get_sleep_summary_mock, withings_api_get_sleep_summary_mock,
data_manager_get_throttle_interval_mock, data_manager_get_throttle_interval_mock,
): ):
"""Constructor.""" """Constructor."""
self._hass = hass self._hass = hass
self._flow_id = flow_id self._flow_id = flow_id
self._nokia_auth_get_credentials_mock = nokia_auth_get_credentials_mock self._withings_auth_get_credentials_mock = withings_auth_get_credentials_mock
self._nokia_api_request_mock = nokia_api_request_mock self._withings_api_request_mock = withings_api_request_mock
self._nokia_api_get_measures_mock = nokia_api_get_measures_mock self._withings_api_get_measures_mock = withings_api_get_measures_mock
self._nokia_api_get_sleep_mock = nokia_api_get_sleep_mock self._withings_api_get_sleep_mock = withings_api_get_sleep_mock
self._nokia_api_get_sleep_summary_mock = nokia_api_get_sleep_summary_mock self._withings_api_get_sleep_summary_mock = withings_api_get_sleep_summary_mock
self._data_manager_get_throttle_interval_mock = ( self._data_manager_get_throttle_interval_mock = (
data_manager_get_throttle_interval_mock data_manager_get_throttle_interval_mock
) )
@ -160,29 +160,29 @@ class WithingsFactoryData:
return self._flow_id return self._flow_id
@property @property
def nokia_auth_get_credentials_mock(self): def withings_auth_get_credentials_mock(self):
"""Get auth credentials mock.""" """Get auth credentials mock."""
return self._nokia_auth_get_credentials_mock return self._withings_auth_get_credentials_mock
@property @property
def nokia_api_request_mock(self): def withings_api_request_mock(self):
"""Get request mock.""" """Get request mock."""
return self._nokia_api_request_mock return self._withings_api_request_mock
@property @property
def nokia_api_get_measures_mock(self): def withings_api_get_measures_mock(self):
"""Get measures mock.""" """Get measures mock."""
return self._nokia_api_get_measures_mock return self._withings_api_get_measures_mock
@property @property
def nokia_api_get_sleep_mock(self): def withings_api_get_sleep_mock(self):
"""Get sleep mock.""" """Get sleep mock."""
return self._nokia_api_get_sleep_mock return self._withings_api_get_sleep_mock
@property @property
def nokia_api_get_sleep_summary_mock(self): def withings_api_get_sleep_summary_mock(self):
"""Get sleep summary mock.""" """Get sleep summary mock."""
return self._nokia_api_get_sleep_summary_mock return self._withings_api_get_sleep_summary_mock
@property @property
def data_manager_get_throttle_interval_mock(self): def data_manager_get_throttle_interval_mock(self):
@ -243,9 +243,9 @@ def withings_factory_fixture(request, hass) -> WithingsFactory:
assert await async_setup_component(hass, http.DOMAIN, config.hass_config) assert await async_setup_component(hass, http.DOMAIN, config.hass_config)
assert await async_setup_component(hass, api.DOMAIN, config.hass_config) assert await async_setup_component(hass, api.DOMAIN, config.hass_config)
nokia_auth_get_credentials_patch = asynctest.patch( withings_auth_get_credentials_patch = asynctest.patch(
"nokia.NokiaAuth.get_credentials", "withings_api.WithingsAuth.get_credentials",
return_value=nokia.NokiaCredentials( return_value=withings.WithingsCredentials(
access_token="my_access_token", access_token="my_access_token",
token_expiry=time.time() + 600, token_expiry=time.time() + 600,
token_type="my_token_type", token_type="my_token_type",
@ -255,28 +255,33 @@ def withings_factory_fixture(request, hass) -> WithingsFactory:
consumer_secret=config.withings_config.get(const.CLIENT_SECRET), consumer_secret=config.withings_config.get(const.CLIENT_SECRET),
), ),
) )
nokia_auth_get_credentials_mock = nokia_auth_get_credentials_patch.start() withings_auth_get_credentials_mock = withings_auth_get_credentials_patch.start()
nokia_api_request_patch = asynctest.patch( withings_api_request_patch = asynctest.patch(
"nokia.NokiaApi.request", return_value=config.nokia_request_response "withings_api.WithingsApi.request",
return_value=config.withings_request_response,
) )
nokia_api_request_mock = nokia_api_request_patch.start() withings_api_request_mock = withings_api_request_patch.start()
nokia_api_get_measures_patch = asynctest.patch( withings_api_get_measures_patch = asynctest.patch(
"nokia.NokiaApi.get_measures", return_value=config.nokia_measures_response "withings_api.WithingsApi.get_measures",
return_value=config.withings_measures_response,
) )
nokia_api_get_measures_mock = nokia_api_get_measures_patch.start() withings_api_get_measures_mock = withings_api_get_measures_patch.start()
nokia_api_get_sleep_patch = asynctest.patch( withings_api_get_sleep_patch = asynctest.patch(
"nokia.NokiaApi.get_sleep", return_value=config.nokia_sleep_response "withings_api.WithingsApi.get_sleep",
return_value=config.withings_sleep_response,
) )
nokia_api_get_sleep_mock = nokia_api_get_sleep_patch.start() withings_api_get_sleep_mock = withings_api_get_sleep_patch.start()
nokia_api_get_sleep_summary_patch = asynctest.patch( withings_api_get_sleep_summary_patch = asynctest.patch(
"nokia.NokiaApi.get_sleep_summary", "withings_api.WithingsApi.get_sleep_summary",
return_value=config.nokia_sleep_summary_response, return_value=config.withings_sleep_summary_response,
)
withings_api_get_sleep_summary_mock = (
withings_api_get_sleep_summary_patch.start()
) )
nokia_api_get_sleep_summary_mock = nokia_api_get_sleep_summary_patch.start()
data_manager_get_throttle_interval_patch = asynctest.patch( data_manager_get_throttle_interval_patch = asynctest.patch(
"homeassistant.components.withings.common.WithingsDataManager" "homeassistant.components.withings.common.WithingsDataManager"
@ -295,11 +300,11 @@ def withings_factory_fixture(request, hass) -> WithingsFactory:
patches.extend( patches.extend(
[ [
nokia_auth_get_credentials_patch, withings_auth_get_credentials_patch,
nokia_api_request_patch, withings_api_request_patch,
nokia_api_get_measures_patch, withings_api_get_measures_patch,
nokia_api_get_sleep_patch, withings_api_get_sleep_patch,
nokia_api_get_sleep_summary_patch, withings_api_get_sleep_summary_patch,
data_manager_get_throttle_interval_patch, data_manager_get_throttle_interval_patch,
get_measures_patch, get_measures_patch,
] ]
@ -328,11 +333,11 @@ def withings_factory_fixture(request, hass) -> WithingsFactory:
return WithingsFactoryData( return WithingsFactoryData(
hass, hass,
flow_id, flow_id,
nokia_auth_get_credentials_mock, withings_auth_get_credentials_mock,
nokia_api_request_mock, withings_api_request_mock,
nokia_api_get_measures_mock, withings_api_get_measures_mock,
nokia_api_get_sleep_mock, withings_api_get_sleep_mock,
nokia_api_get_sleep_summary_mock, withings_api_get_sleep_summary_mock,
data_manager_get_throttle_interval_mock, data_manager_get_throttle_interval_mock,
) )

View File

@ -1,6 +1,6 @@
"""Tests for the Withings component.""" """Tests for the Withings component."""
from asynctest import MagicMock from asynctest import MagicMock
import nokia import withings_api as withings
from oauthlib.oauth2.rfc6749.errors import MissingTokenError from oauthlib.oauth2.rfc6749.errors import MissingTokenError
import pytest import pytest
from requests_oauthlib import TokenUpdated from requests_oauthlib import TokenUpdated
@ -13,19 +13,19 @@ from homeassistant.components.withings.common import (
from homeassistant.exceptions import PlatformNotReady from homeassistant.exceptions import PlatformNotReady
@pytest.fixture(name="nokia_api") @pytest.fixture(name="withings_api")
def nokia_api_fixture(): def withings_api_fixture():
"""Provide nokia api.""" """Provide withings api."""
nokia_api = nokia.NokiaApi.__new__(nokia.NokiaApi) withings_api = withings.WithingsApi.__new__(withings.WithingsApi)
nokia_api.get_measures = MagicMock() withings_api.get_measures = MagicMock()
nokia_api.get_sleep = MagicMock() withings_api.get_sleep = MagicMock()
return nokia_api return withings_api
@pytest.fixture(name="data_manager") @pytest.fixture(name="data_manager")
def data_manager_fixture(hass, nokia_api: nokia.NokiaApi): def data_manager_fixture(hass, withings_api: withings.WithingsApi):
"""Provide data manager.""" """Provide data manager."""
return WithingsDataManager(hass, "My Profile", nokia_api) return WithingsDataManager(hass, "My Profile", withings_api)
def test_print_service(): def test_print_service():

View File

@ -2,7 +2,12 @@
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
import asynctest import asynctest
from nokia import NokiaApi, NokiaMeasures, NokiaSleep, NokiaSleepSummary from withings_api import (
WithingsApi,
WithingsMeasures,
WithingsSleep,
WithingsSleepSummary,
)
import pytest import pytest
from homeassistant.components.withings import DOMAIN from homeassistant.components.withings import DOMAIN
@ -15,7 +20,7 @@ from homeassistant.helpers.entity_component import async_update_entity
from homeassistant.helpers.typing import HomeAssistantType from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util import slugify from homeassistant.util import slugify
from .common import nokia_sleep_response from .common import withings_sleep_response
from .conftest import WithingsFactory, WithingsFactoryConfig from .conftest import WithingsFactory, WithingsFactoryConfig
@ -120,9 +125,9 @@ async def test_health_sensor_state_none(
data = await withings_factory( data = await withings_factory(
WithingsFactoryConfig( WithingsFactoryConfig(
measures=measure, measures=measure,
nokia_measures_response=None, withings_measures_response=None,
nokia_sleep_response=None, withings_sleep_response=None,
nokia_sleep_summary_response=None, withings_sleep_summary_response=None,
) )
) )
@ -153,9 +158,9 @@ async def test_health_sensor_state_empty(
data = await withings_factory( data = await withings_factory(
WithingsFactoryConfig( WithingsFactoryConfig(
measures=measure, measures=measure,
nokia_measures_response=NokiaMeasures({"measuregrps": []}), withings_measures_response=WithingsMeasures({"measuregrps": []}),
nokia_sleep_response=NokiaSleep({"series": []}), withings_sleep_response=WithingsSleep({"series": []}),
nokia_sleep_summary_response=NokiaSleepSummary({"series": []}), withings_sleep_summary_response=WithingsSleepSummary({"series": []}),
) )
) )
@ -201,7 +206,8 @@ async def test_sleep_state_throttled(
data = await withings_factory( data = await withings_factory(
WithingsFactoryConfig( WithingsFactoryConfig(
measures=[measure], nokia_sleep_response=nokia_sleep_response(sleep_states) measures=[measure],
withings_sleep_response=withings_sleep_response(sleep_states),
) )
) )
@ -257,16 +263,16 @@ async def test_async_setup_entry_credentials_saver(hass: HomeAssistantType):
"expires_in": "2", "expires_in": "2",
} }
original_nokia_api = NokiaApi original_withings_api = WithingsApi
nokia_api_instance = None withings_api_instance = None
def new_nokia_api(*args, **kwargs): def new_withings_api(*args, **kwargs):
nonlocal nokia_api_instance nonlocal withings_api_instance
nokia_api_instance = original_nokia_api(*args, **kwargs) withings_api_instance = original_withings_api(*args, **kwargs)
nokia_api_instance.request = MagicMock() withings_api_instance.request = MagicMock()
return nokia_api_instance return withings_api_instance
nokia_api_patch = patch("nokia.NokiaApi", side_effect=new_nokia_api) withings_api_patch = patch("withings_api.WithingsApi", side_effect=new_withings_api)
session_patch = patch("requests_oauthlib.OAuth2Session") session_patch = patch("requests_oauthlib.OAuth2Session")
client_patch = patch("oauthlib.oauth2.WebApplicationClient") client_patch = patch("oauthlib.oauth2.WebApplicationClient")
update_entry_patch = patch.object( update_entry_patch = patch.object(
@ -275,7 +281,7 @@ async def test_async_setup_entry_credentials_saver(hass: HomeAssistantType):
wraps=hass.config_entries.async_update_entry, wraps=hass.config_entries.async_update_entry,
) )
with session_patch, client_patch, nokia_api_patch, update_entry_patch: with session_patch, client_patch, withings_api_patch, update_entry_patch:
async_add_entities = MagicMock() async_add_entities = MagicMock()
hass.config_entries.async_update_entry = MagicMock() hass.config_entries.async_update_entry = MagicMock()
config_entry = ConfigEntry( config_entry = ConfigEntry(
@ -298,7 +304,7 @@ async def test_async_setup_entry_credentials_saver(hass: HomeAssistantType):
await async_setup_entry(hass, config_entry, async_add_entities) await async_setup_entry(hass, config_entry, async_add_entities)
nokia_api_instance.set_token(expected_creds) withings_api_instance.set_token(expected_creds)
new_creds = config_entry.data[const.CREDENTIALS] new_creds = config_entry.data[const.CREDENTIALS]
assert new_creds["access_token"] == "my_access_token2" assert new_creds["access_token"] == "my_access_token2"