Convert test fixtures to async (#142052)

This commit is contained in:
Erik Montnemery 2025-04-02 14:05:07 +02:00 committed by GitHub
parent 93162f6b65
commit dfd86d56ec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
24 changed files with 157 additions and 193 deletions

View File

@ -19,18 +19,18 @@ from homeassistant.setup import async_setup_component
@pytest.fixture
def data(hass: HomeAssistant) -> hass_auth.Data:
async def data(hass: HomeAssistant) -> hass_auth.Data:
"""Create a loaded data class."""
data = hass_auth.Data(hass)
hass.loop.run_until_complete(data.async_load())
await data.async_load()
return data
@pytest.fixture
def legacy_data(hass: HomeAssistant) -> hass_auth.Data:
async def legacy_data(hass: HomeAssistant) -> hass_auth.Data:
"""Create a loaded legacy data class."""
data = hass_auth.Data(hass)
hass.loop.run_until_complete(data.async_load())
await data.async_load()
data.is_legacy = True
return data

View File

@ -22,12 +22,12 @@ from tests.typing import ClientSessionGenerator
@pytest.fixture
def mock_api_client(
async def mock_api_client(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> TestClient:
"""Start the Home Assistant HTTP component and return admin API client."""
hass.loop.run_until_complete(async_setup_component(hass, "api", {}))
return hass.loop.run_until_complete(hass_client())
await async_setup_component(hass, "api", {})
return await hass_client()
async def test_api_list_state_entities(

View File

@ -218,9 +218,9 @@ def mock_user_data() -> Generator[MagicMock]:
@pytest.fixture
def mock_cloud_fixture(hass: HomeAssistant) -> CloudPreferences:
async def mock_cloud_fixture(hass: HomeAssistant) -> CloudPreferences:
"""Fixture for cloud component."""
hass.loop.run_until_complete(mock_cloud(hass))
await mock_cloud(hass)
return mock_cloud_prefs(hass, {})

View File

@ -33,21 +33,19 @@ HOME_LONGITUDE = -117.237561
@pytest.fixture(autouse=True)
def setup_zone(hass: HomeAssistant) -> None:
async def setup_zone(hass: HomeAssistant) -> None:
"""Create test zone."""
hass.loop.run_until_complete(
async_setup_component(
hass,
zone.DOMAIN,
{
"zone": {
"name": "test",
"latitude": HOME_LATITUDE,
"longitude": HOME_LONGITUDE,
"radius": 250,
}
},
)
await async_setup_component(
hass,
zone.DOMAIN,
{
"zone": {
"name": "test",
"latitude": HOME_LATITUDE,
"longitude": HOME_LONGITUDE,
"radius": 250,
}
},
)

View File

@ -31,16 +31,16 @@ async def async_set_txt(hass: HomeAssistant, txt: str | None) -> None:
@pytest.fixture
def setup_duckdns(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None:
async def setup_duckdns(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Fixture that sets up DuckDNS."""
aioclient_mock.get(
duckdns.UPDATE_URL, params={"domains": DOMAIN, "token": TOKEN}, text="OK"
)
hass.loop.run_until_complete(
async_setup_component(
hass, duckdns.DOMAIN, {"duckdns": {"domain": DOMAIN, "access_token": TOKEN}}
)
await async_setup_component(
hass, duckdns.DOMAIN, {"duckdns": {"domain": DOMAIN, "access_token": TOKEN}}
)

View File

@ -16,7 +16,9 @@ UPDATE_URL = freedns.UPDATE_URL
@pytest.fixture
def setup_freedns(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None:
async def setup_freedns(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Fixture that sets up FreeDNS."""
params = {}
params[ACCESS_TOKEN] = ""
@ -24,17 +26,15 @@ def setup_freedns(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> N
UPDATE_URL, params=params, text="Successfully updated 1 domains."
)
hass.loop.run_until_complete(
async_setup_component(
hass,
freedns.DOMAIN,
{
freedns.DOMAIN: {
"access_token": ACCESS_TOKEN,
"scan_interval": UPDATE_INTERVAL,
}
},
)
await async_setup_component(
hass,
freedns.DOMAIN,
{
freedns.DOMAIN: {
"access_token": ACCESS_TOKEN,
"scan_interval": UPDATE_INTERVAL,
}
},
)

View File

@ -13,9 +13,9 @@ from tests.typing import WebSocketGenerator
@pytest.fixture(autouse=True)
def setup_frontend(hass: HomeAssistant) -> None:
async def setup_frontend(hass: HomeAssistant) -> None:
"""Fixture to setup the frontend."""
hass.loop.run_until_complete(async_setup_component(hass, "frontend", {}))
await async_setup_component(hass, "frontend", {})
async def test_get_user_data_empty(

View File

@ -29,22 +29,20 @@ def calls(hass: HomeAssistant) -> list[ServiceCall]:
@pytest.fixture(autouse=True)
def setup_comp(hass: HomeAssistant) -> None:
async def setup_comp(hass: HomeAssistant) -> None:
"""Initialize components."""
mock_component(hass, "group")
hass.loop.run_until_complete(
async_setup_component(
hass,
zone.DOMAIN,
{
"zone": {
"name": "test",
"latitude": 32.880837,
"longitude": -117.237561,
"radius": 250,
}
},
)
await async_setup_component(
hass,
zone.DOMAIN,
{
"zone": {
"name": "test",
"latitude": 32.880837,
"longitude": -117.237561,
"radius": 250,
}
},
)

View File

@ -1,6 +1,5 @@
"""The tests for the Google Assistant component."""
from asyncio import AbstractEventLoop
from http import HTTPStatus
import json
from unittest.mock import patch
@ -38,32 +37,28 @@ def auth_header(hass_access_token: str) -> dict[str, str]:
@pytest.fixture
def assistant_client(
event_loop: AbstractEventLoop,
async def assistant_client(
hass: core.HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
) -> TestClient:
"""Create web client for the Google Assistant API."""
loop = event_loop
loop.run_until_complete(
setup.async_setup_component(
hass,
"google_assistant",
{
"google_assistant": {
"project_id": PROJECT_ID,
"entity_config": {
"light.ceiling_lights": {
"aliases": ["top lights", "ceiling lights"],
"name": "Roof Lights",
}
},
}
},
)
await setup.async_setup_component(
hass,
"google_assistant",
{
"google_assistant": {
"project_id": PROJECT_ID,
"entity_config": {
"light.ceiling_lights": {
"aliases": ["top lights", "ceiling lights"],
"name": "Roof Lights",
}
},
}
},
)
return loop.run_until_complete(hass_client_no_auth())
return await hass_client_no_auth()
@pytest.fixture(autouse=True)
@ -87,16 +82,12 @@ async def wanted_platforms_only() -> None:
@pytest.fixture
def hass_fixture(
event_loop: AbstractEventLoop, hass: core.HomeAssistant
) -> core.HomeAssistant:
async def hass_fixture(hass: core.HomeAssistant) -> core.HomeAssistant:
"""Set up a Home Assistant instance for these tests."""
loop = event_loop
# We need to do this to get access to homeassistant/turn_(on,off)
loop.run_until_complete(setup.async_setup_component(hass, core.DOMAIN, {}))
await setup.async_setup_component(hass, core.DOMAIN, {})
loop.run_until_complete(setup.async_setup_component(hass, "demo", {}))
await setup.async_setup_component(hass, "demo", {})
return hass

View File

@ -46,7 +46,7 @@ def hassio_env(supervisor_is_connected: AsyncMock) -> Generator[None]:
@pytest.fixture
def hassio_stubs(
async def hassio_stubs(
hassio_env: None,
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
@ -75,27 +75,27 @@ def hassio_stubs(
"homeassistant.components.hassio.issues.SupervisorIssues.setup",
),
):
hass.loop.run_until_complete(async_setup_component(hass, "hassio", {}))
await async_setup_component(hass, "hassio", {})
return hass_api.call_args[0][1]
@pytest.fixture
def hassio_client(
async def hassio_client(
hassio_stubs: RefreshToken, hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> TestClient:
"""Return a Hass.io HTTP client."""
return hass.loop.run_until_complete(hass_client())
return await hass_client()
@pytest.fixture
def hassio_noauth_client(
async def hassio_noauth_client(
hassio_stubs: RefreshToken,
hass: HomeAssistant,
aiohttp_client: ClientSessionGenerator,
) -> TestClient:
"""Return a Hass.io HTTP client without auth."""
return hass.loop.run_until_complete(aiohttp_client(hass.http.app))
return await aiohttp_client(hass.http.app)
@pytest.fixture

View File

@ -1,6 +1,5 @@
"""Test cors for the HTTP component."""
from asyncio import AbstractEventLoop
from http import HTTPStatus
from pathlib import Path
from unittest.mock import patch
@ -55,14 +54,12 @@ async def mock_handler(request):
@pytest.fixture
def client(
event_loop: AbstractEventLoop, aiohttp_client: ClientSessionGenerator
) -> TestClient:
async def client(aiohttp_client: ClientSessionGenerator) -> TestClient:
"""Fixture to set up a web.Application."""
app = web.Application()
setup_cors(app, [TRUSTED_ORIGIN])
app[KEY_ALLOW_CONFIGURED_CORS](app.router.add_get("/", mock_handler))
return event_loop.run_until_complete(aiohttp_client(app))
return await aiohttp_client(app)
async def test_cors_requests(client) -> None:

View File

@ -1,6 +1,5 @@
"""The tests the for Meraki device tracker."""
from asyncio import AbstractEventLoop
from http import HTTPStatus
import json
@ -22,31 +21,25 @@ from tests.typing import ClientSessionGenerator
@pytest.fixture
def meraki_client(
event_loop: AbstractEventLoop,
async def meraki_client(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
) -> TestClient:
"""Meraki mock client."""
loop = event_loop
assert await async_setup_component(
hass,
device_tracker.DOMAIN,
{
device_tracker.DOMAIN: {
CONF_PLATFORM: "meraki",
CONF_VALIDATOR: "validator",
CONF_SECRET: "secret",
}
},
)
await hass.async_block_till_done()
async def setup_and_wait():
result = await async_setup_component(
hass,
device_tracker.DOMAIN,
{
device_tracker.DOMAIN: {
CONF_PLATFORM: "meraki",
CONF_VALIDATOR: "validator",
CONF_SECRET: "secret",
}
},
)
await hass.async_block_till_done()
return result
assert loop.run_until_complete(setup_and_wait())
return loop.run_until_complete(hass_client())
return await hass_client()
async def test_invalid_or_missing_data(

View File

@ -18,7 +18,7 @@ PASSWORD = "abcdefgh"
@pytest.fixture
def setup_namecheapdns(
async def setup_namecheapdns(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Fixture that sets up NamecheapDNS."""
@ -28,12 +28,10 @@ def setup_namecheapdns(
text="<interface-response><ErrCount>0</ErrCount></interface-response>",
)
hass.loop.run_until_complete(
async_setup_component(
hass,
namecheapdns.DOMAIN,
{"namecheapdns": {"host": HOST, "domain": DOMAIN, "password": PASSWORD}},
)
await async_setup_component(
hass,
namecheapdns.DOMAIN,
{"namecheapdns": {"host": HOST, "domain": DOMAIN, "password": PASSWORD}},
)

View File

@ -22,22 +22,20 @@ USERNAME = "abc@123.com"
@pytest.fixture
def setup_no_ip(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None:
async def setup_no_ip(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None:
"""Fixture that sets up NO-IP."""
aioclient_mock.get(UPDATE_URL, params={"hostname": DOMAIN}, text="good 0.0.0.0")
hass.loop.run_until_complete(
async_setup_component(
hass,
no_ip.DOMAIN,
{
no_ip.DOMAIN: {
"domain": DOMAIN,
"username": USERNAME,
"password": PASSWORD,
}
},
)
await async_setup_component(
hass,
no_ip.DOMAIN,
{
no_ip.DOMAIN: {
"domain": DOMAIN,
"username": USERNAME,
"password": PASSWORD,
}
},
)

View File

@ -36,11 +36,9 @@ from tests.typing import ClientSessionGenerator
@pytest.fixture(autouse=True)
def auth_active(hass: HomeAssistant) -> None:
async def auth_active(hass: HomeAssistant) -> None:
"""Ensure auth is always active."""
hass.loop.run_until_complete(
register_auth_provider(hass, {"type": "homeassistant"})
)
await register_auth_provider(hass, {"type": "homeassistant"})
@pytest.fixture(name="rpi")

View File

@ -291,13 +291,13 @@ BAD_JSON_SUFFIX = "** and it ends here ^^"
@pytest.fixture
def setup_comp(
async def setup_comp(
hass: HomeAssistant,
mock_device_tracker_conf: list[Device],
mqtt_mock: MqttMockHAClient,
) -> None:
"""Initialize components."""
hass.loop.run_until_complete(async_setup_component(hass, "device_tracker", {}))
await async_setup_component(hass, "device_tracker", {})
hass.states.async_set("zone.inner", "zoning", INNER_ZONE)
@ -320,7 +320,7 @@ async def setup_owntracks(
@pytest.fixture
def context(hass: HomeAssistant, setup_comp: None) -> OwnTracksContextFactory:
async def context(hass: HomeAssistant, setup_comp: None) -> OwnTracksContextFactory:
"""Set up the mocked context."""
orig_context = owntracks.OwnTracksContext
context = None
@ -331,16 +331,14 @@ def context(hass: HomeAssistant, setup_comp: None) -> OwnTracksContextFactory:
context = orig_context(*args)
return context
hass.loop.run_until_complete(
setup_owntracks(
hass,
{
CONF_MAX_GPS_ACCURACY: 200,
CONF_WAYPOINT_IMPORT: True,
CONF_WAYPOINT_WHITELIST: ["jon", "greg"],
},
store_context,
)
await setup_owntracks(
hass,
{
CONF_MAX_GPS_ACCURACY: 200,
CONF_WAYPOINT_IMPORT: True,
CONF_WAYPOINT_WHITELIST: ["jon", "greg"],
},
store_context,
)
def get_context():

View File

@ -43,7 +43,7 @@ def mock_dev_track(mock_device_tracker_conf: list[Device]) -> None:
@pytest.fixture
def mock_client(
async def mock_client(
hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator
) -> TestClient:
"""Start the Home Assistant HTTP component."""
@ -54,9 +54,9 @@ def mock_client(
MockConfigEntry(
domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"}
).add_to_hass(hass)
hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {}))
await async_setup_component(hass, "owntracks", {})
return hass.loop.run_until_complete(hass_client_no_auth())
return await hass_client_no_auth()
async def test_handle_valid_message(mock_client) -> None:

View File

@ -31,7 +31,7 @@ def storage_collection(hass: HomeAssistant) -> person.PersonStorageCollection:
@pytest.fixture
def storage_setup(
async def storage_setup(
hass: HomeAssistant, hass_storage: dict[str, Any], hass_admin_user: MockUser
) -> None:
"""Storage setup."""
@ -49,4 +49,4 @@ def storage_setup(
]
},
}
assert hass.loop.run_until_complete(async_setup_component(hass, DOMAIN, {}))
assert await async_setup_component(hass, DOMAIN, {})

View File

@ -1,6 +1,5 @@
"""The tests for the rss_feed_api component."""
from asyncio import AbstractEventLoop
from http import HTTPStatus
from aiohttp.test_utils import TestClient
@ -14,13 +13,11 @@ from tests.typing import ClientSessionGenerator
@pytest.fixture
def mock_http_client(
event_loop: AbstractEventLoop,
async def mock_http_client(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
) -> TestClient:
"""Set up test fixture."""
loop = event_loop
config = {
"rss_feed_template": {
"testfeed": {
@ -35,8 +32,8 @@ def mock_http_client(
}
}
loop.run_until_complete(async_setup_component(hass, "rss_feed_template", config))
return loop.run_until_complete(hass_client())
await async_setup_component(hass, "rss_feed_template", config)
return await hass_client()
async def test_get_nonexistant_feed(mock_http_client) -> None:

View File

@ -94,10 +94,12 @@ SENSOR_OUTPUT = {
@pytest.fixture
def mock_client(hass: HomeAssistant, hass_client: ClientSessionGenerator) -> TestClient:
async def mock_client(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> TestClient:
"""Start the Home Assistant HTTP component."""
with patch("homeassistant.components.spaceapi", return_value=True):
hass.loop.run_until_complete(async_setup_component(hass, "spaceapi", CONFIG))
await async_setup_component(hass, "spaceapi", CONFIG)
hass.states.async_set(
"test.temp1",
@ -126,7 +128,7 @@ def mock_client(hass: HomeAssistant, hass_client: ClientSessionGenerator) -> Tes
"test.hum1", 88, attributes={ATTR_UNIT_OF_MEASUREMENT: PERCENTAGE}
)
return hass.loop.run_until_complete(hass_client())
return await hass_client()
async def test_spaceapi_get(hass: HomeAssistant, mock_client) -> None:

View File

@ -27,12 +27,10 @@ def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None:
@pytest.fixture(autouse=True)
def setup_comp(hass: HomeAssistant) -> None:
async def setup_comp(hass: HomeAssistant) -> None:
"""Initialize components."""
mock_component(hass, "group")
hass.loop.run_until_complete(
async_setup_component(hass, sun.DOMAIN, {sun.DOMAIN: {}})
)
await async_setup_component(hass, sun.DOMAIN, {sun.DOMAIN: {}})
async def test_sunset_trigger(

View File

@ -17,10 +17,12 @@ from tests.typing import ClientSessionGenerator, WebSocketGenerator
@pytest.fixture
def mock_client(hass: HomeAssistant, hass_client: ClientSessionGenerator) -> TestClient:
async def mock_client(
hass: HomeAssistant, hass_client: ClientSessionGenerator
) -> TestClient:
"""Create http client for webhooks."""
hass.loop.run_until_complete(async_setup_component(hass, "webhook", {}))
return hass.loop.run_until_complete(hass_client())
await async_setup_component(hass, "webhook", {})
return await hass_client()
async def test_unregistering_webhook(hass: HomeAssistant, mock_client) -> None:

View File

@ -17,22 +17,20 @@ def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None:
@pytest.fixture(autouse=True)
def setup_comp(hass: HomeAssistant) -> None:
async def setup_comp(hass: HomeAssistant) -> None:
"""Initialize components."""
mock_component(hass, "group")
hass.loop.run_until_complete(
async_setup_component(
hass,
zone.DOMAIN,
{
"zone": {
"name": "test",
"latitude": 32.880837,
"longitude": -117.237561,
"radius": 250,
}
},
)
await async_setup_component(
hass,
zone.DOMAIN,
{
"zone": {
"name": "test",
"latitude": 32.880837,
"longitude": -117.237561,
"radius": 250,
}
},
)

View File

@ -26,12 +26,10 @@ def reset_log_level() -> Generator[None]:
@pytest.fixture
def provider(hass: HomeAssistant) -> hass_auth.HassAuthProvider:
async def provider(hass: HomeAssistant) -> hass_auth.HassAuthProvider:
"""Home Assistant auth provider."""
provider = hass.loop.run_until_complete(
register_auth_provider(hass, {"type": "homeassistant"})
)
hass.loop.run_until_complete(provider.async_initialize())
provider = await register_auth_provider(hass, {"type": "homeassistant"})
await provider.async_initialize()
return provider