Deprecated stuff (#16019)

* Use async with for locks

* Fix regex in template test

* Close session correctly

* Use correct current_task method

* push camera cleanup

* Lint

* Revert current_task

* Update websocket_api.py

* Mock executor_job betteR

* Fix async_create_task mock
This commit is contained in:
Paulus Schoutsen 2018-08-20 16:34:18 +02:00 committed by GitHub
parent 975befd136
commit d1e1b9b38a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 50 additions and 22 deletions

View file

@ -21,6 +21,8 @@ import homeassistant.util.dt as dt_util
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['http']
CONF_BUFFER_SIZE = 'buffer' CONF_BUFFER_SIZE = 'buffer'
CONF_IMAGE_FIELD = 'field' CONF_IMAGE_FIELD = 'field'

View file

@ -330,19 +330,18 @@ class DeviceTracker:
}) })
# update known_devices.yaml # update known_devices.yaml
self.hass.async_add_job( self.hass.async_create_task(
self.async_update_config( self.async_update_config(
self.hass.config.path(YAML_DEVICES), dev_id, device) self.hass.config.path(YAML_DEVICES), dev_id, device)
) )
@asyncio.coroutine async def async_update_config(self, path, dev_id, device):
def async_update_config(self, path, dev_id, device):
"""Add device to YAML configuration file. """Add device to YAML configuration file.
This method is a coroutine. This method is a coroutine.
""" """
with (yield from self._is_updating): async with self._is_updating:
yield from self.hass.async_add_job( await self.hass.async_add_executor_job(
update_config, self.hass.config.path(YAML_DEVICES), update_config, self.hass.config.path(YAML_DEVICES),
dev_id, device) dev_id, device)
@ -681,8 +680,7 @@ def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType,
# Initial scan of each mac we also tell about host name for config # Initial scan of each mac we also tell about host name for config
seen = set() # type: Any seen = set() # type: Any
@asyncio.coroutine async def async_device_tracker_scan(now: dt_util.dt.datetime):
def async_device_tracker_scan(now: dt_util.dt.datetime):
"""Handle interval matches.""" """Handle interval matches."""
if update_lock.locked(): if update_lock.locked():
_LOGGER.warning( _LOGGER.warning(
@ -690,18 +688,18 @@ def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType,
"scan interval %s", platform, interval) "scan interval %s", platform, interval)
return return
with (yield from update_lock): async with update_lock:
found_devices = yield from scanner.async_scan_devices() found_devices = await scanner.async_scan_devices()
for mac in found_devices: for mac in found_devices:
if mac in seen: if mac in seen:
host_name = None host_name = None
else: else:
host_name = yield from scanner.async_get_device_name(mac) host_name = await scanner.async_get_device_name(mac)
seen.add(mac) seen.add(mac)
try: try:
extra_attributes = (yield from extra_attributes = (await
scanner.async_get_extra_attributes(mac)) scanner.async_get_extra_attributes(mac))
except NotImplementedError: except NotImplementedError:
extra_attributes = dict() extra_attributes = dict()

View file

@ -325,7 +325,6 @@ class ActiveConnection:
await wsock.prepare(request) await wsock.prepare(request)
self.debug("Connected") self.debug("Connected")
# Get a reference to current task so we can cancel our connection
self._handle_task = asyncio.Task.current_task(loop=self.hass.loop) self._handle_task = asyncio.Task.current_task(loop=self.hass.loop)
@callback @callback

View file

@ -123,14 +123,30 @@ def async_test_home_assistant(loop):
INSTANCES.append(hass) INSTANCES.append(hass)
orig_async_add_job = hass.async_add_job orig_async_add_job = hass.async_add_job
orig_async_add_executor_job = hass.async_add_executor_job
orig_async_create_task = hass.async_create_task
def async_add_job(target, *args): def async_add_job(target, *args):
"""Add a magic mock.""" """Add job."""
if isinstance(target, Mock): if isinstance(target, Mock):
return mock_coro(target(*args)) return mock_coro(target(*args))
return orig_async_add_job(target, *args) return orig_async_add_job(target, *args)
def async_add_executor_job(target, *args):
"""Add executor job."""
if isinstance(target, Mock):
return mock_coro(target(*args))
return orig_async_add_executor_job(target, *args)
def async_create_task(coroutine):
"""Create task."""
if isinstance(coroutine, Mock):
return mock_coro()
return orig_async_create_task(coroutine)
hass.async_add_job = async_add_job hass.async_add_job = async_add_job
hass.async_add_executor_job = async_add_executor_job
hass.async_create_task = async_create_task
hass.config.location_name = 'test home' hass.config.location_name = 'test home'
hass.config.config_dir = get_test_config_dir() hass.config.config_dir = get_test_config_dir()

View file

@ -30,7 +30,7 @@ async def test_bad_posting(aioclient_mock, hass, aiohttp_client):
assert resp.status == 400 assert resp.status == 400
async def test_posting_url(aioclient_mock, hass, aiohttp_client): async def test_posting_url(hass, aiohttp_client):
"""Test that posting to api endpoint works.""" """Test that posting to api endpoint works."""
await async_setup_component(hass, 'camera', { await async_setup_component(hass, 'camera', {
'camera': { 'camera': {
@ -38,7 +38,7 @@ async def test_posting_url(aioclient_mock, hass, aiohttp_client):
'name': 'config_test', 'name': 'config_test',
}}) }})
client = await async_setup_auth(hass, aiohttp_client) client = await aiohttp_client(hass.http.app)
files = {'image': io.BytesIO(b'fake')} files = {'image': io.BytesIO(b'fake')}
# initial state # initial state

View file

@ -511,8 +511,8 @@ class TestHelpersTemplate(unittest.TestCase):
def test_regex_match(self): def test_regex_match(self):
"""Test regex_match method.""" """Test regex_match method."""
tpl = template.Template(""" tpl = template.Template(r"""
{{ '123-456-7890' | regex_match('(\d{3})-(\d{3})-(\d{4})') }} {{ '123-456-7890' | regex_match('(\\d{3})-(\\d{3})-(\\d{4})') }}
""", self.hass) """, self.hass)
self.assertEqual('True', tpl.render()) self.assertEqual('True', tpl.render())
@ -528,8 +528,8 @@ class TestHelpersTemplate(unittest.TestCase):
def test_regex_search(self): def test_regex_search(self):
"""Test regex_search method.""" """Test regex_search method."""
tpl = template.Template(""" tpl = template.Template(r"""
{{ '123-456-7890' | regex_search('(\d{3})-(\d{3})-(\d{4})') }} {{ '123-456-7890' | regex_search('(\\d{3})-(\\d{3})-(\\d{4})') }}
""", self.hass) """, self.hass)
self.assertEqual('True', tpl.render()) self.assertEqual('True', tpl.render())
@ -545,8 +545,8 @@ class TestHelpersTemplate(unittest.TestCase):
def test_regex_replace(self): def test_regex_replace(self):
"""Test regex_replace method.""" """Test regex_replace method."""
tpl = template.Template(""" tpl = template.Template(r"""
{{ 'Hello World' | regex_replace('(Hello\s)',) }} {{ 'Hello World' | regex_replace('(Hello\\s)',) }}
""", self.hass) """, self.hass)
self.assertEqual('World', tpl.render()) self.assertEqual('World', tpl.render())

View file

@ -12,6 +12,8 @@ from yarl import URL
from aiohttp.client_exceptions import ClientResponseError from aiohttp.client_exceptions import ClientResponseError
from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE
retype = type(re.compile('')) retype = type(re.compile(''))
@ -216,7 +218,18 @@ def mock_aiohttp_client():
"""Context manager to mock aiohttp client.""" """Context manager to mock aiohttp client."""
mocker = AiohttpClientMocker() mocker = AiohttpClientMocker()
def create_session(hass, *args):
session = mocker.create_session(hass.loop)
async def close_session(event):
"""Close session."""
await session.close()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, close_session)
return session
with mock.patch( with mock.patch(
'homeassistant.helpers.aiohttp_client.async_create_clientsession', 'homeassistant.helpers.aiohttp_client.async_create_clientsession',
side_effect=lambda hass, *args: mocker.create_session(hass.loop)): side_effect=create_session):
yield mocker yield mocker