Remove blueprint from mypy ignore list (#74990)

This commit is contained in:
epenet 2022-07-11 17:46:32 +02:00 committed by GitHub
parent 924dce1b86
commit 63706d2f67
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 24 additions and 30 deletions

View File

@ -13,7 +13,7 @@ from homeassistant.exceptions import HomeAssistantError
class BlueprintException(HomeAssistantError): class BlueprintException(HomeAssistantError):
"""Base exception for blueprint errors.""" """Base exception for blueprint errors."""
def __init__(self, domain: str, msg: str) -> None: def __init__(self, domain: str | None, msg: str) -> None:
"""Initialize a blueprint exception.""" """Initialize a blueprint exception."""
super().__init__(msg) super().__init__(msg)
self.domain = domain self.domain = domain
@ -22,7 +22,9 @@ class BlueprintException(HomeAssistantError):
class BlueprintWithNameException(BlueprintException): class BlueprintWithNameException(BlueprintException):
"""Base exception for blueprint errors.""" """Base exception for blueprint errors."""
def __init__(self, domain: str, blueprint_name: str, msg: str) -> None: def __init__(
self, domain: str | None, blueprint_name: str | None, msg: str
) -> None:
"""Initialize blueprint exception.""" """Initialize blueprint exception."""
super().__init__(domain, msg) super().__init__(domain, msg)
self.blueprint_name = blueprint_name self.blueprint_name = blueprint_name
@ -41,8 +43,8 @@ class InvalidBlueprint(BlueprintWithNameException):
def __init__( def __init__(
self, self,
domain: str, domain: str | None,
blueprint_name: str, blueprint_name: str | None,
blueprint_data: Any, blueprint_data: Any,
msg_or_exc: vol.Invalid, msg_or_exc: vol.Invalid,
) -> None: ) -> None:

View File

@ -91,12 +91,12 @@ def _get_community_post_import_url(url: str) -> str:
def _extract_blueprint_from_community_topic( def _extract_blueprint_from_community_topic(
url: str, url: str,
topic: dict, topic: dict,
) -> ImportedBlueprint | None: ) -> ImportedBlueprint:
"""Extract a blueprint from a community post JSON. """Extract a blueprint from a community post JSON.
Async friendly. Async friendly.
""" """
block_content = None block_content: str
blueprint = None blueprint = None
post = topic["post_stream"]["posts"][0] post = topic["post_stream"]["posts"][0]
@ -118,6 +118,7 @@ def _extract_blueprint_from_community_topic(
if not is_blueprint_config(data): if not is_blueprint_config(data):
continue continue
assert isinstance(data, dict)
blueprint = Blueprint(data) blueprint = Blueprint(data)
break break
@ -134,7 +135,7 @@ def _extract_blueprint_from_community_topic(
async def fetch_blueprint_from_community_post( async def fetch_blueprint_from_community_post(
hass: HomeAssistant, url: str hass: HomeAssistant, url: str
) -> ImportedBlueprint | None: ) -> ImportedBlueprint:
"""Get blueprints from a community post url. """Get blueprints from a community post url.
Method can raise aiohttp client exceptions, vol.Invalid. Method can raise aiohttp client exceptions, vol.Invalid.
@ -160,6 +161,7 @@ async def fetch_blueprint_from_github_url(
resp = await session.get(import_url, raise_for_status=True) resp = await session.get(import_url, raise_for_status=True)
raw_yaml = await resp.text() raw_yaml = await resp.text()
data = yaml.parse_yaml(raw_yaml) data = yaml.parse_yaml(raw_yaml)
assert isinstance(data, dict)
blueprint = Blueprint(data) blueprint = Blueprint(data)
parsed_import_url = yarl.URL(import_url) parsed_import_url = yarl.URL(import_url)
@ -189,7 +191,7 @@ async def fetch_blueprint_from_github_gist_url(
blueprint = None blueprint = None
filename = None filename = None
content = None content: str
for filename, info in gist["files"].items(): for filename, info in gist["files"].items():
if not filename.endswith(".yaml"): if not filename.endswith(".yaml"):
@ -200,6 +202,7 @@ async def fetch_blueprint_from_github_gist_url(
if not is_blueprint_config(data): if not is_blueprint_config(data):
continue continue
assert isinstance(data, dict)
blueprint = Blueprint(data) blueprint = Blueprint(data)
break break

View File

@ -188,7 +188,7 @@ class DomainBlueprints:
self.hass = hass self.hass = hass
self.domain = domain self.domain = domain
self.logger = logger self.logger = logger
self._blueprints = {} self._blueprints: dict[str, Blueprint | None] = {}
self._load_lock = asyncio.Lock() self._load_lock = asyncio.Lock()
hass.data.setdefault(DOMAIN, {})[domain] = self hass.data.setdefault(DOMAIN, {})[domain] = self
@ -216,19 +216,20 @@ class DomainBlueprints:
except HomeAssistantError as err: except HomeAssistantError as err:
raise FailedToLoad(self.domain, blueprint_path, err) from err raise FailedToLoad(self.domain, blueprint_path, err) from err
assert isinstance(blueprint_data, dict)
return Blueprint( return Blueprint(
blueprint_data, expected_domain=self.domain, path=blueprint_path blueprint_data, expected_domain=self.domain, path=blueprint_path
) )
def _load_blueprints(self) -> dict[str, Blueprint | BlueprintException]: def _load_blueprints(self) -> dict[str, Blueprint | BlueprintException | None]:
"""Load all the blueprints.""" """Load all the blueprints."""
blueprint_folder = pathlib.Path( blueprint_folder = pathlib.Path(
self.hass.config.path(BLUEPRINT_FOLDER, self.domain) self.hass.config.path(BLUEPRINT_FOLDER, self.domain)
) )
results = {} results: dict[str, Blueprint | BlueprintException | None] = {}
for blueprint_path in blueprint_folder.glob("**/*.yaml"): for path in blueprint_folder.glob("**/*.yaml"):
blueprint_path = str(blueprint_path.relative_to(blueprint_folder)) blueprint_path = str(path.relative_to(blueprint_folder))
if self._blueprints.get(blueprint_path) is None: if self._blueprints.get(blueprint_path) is None:
try: try:
self._blueprints[blueprint_path] = self._load_blueprint( self._blueprints[blueprint_path] = self._load_blueprint(
@ -245,7 +246,7 @@ class DomainBlueprints:
async def async_get_blueprints( async def async_get_blueprints(
self, self,
) -> dict[str, Blueprint | BlueprintException]: ) -> dict[str, Blueprint | BlueprintException | None]:
"""Get all the blueprints.""" """Get all the blueprints."""
async with self._load_lock: async with self._load_lock:
return await self.hass.async_add_executor_job(self._load_blueprints) return await self.hass.async_add_executor_job(self._load_blueprints)

View File

@ -24,13 +24,13 @@ def async_setup(hass: HomeAssistant):
websocket_api.async_register_command(hass, ws_delete_blueprint) websocket_api.async_register_command(hass, ws_delete_blueprint)
@websocket_api.async_response
@websocket_api.websocket_command( @websocket_api.websocket_command(
{ {
vol.Required("type"): "blueprint/list", vol.Required("type"): "blueprint/list",
vol.Required("domain"): cv.string, vol.Required("domain"): cv.string,
} }
) )
@websocket_api.async_response
async def ws_list_blueprints(hass, connection, msg): async def ws_list_blueprints(hass, connection, msg):
"""List available blueprints.""" """List available blueprints."""
domain_blueprints: dict[str, models.DomainBlueprints] | None = hass.data.get( domain_blueprints: dict[str, models.DomainBlueprints] | None = hass.data.get(
@ -55,13 +55,13 @@ async def ws_list_blueprints(hass, connection, msg):
connection.send_result(msg["id"], results) connection.send_result(msg["id"], results)
@websocket_api.async_response
@websocket_api.websocket_command( @websocket_api.websocket_command(
{ {
vol.Required("type"): "blueprint/import", vol.Required("type"): "blueprint/import",
vol.Required("url"): cv.url, vol.Required("url"): cv.url,
} }
) )
@websocket_api.async_response
async def ws_import_blueprint(hass, connection, msg): async def ws_import_blueprint(hass, connection, msg):
"""Import a blueprint.""" """Import a blueprint."""
async with async_timeout.timeout(10): async with async_timeout.timeout(10):
@ -86,7 +86,6 @@ async def ws_import_blueprint(hass, connection, msg):
) )
@websocket_api.async_response
@websocket_api.websocket_command( @websocket_api.websocket_command(
{ {
vol.Required("type"): "blueprint/save", vol.Required("type"): "blueprint/save",
@ -96,6 +95,7 @@ async def ws_import_blueprint(hass, connection, msg):
vol.Optional("source_url"): cv.url, vol.Optional("source_url"): cv.url,
} }
) )
@websocket_api.async_response
async def ws_save_blueprint(hass, connection, msg): async def ws_save_blueprint(hass, connection, msg):
"""Save a blueprint.""" """Save a blueprint."""
@ -135,7 +135,6 @@ async def ws_save_blueprint(hass, connection, msg):
) )
@websocket_api.async_response
@websocket_api.websocket_command( @websocket_api.websocket_command(
{ {
vol.Required("type"): "blueprint/delete", vol.Required("type"): "blueprint/delete",
@ -143,6 +142,7 @@ async def ws_save_blueprint(hass, connection, msg):
vol.Required("path"): cv.path, vol.Required("path"): cv.path,
} }
) )
@websocket_api.async_response
async def ws_delete_blueprint(hass, connection, msg): async def ws_delete_blueprint(hass, connection, msg):
"""Delete a blueprint.""" """Delete a blueprint."""

View File

@ -2656,15 +2656,6 @@ no_implicit_optional = false
warn_return_any = false warn_return_any = false
warn_unreachable = false warn_unreachable = false
[mypy-homeassistant.components.blueprint.importer]
ignore_errors = true
[mypy-homeassistant.components.blueprint.models]
ignore_errors = true
[mypy-homeassistant.components.blueprint.websocket_api]
ignore_errors = true
[mypy-homeassistant.components.cloud.client] [mypy-homeassistant.components.cloud.client]
ignore_errors = true ignore_errors = true

View File

@ -16,9 +16,6 @@ from .model import Config, Integration
# remove your component from this list to enable type checks. # remove your component from this list to enable type checks.
# Do your best to not add anything new here. # Do your best to not add anything new here.
IGNORED_MODULES: Final[list[str]] = [ IGNORED_MODULES: Final[list[str]] = [
"homeassistant.components.blueprint.importer",
"homeassistant.components.blueprint.models",
"homeassistant.components.blueprint.websocket_api",
"homeassistant.components.cloud.client", "homeassistant.components.cloud.client",
"homeassistant.components.cloud.http_api", "homeassistant.components.cloud.http_api",
"homeassistant.components.conversation", "homeassistant.components.conversation",