Always do thread safety check when writing state (#118886)

* Always do thread safety check when writing state

Refactor the 3 most common places where the thread safety check
for the event loop to be inline to make the check fast enough
that we can keep it long term. While code review catches most
of the thread safety issues in core, some of them still make
it through, and new ones keep getting added. Its not possible
to catch them all with manual code review, so its worth the
tiny overhead to check each time.

Previously the check was limited to custom components
because they were the most common source of thread
safety issues.

* Always do thread safety check when writing state

Refactor the 3 most common places where the thread safety check
for the event loop to be inline to make the check fast enough
that we can keep it long term. While code review catches most
of the thread safety issues in core, some of them still make
it through, and new ones keep getting added. Its not possible
to catch them all with manual code review, so its worth the
tiny overhead to check each time.

Previously the check was limited to custom components
because they were the most common source of thread
safety issues.

* async_fire is more common than expected with ccs

* fix mock

* fix hass mocking
This commit is contained in:
J. Nick Koston 2024-06-05 22:41:55 -05:00 committed by GitHub
parent 64b23419e0
commit 475c20d529
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 34 additions and 33 deletions

View file

@ -2617,13 +2617,12 @@ async def test_async_write_ha_state_thread_safety(hass: HomeAssistant) -> None:
assert not hass.states.get(ent2.entity_id)
async def test_async_write_ha_state_thread_safety_custom_component(
async def test_async_write_ha_state_thread_safety_always(
hass: HomeAssistant,
) -> None:
"""Test async_write_ha_state thread safe for custom components."""
"""Test async_write_ha_state thread safe check."""
ent = entity.Entity()
ent._is_custom_component = True
ent.entity_id = "test.any"
ent.hass = hass
ent.platform = MockEntityPlatform(hass, domain="test")
@ -2631,7 +2630,6 @@ async def test_async_write_ha_state_thread_safety_custom_component(
assert hass.states.get(ent.entity_id)
ent2 = entity.Entity()
ent2._is_custom_component = True
ent2.entity_id = "test.any2"
ent2.hass = hass
ent2.platform = MockEntityPlatform(hass, domain="test")