Add more util aliases to import conventions (#136153)

This commit is contained in:
epenet 2025-01-21 15:58:23 +01:00 committed by GitHub
parent 3b79ded0b0
commit b11b36b523
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
40 changed files with 134 additions and 114 deletions

View File

@ -27,7 +27,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, TemplateError
from homeassistant.helpers import device_registry as dr, intent, llm, template
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import ulid
from homeassistant.util import ulid as ulid_util
from . import AnthropicConfigEntry
from .const import (
@ -164,7 +164,7 @@ class AnthropicConversationEntity(
]
if user_input.conversation_id is None:
conversation_id = ulid.ulid_now()
conversation_id = ulid_util.ulid_now()
messages = []
elif user_input.conversation_id in self.history:
@ -177,8 +177,8 @@ class AnthropicConversationEntity(
# a new conversation was started. If the user picks their own, they
# want to track a conversation and we respect it.
try:
ulid.ulid_to_bytes(user_input.conversation_id)
conversation_id = ulid.ulid_now()
ulid_util.ulid_to_bytes(user_input.conversation_id)
conversation_id = ulid_util.ulid_now()
except ValueError:
conversation_id = user_input.conversation_id

View File

@ -13,7 +13,7 @@ import yarl
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import aiohttp_client, config_validation as cv
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
from .models import Blueprint
from .schemas import BLUEPRINT_SCHEMA, is_blueprint_config
@ -115,7 +115,7 @@ def _extract_blueprint_from_community_topic(
block_content = html.unescape(block_content.strip())
try:
data = yaml.parse_yaml(block_content)
data = yaml_util.parse_yaml(block_content)
except HomeAssistantError:
if block_syntax == "yaml":
raise
@ -167,7 +167,7 @@ async def fetch_blueprint_from_github_url(
resp = await session.get(import_url, raise_for_status=True)
raw_yaml = await resp.text()
data = yaml.parse_yaml(raw_yaml)
data = yaml_util.parse_yaml(raw_yaml)
assert isinstance(data, dict)
blueprint = Blueprint(data, schema=BLUEPRINT_SCHEMA)
@ -204,7 +204,7 @@ async def fetch_blueprint_from_github_gist_url(
continue
content = info["content"]
data = yaml.parse_yaml(content)
data = yaml_util.parse_yaml(content)
if not is_blueprint_config(data):
continue
@ -235,7 +235,7 @@ async def fetch_blueprint_from_website_url(
resp = await session.get(url, raise_for_status=True)
raw_yaml = await resp.text()
data = yaml.parse_yaml(raw_yaml)
data = yaml_util.parse_yaml(raw_yaml)
assert isinstance(data, dict)
blueprint = Blueprint(data, schema=BLUEPRINT_SCHEMA)
@ -252,7 +252,7 @@ async def fetch_blueprint_from_generic_url(
resp = await session.get(url, raise_for_status=True)
raw_yaml = await resp.text()
data = yaml.parse_yaml(raw_yaml)
data = yaml_util.parse_yaml(raw_yaml)
assert isinstance(data, dict)
blueprint = Blueprint(data, schema=BLUEPRINT_SCHEMA)

View File

@ -23,7 +23,7 @@ from homeassistant.const import (
)
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
from .const import (
BLUEPRINT_FOLDER,
@ -79,7 +79,7 @@ class Blueprint:
self.domain = data_domain
missing = yaml.extract_inputs(data) - set(self.inputs)
missing = yaml_util.extract_inputs(data) - set(self.inputs)
if missing:
raise InvalidBlueprint(
@ -117,7 +117,7 @@ class Blueprint:
def yaml(self) -> str:
"""Dump blueprint as YAML."""
return yaml.dump(self.data)
return yaml_util.dump(self.data)
@callback
def validate(self) -> list[str] | None:
@ -179,7 +179,7 @@ class BlueprintInputs:
@callback
def async_substitute(self) -> dict:
"""Get the blueprint value with the inputs substituted."""
processed = yaml.substitute(self.blueprint.data, self.inputs_with_default)
processed = yaml_util.substitute(self.blueprint.data, self.inputs_with_default)
combined = {**processed, **self.config_with_inputs}
# From config_with_inputs
combined.pop(CONF_USE_BLUEPRINT)
@ -225,7 +225,9 @@ class DomainBlueprints:
def _load_blueprint(self, blueprint_path: str) -> Blueprint:
"""Load a blueprint."""
try:
blueprint_data = yaml.load_yaml_dict(self.blueprint_folder / blueprint_path)
blueprint_data = yaml_util.load_yaml_dict(
self.blueprint_folder / blueprint_path
)
except FileNotFoundError as err:
raise FailedToLoad(
self.domain,

View File

@ -13,7 +13,7 @@ from homeassistant.components import websocket_api
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
from . import importer, models
from .const import DOMAIN
@ -174,7 +174,7 @@ async def ws_save_blueprint(
domain = msg["domain"]
try:
yaml_data = cast(dict[str, Any], yaml.parse_yaml(msg["yaml"]))
yaml_data = cast(dict[str, Any], yaml_util.parse_yaml(msg["yaml"]))
blueprint = models.Blueprint(
yaml_data, expected_domain=domain, schema=BLUEPRINT_SCHEMA
)
@ -263,7 +263,7 @@ async def ws_substitute_blueprint(
try:
config = blueprint_inputs.async_substitute()
except yaml.UndefinedSubstitution as err:
except yaml_util.UndefinedSubstitution as err:
connection.send_error(msg["id"], websocket_api.ERR_UNKNOWN_ERROR, str(err))
return

View File

@ -34,7 +34,7 @@ from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import location
from homeassistant.util import location as location_util
from homeassistant.util.unit_conversion import DistanceConverter
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
@ -193,7 +193,7 @@ async def async_setup_platform(
devices = []
for station in network.stations:
dist = location.distance(
dist = location_util.distance(
latitude, longitude, station[ATTR_LATITUDE], station[ATTR_LONGITUDE]
)
station_id = station[ATTR_ID]
@ -236,7 +236,7 @@ class CityBikesNetworks:
for network in self.networks:
network_latitude = network[ATTR_LOCATION][ATTR_LATITUDE]
network_longitude = network[ATTR_LOCATION][ATTR_LONGITUDE]
dist = location.distance(
dist = location_util.distance(
latitude, longitude, network_latitude, network_longitude
)
if minimum_dist is None or dist < minimum_dist:

View File

@ -13,7 +13,7 @@ from homeassistant.components.sensor import async_update_suggested_units
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import check_config, config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.util import location, unit_system
from homeassistant.util import location as location_util, unit_system
@callback
@ -99,7 +99,7 @@ async def websocket_detect_config(
) -> None:
"""Detect core config."""
session = async_get_clientsession(hass)
location_info = await location.async_detect_location_info(session)
location_info = await location_util.async_detect_location_info(session)
info: dict[str, Any] = {}

View File

@ -21,7 +21,7 @@ from homeassistant.core import (
from homeassistant.exceptions import HomeAssistantError, TemplateError
from homeassistant.helpers import intent, llm, template
from homeassistant.helpers.event import async_call_later
from homeassistant.util import dt as dt_util, ulid
from homeassistant.util import dt as dt_util, ulid as ulid_util
from homeassistant.util.hass_dict import HassKey
from .const import DOMAIN
@ -101,7 +101,7 @@ async def async_get_chat_session(
history: ChatSession | None = None
if user_input.conversation_id is None:
conversation_id = ulid.ulid_now()
conversation_id = ulid_util.ulid_now()
elif history := all_history.get(user_input.conversation_id):
conversation_id = user_input.conversation_id
@ -112,8 +112,8 @@ async def async_get_chat_session(
# a new conversation was started. If the user picks their own, they
# want to track a conversation and we respect it.
try:
ulid.ulid_to_bytes(user_input.conversation_id)
conversation_id = ulid.ulid_now()
ulid_util.ulid_to_bytes(user_input.conversation_id)
conversation_id = ulid_util.ulid_now()
except ValueError:
conversation_id = user_input.conversation_id

View File

@ -7,7 +7,7 @@ from dwdwfsapi import DwdWeatherWarningsAPI
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util import location
from homeassistant.util import location as location_util
from .const import (
CONF_REGION_DEVICE_TRACKER,
@ -58,7 +58,7 @@ class DwdWeatherWarningsCoordinator(DataUpdateCoordinator[None]):
distance = None
if self._previous_position is not None:
distance = location.distance(
distance = location_util.distance(
self._previous_position[0],
self._previous_position[1],
position[0],

View File

@ -22,7 +22,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, TemplateError
from homeassistant.helpers import device_registry as dr, intent, llm, template
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import ulid
from homeassistant.util import ulid as ulid_util
from .const import (
CONF_CHAT_MODEL,
@ -204,7 +204,7 @@ class GoogleGenerativeAIConversationEntity(
"""Process a sentence."""
result = conversation.ConversationResult(
response=intent.IntentResponse(language=user_input.language),
conversation_id=user_input.conversation_id or ulid.ulid_now(),
conversation_id=user_input.conversation_id or ulid_util.ulid_now(),
)
assert result.conversation_id

View File

@ -28,7 +28,7 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.hassio import get_supervisor_ip, is_hassio
from homeassistant.util import dt as dt_util, yaml
from homeassistant.util import dt as dt_util, yaml as yaml_util
from .const import KEY_HASS
from .view import HomeAssistantView
@ -244,7 +244,7 @@ class IpBanManager:
str(ip_ban.ip_address): {ATTR_BANNED_AT: ip_ban.banned_at.isoformat()}
}
# Write in a single write call to avoid interleaved writes
out.write("\n" + yaml.dump(ip_))
out.write("\n" + yaml_util.dump(ip_))
async def async_add_ban(self, remote_addr: IPv4Address | IPv6Address) -> None:
"""Add a new IP address to the banned list."""

View File

@ -21,7 +21,7 @@ from homeassistant.helpers import (
device_registry as dr,
intent,
)
from homeassistant.util import ulid
from homeassistant.util import ulid as ulid_util
from .const import TIMER_DATA
@ -261,7 +261,7 @@ class TimerManager:
if seconds is not None:
total_seconds += seconds
timer_id = ulid.ulid_now()
timer_id = ulid_util.ulid_now()
created_at = time.monotonic_ns()
timer = TimerInfo(
id=timer_id,

View File

@ -13,7 +13,7 @@ import logging
from anyio.streams.memory import MemoryObjectSendStream
from mcp import types
from homeassistant.util import ulid
from homeassistant.util import ulid as ulid_util
_LOGGER = logging.getLogger(__name__)
@ -39,7 +39,7 @@ class SessionManager:
@asynccontextmanager
async def create(self, session: Session) -> AsyncGenerator[str]:
"""Context manager to create a new session ID and close when done."""
session_id = ulid.ulid_now()
session_id = ulid_util.ulid_now()
_LOGGER.debug("Creating session: %s", session_id)
self._sessions[session_id] = session
try:

View File

@ -20,7 +20,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, TemplateError
from homeassistant.helpers import intent, llm, template
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import ulid
from homeassistant.util import ulid as ulid_util
from .const import (
CONF_KEEP_ALIVE,
@ -141,7 +141,7 @@ class OllamaConversationEntity(
settings = {**self.entry.data, **self.entry.options}
client = self.hass.data[DOMAIN][self.entry.entry_id]
conversation_id = user_input.conversation_id or ulid.ulid_now()
conversation_id = user_input.conversation_id or ulid_util.ulid_now()
model = settings[CONF_MODEL]
intent_response = intent.IntentResponse(language=user_input.language)
llm_api: llm.APIInstance | None = None

View File

@ -28,7 +28,7 @@ from homeassistant.helpers import config_validation as cv, entity_registry as er
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.json import save_json
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import location
from homeassistant.util import location as location_util
from homeassistant.util.json import JsonObjectType, load_json_object
from .config_flow import PlayStation4FlowHandler # noqa: F401
@ -103,7 +103,9 @@ async def async_migrate_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# Migrate Version 1 -> Version 2: New region codes.
if version == 1:
loc = await location.async_detect_location_info(async_get_clientsession(hass))
loc = await location_util.async_detect_location_info(
async_get_clientsession(hass)
)
if loc:
country = COUNTRYCODE_NAMES.get(loc.country_code)
if country in COUNTRIES:

View File

@ -18,7 +18,7 @@ from homeassistant.const import (
CONF_TOKEN,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.util import location
from homeassistant.util import location as location_util
from .const import (
CONFIG_ENTRY_VERSION,
@ -54,7 +54,7 @@ class PlayStation4FlowHandler(ConfigFlow, domain=DOMAIN):
self.region = None
self.pin: str | None = None
self.m_device = None
self.location: location.LocationInfo | None = None
self.location: location_util.LocationInfo | None = None
self.device_list: list[str] = []
async def async_step_user(
@ -190,7 +190,7 @@ class PlayStation4FlowHandler(ConfigFlow, domain=DOMAIN):
# Try to find region automatically.
if not self.location:
self.location = await location.async_detect_location_info(
self.location = await location_util.async_detect_location_info(
async_get_clientsession(self.hass)
)
if self.location:

View File

@ -21,7 +21,7 @@ from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.network import get_url, is_cloud_connection
from homeassistant.helpers.typing import ConfigType
from homeassistant.loader import bind_hass
from homeassistant.util import network
from homeassistant.util import network as network_util
from homeassistant.util.aiohttp import MockRequest, MockStreamReader, serialize_response
_LOGGER = logging.getLogger(__name__)
@ -174,7 +174,7 @@ async def async_handle_webhook(
_LOGGER.debug("Unable to parse remote ip %s", request.remote)
return Response(status=HTTPStatus.OK)
is_local = network.is_local(request_remote)
is_local = network_util.is_local(request_remote)
if not is_local:
_LOGGER.warning("Received remote request for local webhook %s", webhook_id)

View File

@ -13,7 +13,7 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers import intent
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import ulid
from homeassistant.util import ulid as ulid_util
from .const import DOMAIN
from .data import WyomingService
@ -97,7 +97,7 @@ class WyomingConversationEntity(
self, user_input: conversation.ConversationInput
) -> conversation.ConversationResult:
"""Process a sentence."""
conversation_id = user_input.conversation_id or ulid.ulid_now()
conversation_id = user_input.conversation_id or ulid_util.ulid_now()
intent_response = intent.IntentResponse(language=user_input.language)
try:

View File

@ -25,7 +25,7 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import uuid
from homeassistant.util import uuid as uuid_util
from .const import (
ATTR_MAIN_SYNC,
@ -735,7 +735,7 @@ class MusicCastMediaPlayer(MusicCastDeviceEntity, MediaPlayerEntity):
group = (
self.coordinator.data.group_id
if self.is_server
else uuid.random_uuid_hex().upper()
else uuid_util.random_uuid_hex().upper()
)
ip_addresses = set()

View File

@ -28,7 +28,7 @@ from homeassistant.const import (
)
from homeassistant.core import Context, Event, HomeAssistant, callback, split_entity_id
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
from homeassistant.util.hass_dict import HassKey
from homeassistant.util.json import JsonObjectType
@ -370,7 +370,7 @@ class AssistAPI(API):
prompt.append(
"An overview of the areas and the devices in this smart home:"
)
prompt.append(yaml.dump(list(exposed_entities.values())))
prompt.append(yaml_util.dump(list(exposed_entities.values())))
return "\n".join(prompt)

View File

@ -7,7 +7,7 @@ import logging
from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE
from homeassistant.core import HomeAssistant, State
from homeassistant.util import location as loc_util
from homeassistant.util import location as location_util
_LOGGER = logging.getLogger(__name__)
@ -36,7 +36,7 @@ def closest(latitude: float, longitude: float, states: Iterable[State]) -> State
return min(
with_location,
key=lambda state: loc_util.distance(
key=lambda state: location_util.distance(
state.attributes.get(ATTR_LATITUDE),
state.attributes.get(ATTR_LONGITUDE),
latitude,

View File

@ -74,7 +74,7 @@ from homeassistant.loader import bind_hass
from homeassistant.util import (
convert,
dt as dt_util,
location as loc_util,
location as location_util,
slugify as slugify_util,
)
from homeassistant.util.async_ import run_callback_threadsafe
@ -1858,7 +1858,7 @@ def distance(hass, *args):
return hass.config.distance(*locations[0])
return hass.config.units.length(
loc_util.distance(*locations[0] + locations[1]), UnitOfLength.METERS
location_util.distance(*locations[0] + locations[1]), UnitOfLength.METERS
)

View File

@ -912,7 +912,15 @@ voluptuous = "vol"
"homeassistant.helpers.floor_registry" = "fr"
"homeassistant.helpers.issue_registry" = "ir"
"homeassistant.helpers.label_registry" = "lr"
"homeassistant.util.color" = "color_util"
"homeassistant.util.dt" = "dt_util"
"homeassistant.util.json" = "json_util"
"homeassistant.util.location" = "location_util"
"homeassistant.util.logging" = "logging_util"
"homeassistant.util.network" = "network_util"
"homeassistant.util.ulid" = "ulid_util"
"homeassistant.util.uuid" = "uuid_util"
"homeassistant.util.yaml" = "yaml_util"
[tool.ruff.lint.flake8-pytest-style]
fixture-parentheses = false

View File

@ -16,7 +16,7 @@ from homeassistant.core import Context, HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import intent, llm
from homeassistant.setup import async_setup_component
from homeassistant.util import ulid
from homeassistant.util import ulid as ulid_util
from tests.common import MockConfigEntry
@ -472,7 +472,7 @@ async def test_conversation_id(
assert result.conversation_id == conversation_id
unknown_id = ulid.ulid()
unknown_id = ulid_util.ulid()
result = await conversation.async_converse(
hass, "hello", unknown_id, None, agent_id="conversation.claude"

View File

@ -17,7 +17,7 @@ from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util, yaml
from homeassistant.util import dt as dt_util, yaml as yaml_util
from tests.common import MockConfigEntry, async_fire_time_changed, async_mock_service
@ -38,7 +38,7 @@ def patch_blueprint(
return orig_load(self, path)
return models.Blueprint(
yaml.load_yaml(data_path),
yaml_util.load_yaml(data_path),
expected_domain=self.domain,
path=path,
schema=automation.config.AUTOMATION_BLUEPRINT_SCHEMA,

View File

@ -51,7 +51,7 @@ from homeassistant.helpers.script import (
_async_stop_scripts_at_shutdown,
)
from homeassistant.setup import async_setup_component
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
import homeassistant.util.dt as dt_util
from tests.common import (
@ -1376,7 +1376,9 @@ async def test_reload_automation_when_blueprint_changes(
# Reload the automations without any change, but with updated blueprint
blueprint_path = automation.async_get_blueprints(hass).blueprint_folder
blueprint_config = yaml.load_yaml(blueprint_path / "test_event_service.yaml")
blueprint_config = yaml_util.load_yaml(
blueprint_path / "test_event_service.yaml"
)
blueprint_config["actions"] = [blueprint_config["actions"]]
blueprint_config["actions"].append(blueprint_config["actions"][-1])
@ -1387,7 +1389,7 @@ async def test_reload_automation_when_blueprint_changes(
return_value=config,
),
patch(
"homeassistant.components.blueprint.models.yaml.load_yaml_dict",
"homeassistant.components.blueprint.models.yaml_util.load_yaml_dict",
autospec=True,
return_value=blueprint_config,
),
@ -2691,7 +2693,7 @@ async def test_blueprint_automation_fails_substitution(
"""Test blueprint automation with bad inputs."""
with patch(
"homeassistant.components.blueprint.models.BlueprintInputs.async_substitute",
side_effect=yaml.UndefinedSubstitution("blah"),
side_effect=yaml_util.UndefinedSubstitution("blah"),
):
assert await async_setup_component(
hass,

View File

@ -8,7 +8,7 @@ import pytest
from homeassistant.components.blueprint import BLUEPRINT_SCHEMA, models
from homeassistant.components.blueprint.const import BLUEPRINT_FOLDER
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
DOMAINS = ["automation"]
LOGGER = logging.getLogger(__name__)
@ -25,5 +25,5 @@ def test_default_blueprints(domain: str) -> None:
for fil in items:
LOGGER.info("Processing %s", fil)
assert fil.name.endswith(".yaml")
data = yaml.load_yaml(fil)
data = yaml_util.load_yaml(fil)
models.Blueprint(data, expected_domain=domain, schema=BLUEPRINT_SCHEMA)

View File

@ -13,7 +13,7 @@ from homeassistant.const import STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
from tests.typing import ClientSessionGenerator
@ -223,7 +223,7 @@ async def test_update_automation_config_with_blueprint_substitution_error(
with patch(
"homeassistant.components.blueprint.models.BlueprintInputs.async_substitute",
side_effect=yaml.UndefinedSubstitution("blah"),
side_effect=yaml_util.UndefinedSubstitution("blah"),
):
resp = await client.post(
"/api/config/automation/config/moon",

View File

@ -10,7 +10,7 @@ from homeassistant.components.config import core
from homeassistant.components.websocket_api import TYPE_RESULT
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util, location
from homeassistant.util import dt as dt_util, location as location_util
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
from tests.common import MockUser
@ -238,7 +238,7 @@ async def test_detect_config_fail(hass: HomeAssistant, client) -> None:
"""Test detect config."""
with patch(
"homeassistant.util.location.async_detect_location_info",
return_value=location.LocationInfo(
return_value=location_util.LocationInfo(
ip=None,
country_code=None,
currency=None,

View File

@ -13,7 +13,7 @@ from homeassistant.const import STATE_OFF, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
from tests.typing import ClientSessionGenerator
@ -226,7 +226,7 @@ async def test_update_script_config_with_blueprint_substitution_error(
with patch(
"homeassistant.components.blueprint.models.BlueprintInputs.async_substitute",
side_effect=yaml.UndefinedSubstitution("blah"),
side_effect=yaml_util.UndefinedSubstitution("blah"),
):
resp = await client.post(
"/api/config/script/config/moon",

View File

@ -41,7 +41,7 @@ from homeassistant.data_entry_flow import (
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers.translation import async_get_translations
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
from tests.common import QualityScaleStatus, get_quality_scale
@ -642,7 +642,7 @@ def ignore_translations() -> str | list[str]:
def _get_integration_quality_scale(integration: str) -> dict[str, Any]:
"""Get the quality scale for an integration."""
try:
return yaml.load_yaml_dict(
return yaml_util.load_yaml_dict(
f"homeassistant/components/{integration}/quality_scale.yaml"
).get("rules", {})
except FileNotFoundError:

View File

@ -11,7 +11,7 @@ from homeassistant.components.light import ColorMode
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util import color
from homeassistant.util import color as color_util
from .conftest import create_config_entry
@ -167,10 +167,10 @@ LIGHT_RAW = {
},
"swversion": "66009461",
}
LIGHT_GAMUT = color.GamutType(
color.XYPoint(0.704, 0.296),
color.XYPoint(0.2151, 0.7106),
color.XYPoint(0.138, 0.08),
LIGHT_GAMUT = color_util.GamutType(
color_util.XYPoint(0.704, 0.296),
color_util.XYPoint(0.2151, 0.7106),
color_util.XYPoint(0.138, 0.08),
)
LIGHT_GAMUT_TYPE = "A"
@ -770,7 +770,7 @@ def test_hs_color() -> None:
rooms={},
)
assert light.hs_color == color.color_xy_to_hs(0.4, 0.5, LIGHT_GAMUT)
assert light.hs_color == color_util.color_xy_to_hs(0.4, 0.5, LIGHT_GAMUT)
async def test_group_features(

View File

@ -24,7 +24,7 @@ from homeassistant.const import (
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.util import location
from homeassistant.util import location as location_util
from tests.common import MockConfigEntry
@ -64,7 +64,7 @@ MOCK_TCP_PORT = 997
MOCK_AUTO = {"Config Mode": "Auto Discover"}
MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST}
MOCK_LOCATION = location.LocationInfo(
MOCK_LOCATION = location_util.LocationInfo(
"0.0.0.0",
"US",
"USD",
@ -83,7 +83,8 @@ MOCK_LOCATION = location.LocationInfo(
def location_info_fixture():
"""Mock location info."""
with patch(
"homeassistant.components.ps4.config_flow.location.async_detect_location_info",
"homeassistant.components.ps4."
"config_flow.location_util.async_detect_location_info",
return_value=MOCK_LOCATION,
):
yield
@ -359,7 +360,8 @@ async def test_0_pin(hass: HomeAssistant) -> None:
"pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}]
),
patch(
"homeassistant.components.ps4.config_flow.location.async_detect_location_info",
"homeassistant.components.ps4."
"config_flow.location_util.async_detect_location_info",
return_value=MOCK_LOCATION,
),
):

View File

@ -31,7 +31,7 @@ from homeassistant.data_entry_flow import FlowResultType
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util import location
from homeassistant.util import location as location_util
from tests.common import MockConfigEntry
@ -58,7 +58,7 @@ MOCK_ENTRY_ID = "SomeID"
MOCK_CONFIG = MockConfigEntry(domain=DOMAIN, data=MOCK_DATA, entry_id=MOCK_ENTRY_ID)
MOCK_LOCATION = location.LocationInfo(
MOCK_LOCATION = location_util.LocationInfo(
"0.0.0.0",
"US",
"USD",

View File

@ -18,7 +18,7 @@ from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import Context, HomeAssistant, callback
from homeassistant.helpers import device_registry as dr, template
from homeassistant.setup import async_setup_component
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
from tests.common import MockConfigEntry, async_mock_service
@ -37,7 +37,7 @@ def patch_blueprint(blueprint_path: str, data_path: str) -> Iterator[None]:
return orig_load(self, path)
return Blueprint(
yaml.load_yaml(data_path),
yaml_util.load_yaml(data_path),
expected_domain=self.domain,
path=path,
schema=BLUEPRINT_SCHEMA,

View File

@ -42,7 +42,7 @@ from homeassistant.helpers.script import (
)
from homeassistant.helpers.service import async_get_all_descriptions
from homeassistant.setup import async_setup_component
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
import homeassistant.util.dt as dt_util
from tests.common import (
@ -1722,7 +1722,7 @@ async def test_blueprint_script_fails_substitution(
"""Test blueprint script with bad inputs."""
with patch(
"homeassistant.components.blueprint.models.BlueprintInputs.async_substitute",
side_effect=yaml.UndefinedSubstitution("blah"),
side_effect=yaml_util.UndefinedSubstitution("blah"),
):
assert await async_setup_component(
hass,

View File

@ -19,7 +19,7 @@ from homeassistant.components.template import DOMAIN, SERVICE_RELOAD
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
from tests.common import async_mock_service
@ -40,7 +40,7 @@ def patch_blueprint(
return orig_load(self, path)
return Blueprint(
yaml.load_yaml(data_path),
yaml_util.load_yaml(data_path),
expected_domain=self.domain,
path=path,
schema=BLUEPRINT_SCHEMA,

View File

@ -90,7 +90,7 @@ from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.translation import _TranslationsCacheData
from homeassistant.helpers.typing import ConfigType
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util, location
from homeassistant.util import dt as dt_util, location as location_util
from homeassistant.util.async_ import create_eager_task, get_scheduled_timer_handles
from homeassistant.util.json import json_loads
@ -250,7 +250,9 @@ def check_real[**_P, _R](func: Callable[_P, Coroutine[Any, Any, _R]]):
# Guard a few functions that would make network connections
location.async_detect_location_info = check_real(location.async_detect_location_info)
location_util.async_detect_location_info = check_real(
location_util.async_detect_location_info
)
@pytest.fixture(name="caplog")

View File

@ -7,7 +7,7 @@ import pytest
import voluptuous as vol
from homeassistant.helpers import selector
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
FAKE_UUID = "a266a680b608c32770e6c45bfe6b8411"
@ -77,7 +77,7 @@ def _test_selector(
"selector": {selector_type: selector_instance.config}
}
# Test serialized selector can be dumped to YAML
yaml.dump(selector_instance.serialize())
yaml_util.dump(selector_instance.serialize())
@pytest.mark.parametrize(

View File

@ -15,7 +15,7 @@ import yaml as pyyaml
from homeassistant.config import YAML_CONFIG_FILE, load_yaml_config_file
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
from homeassistant.util.yaml import loader as yaml_loader
from tests.common import extract_stack_to_frame
@ -86,7 +86,7 @@ def test_unhashable_key() -> None:
def test_no_key() -> None:
"""Test item without a key."""
with pytest.raises(HomeAssistantError):
yaml.load_yaml(YAML_CONFIG_FILE)
yaml_util.load_yaml(YAML_CONFIG_FILE)
@pytest.mark.usefixtures("try_both_loaders")
@ -386,13 +386,13 @@ def test_load_yaml_encoding_error(mock_open: Mock) -> None:
@pytest.mark.usefixtures("try_both_dumpers")
def test_dump() -> None:
"""The that the dump method returns empty None values."""
assert yaml.dump({"a": None, "b": "b"}) == "a:\nb: b\n"
assert yaml_util.dump({"a": None, "b": "b"}) == "a:\nb: b\n"
@pytest.mark.usefixtures("try_both_dumpers")
def test_dump_unicode() -> None:
"""The that the dump method returns empty None values."""
assert yaml.dump({"a": None, "b": "привет"}) == "a:\nb: привет\n"
assert yaml_util.dump({"a": None, "b": "привет"}) == "a:\nb: привет\n"
@pytest.mark.parametrize("hass_config_yaml", ['key: [1, "2", 3]'])
@ -400,7 +400,7 @@ def test_dump_unicode() -> None:
def test_representing_yaml_loaded_data() -> None:
"""Test we can represent YAML loaded data."""
data = load_yaml_config_file(YAML_CONFIG_FILE)
assert yaml.dump(data) == "key:\n- 1\n- '2'\n- 3\n"
assert yaml_util.dump(data) == "key:\n- 1\n- '2'\n- 3\n"
@pytest.mark.parametrize("hass_config_yaml", ["key: thing1\nkey: thing2"])
@ -413,7 +413,7 @@ def test_duplicate_key(caplog: pytest.LogCaptureFixture) -> None:
@pytest.mark.parametrize(
"hass_config_yaml_files",
[{YAML_CONFIG_FILE: "key: !secret a", yaml.SECRET_YAML: "a: 1\nb: !secret a"}],
[{YAML_CONFIG_FILE: "key: !secret a", yaml_util.SECRET_YAML: "a: 1\nb: !secret a"}],
)
@pytest.mark.usefixtures("try_both_loaders", "mock_hass_config_yaml")
def test_no_recursive_secrets() -> None:
@ -426,8 +426,8 @@ def test_no_recursive_secrets() -> None:
def test_input_class() -> None:
"""Test input class."""
yaml_input = yaml.Input("hello")
yaml_input2 = yaml.Input("hello")
yaml_input = yaml_util.Input("hello")
yaml_input2 = yaml_util.Input("hello")
assert yaml_input.name == "hello"
assert yaml_input == yaml_input2
@ -438,8 +438,8 @@ def test_input_class() -> None:
@pytest.mark.usefixtures("try_both_loaders", "try_both_dumpers")
def test_input() -> None:
"""Test loading inputs."""
data = {"hello": yaml.Input("test_name")}
assert yaml.parse_yaml(yaml.dump(data)) == data
data = {"hello": yaml_util.Input("test_name")}
assert yaml_util.parse_yaml(yaml_util.dump(data)) == data
@pytest.mark.skipif(
@ -448,7 +448,7 @@ def test_input() -> None:
)
def test_c_loader_is_available_in_ci() -> None:
"""Verify we are testing the C loader in the CI."""
assert yaml.loader.HAS_C_LOADER is True
assert yaml_util.loader.HAS_C_LOADER is True
@pytest.mark.usefixtures("try_both_loaders")
@ -552,7 +552,7 @@ def test_string_used_as_vol_schema() -> None:
@pytest.mark.usefixtures("try_both_loaders", "mock_hass_config_yaml")
def test_load_yaml_dict(expected_data: Any) -> None:
"""Test item without a key."""
assert yaml.load_yaml_dict(YAML_CONFIG_FILE) == expected_data
assert yaml_util.load_yaml_dict(YAML_CONFIG_FILE) == expected_data
@pytest.mark.parametrize("hass_config_yaml", ["abc", "123", "[]"])

View File

@ -8,7 +8,7 @@ import pytest
from homeassistant.config import YAML_CONFIG_FILE, load_yaml_config_file
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util import yaml
from homeassistant.util import yaml as yaml_util
from homeassistant.util.yaml import loader as yaml_loader
from tests.common import get_test_config_dir, patch_yaml_files
@ -63,7 +63,7 @@ def default_config(filepaths: dict[str, Path]) -> YamlFile:
def default_secrets(filepaths: dict[str, Path]) -> YamlFile:
"""Return the default secrets file for testing."""
return YamlFile(
path=filepaths["config"] / yaml.SECRET_YAML,
path=filepaths["config"] / yaml_util.SECRET_YAML,
contents=(
"http_pw: pwhttp\n"
"comp1_un: un1\n"
@ -112,7 +112,8 @@ def test_secret_overrides_parent(
path=filepaths["sub_folder"] / "sub.yaml", contents=default_config.contents
)
sub_secrets = YamlFile(
path=filepaths["sub_folder"] / yaml.SECRET_YAML, contents="http_pw: override"
path=filepaths["sub_folder"] / yaml_util.SECRET_YAML,
contents="http_pw: override",
)
loaded_file = load_config_file(
@ -133,7 +134,7 @@ def test_secrets_from_unrelated_fails(
contents="http:\n api_password: !secret test",
)
unrelated_secrets = YamlFile(
path=filepaths["unrelated"] / yaml.SECRET_YAML, contents="test: failure"
path=filepaths["unrelated"] / yaml_util.SECRET_YAML, contents="test: failure"
)
with pytest.raises(HomeAssistantError, match="Secret test not defined"):
load_config_file(
@ -162,7 +163,8 @@ def test_bad_logger_value(
path=filepaths["config"] / YAML_CONFIG_FILE, contents="api_password: !secret pw"
)
secrets_file = YamlFile(
path=filepaths["config"] / yaml.SECRET_YAML, contents="logger: info\npw: abc"
path=filepaths["config"] / yaml_util.SECRET_YAML,
contents="logger: info\npw: abc",
)
with caplog.at_level(logging.ERROR):
load_config_file(config_file.path, [config_file, secrets_file])
@ -178,7 +180,7 @@ def test_secrets_are_not_dict(
) -> None:
"""Did secrets handle non-dict file."""
non_dict_secrets = YamlFile(
path=filepaths["config"] / yaml.SECRET_YAML,
path=filepaths["config"] / yaml_util.SECRET_YAML,
contents="- http_pw: pwhttp\n comp1_un: un1\n comp1_pw: pw1\n",
)
with pytest.raises(HomeAssistantError, match="Secrets is not a dictionary"):