From 5ad71b5e452210ecf2f19f181453ff013eb045f8 Mon Sep 17 00:00:00 2001 From: Ruslan Sayfutdinov Date: Mon, 17 May 2021 20:54:06 +0100 Subject: [PATCH] Define sync hass.create_task function (#50788) --- homeassistant/core.py | 7 +++++++ tests/test_core.py | 23 +++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/homeassistant/core.py b/homeassistant/core.py index 067afb23c8a..b1610faad6e 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -373,6 +373,13 @@ class HomeAssistant: return task + def create_task(self, target: Coroutine) -> None: + """Add task to the executor pool. + + target: target to call. + """ + self.loop.call_soon_threadsafe(self.async_create_task, target) + @callback def async_create_task(self, target: Coroutine) -> asyncio.tasks.Task: """Create a task from within the eventloop. diff --git a/tests/test_core.py b/tests/test_core.py index 0a205cedad1..39c5b310537 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -233,6 +233,29 @@ async def test_async_add_job_pending_tasks_coro(hass): assert len(call_count) == 2 +async def test_async_create_task_pending_tasks_coro(hass): + """Add a coro to pending tasks.""" + call_count = [] + + async def test_coro(): + """Test Coro.""" + call_count.append("call") + + for _ in range(2): + hass.create_task(test_coro()) + + async def wait_finish_callback(): + """Wait until all stuff is scheduled.""" + await asyncio.sleep(0) + await asyncio.sleep(0) + + await wait_finish_callback() + + assert len(hass._pending_tasks) == 2 + await hass.async_block_till_done() + assert len(call_count) == 2 + + async def test_async_add_job_pending_tasks_executor(hass): """Run an executor in pending tasks.""" call_count = []