diff --git a/script/gen_integration_paths.py b/script/gen_integration_paths.py index 81080c4b541e..4b740ef726ae 100644 --- a/script/gen_integration_paths.py +++ b/script/gen_integration_paths.py @@ -6,10 +6,15 @@ its (transitive) dependencies. That way a change to a dependency, such as `twilio`, also selects its dependents, `twilio_call` and `twilio_sms`, for testing. +Integrations imported directly from the source are added as well, since +integration platforms, such as `lovelace/cast.py`, are coupled to another +integration without declaring it in the manifest. + Dependencies listed in .core_files.yaml are skipped, as any change to those already triggers the full test suite. """ +from collections.abc import Collection import json from pathlib import Path import re @@ -21,6 +26,12 @@ OUTPUT_FILE = Path(".integration_paths.yaml") CORE_COMPONENT_PATTERN = re.compile( r"^\s*-\s*homeassistant/components/([a-z0-9_]+)/\*\*\s*$", re.MULTILINE ) +# `from homeassistant.components.x import`, `import homeassistant.components.x` +# and `from homeassistant.components import x, y`, the latter also parenthesized +INTEGRATION_IMPORT_PATTERN = re.compile( + r"(?:from|import)\s+homeassistant\.components\.([a-z0-9_]+)" + r"|from\s+homeassistant\.components\s+import\s+\(?([a-z0-9_,\s]+)" +) def get_core_integrations() -> set[str]: @@ -38,6 +49,30 @@ def get_dependencies() -> dict[str, list[str]]: } +def get_imported_integrations( + integrations: Collection[str], +) -> dict[str, set[str]]: + """Return the integrations imported in the source of every integration.""" + imported: dict[str, set[str]] = {} + for integration in integrations: + found: set[str] = set() + for path in sorted((COMPONENTS_DIR / integration).rglob("*.py")): + source = path.read_text() + if "homeassistant.components" not in source: + continue + for match in INTEGRATION_IMPORT_PATTERN.finditer(source): + if module := match.group(1): + found.add(module) + else: + found.update(name.strip() for name in match.group(2).split(",")) + imported[integration] = { + module + for module in found + if module in integrations and module != integration + } + return imported + + def get_transitive_dependencies( dependencies: dict[str, list[str]], ) -> dict[str, set[str]]: @@ -65,6 +100,7 @@ def generate() -> str: core_integrations = get_core_integrations() dependencies = get_dependencies() transitive = get_transitive_dependencies(dependencies) + imported = get_imported_integrations(dependencies.keys()) lines: list[str] = [] for integration, integration_dependencies in transitive.items(): @@ -72,11 +108,14 @@ def generate() -> str: f"homeassistant/components/{integration}/**", f"tests/components/{integration}/**", ] - # Only source changes of a dependency can affect this integration, its - # tests cannot. + # Imports are deliberately not resolved transitively: the import graph + # runs through the hub integrations and would select most of the + # repository. Only source changes can affect this integration, tests + # cannot. + coupled = integration_dependencies | imported[integration] paths.extend( f"homeassistant/components/{dependency}/**" - for dependency in sorted(integration_dependencies - core_integrations) + for dependency in sorted(coupled - core_integrations) ) lines.append(f"{integration}: [{', '.join(paths)}]") return "\n".join(lines) + "\n" diff --git a/tests/scripts/test_gen_integration_paths.py b/tests/scripts/test_gen_integration_paths.py index d09c24917e00..16e998f5ff2f 100644 --- a/tests/scripts/test_gen_integration_paths.py +++ b/tests/scripts/test_gen_integration_paths.py @@ -11,6 +11,7 @@ from script import gen_integration_paths from script.gen_integration_paths import ( generate, get_core_integrations, + get_imported_integrations, get_transitive_dependencies, main, ) @@ -25,24 +26,38 @@ components: &components """ +DEPENDENCIES = { + "cast": [], + "http": [], + "lovelace": [], + "plex": [], + "twilio": ["http"], + "twilio_call": ["twilio"], + "twilio_sms": ["twilio"], +} +SOURCES = { + # An integration platform, coupled without declaring the dependency + "lovelace": "from homeassistant.components.cast.services import ATTR_URL_PATH", + # Imports are not followed transitively, so this must not reach cast + "plex": "from homeassistant.components import lovelace", + # http is in the core files, so it is left out + "twilio": "import homeassistant.components.http", +} + + @pytest.fixture def components_dir(tmp_path: Path) -> Generator[Path]: """Create integrations with a dependency on each other.""" - dependencies = { - "http": [], - "twilio": ["http"], - "twilio_call": ["twilio"], - "twilio_sms": ["twilio"], - } components_dir = tmp_path / "homeassistant" / "components" - for integration, integration_dependencies in dependencies.items(): - manifest_path = components_dir / integration / "manifest.json" - manifest_path.parent.mkdir(parents=True) - manifest_path.write_text( + for integration, integration_dependencies in DEPENDENCIES.items(): + integration_dir = components_dir / integration + integration_dir.mkdir(parents=True) + (integration_dir / "manifest.json").write_text( json.dumps( {"domain": integration, "dependencies": integration_dependencies} ) ) + (integration_dir / "__init__.py").write_text(SOURCES.get(integration, "")) with patch.object(gen_integration_paths, "COMPONENTS_DIR", components_dir): yield components_dir @@ -99,11 +114,76 @@ def test_get_transitive_dependencies( assert get_transitive_dependencies(dependencies) == expected +@pytest.mark.usefixtures("components_dir") +def test_get_imported_integrations() -> None: + """Test that imported integrations are detected.""" + assert get_imported_integrations(DEPENDENCIES) == { + "cast": set(), + "http": set(), + "lovelace": {"cast"}, + "plex": {"lovelace"}, + "twilio": {"http"}, + "twilio_call": set(), + "twilio_sms": set(), + } + + +@pytest.mark.parametrize( + ("source", "expected"), + [ + pytest.param( + "from homeassistant.components.cast import DOMAIN", {"cast"}, id="from" + ), + pytest.param( + "from homeassistant.components.cast.services import ATTR_URL_PATH", + {"cast"}, + id="from-submodule", + ), + pytest.param("import homeassistant.components.cast", {"cast"}, id="import"), + pytest.param( + "from homeassistant.components import cast, plex", + {"cast", "plex"}, + id="from-package", + ), + pytest.param( + "from homeassistant.components import (\n cast,\n plex,\n)", + {"cast", "plex"}, + id="from-package-parenthesized", + ), + pytest.param( + "from homeassistant.components.unknown import DOMAIN", set(), id="unknown" + ), + pytest.param( + "from homeassistant.helpers import device_registry", set(), id="helper" + ), + ], +) +@pytest.mark.usefixtures("core_files") +def test_get_imported_integrations_patterns( + tmp_path: Path, source: str, expected: set[str] +) -> None: + """Test the import patterns that are picked up.""" + components_dir = tmp_path / "homeassistant" / "components" + for integration in ("cast", "lovelace", "plex"): + (components_dir / integration).mkdir(parents=True) + (components_dir / "lovelace" / "__init__.py").write_text(source) + + with patch.object(gen_integration_paths, "COMPONENTS_DIR", components_dir): + imported = get_imported_integrations(["cast", "lovelace", "plex"]) + + assert imported["lovelace"] == expected + + @pytest.mark.usefixtures("components_dir", "core_files") def test_generate() -> None: - """Test that dependencies are added, except the ones triggering a full run.""" + """Test that dependencies and imports are added, except core integrations.""" assert generate() == ( + "cast: [homeassistant/components/cast/**, tests/components/cast/**]\n" "http: [homeassistant/components/http/**, tests/components/http/**]\n" + "lovelace: [homeassistant/components/lovelace/**, " + "tests/components/lovelace/**, homeassistant/components/cast/**]\n" + "plex: [homeassistant/components/plex/**, tests/components/plex/**, " + "homeassistant/components/lovelace/**]\n" "twilio: [homeassistant/components/twilio/**, tests/components/twilio/**]\n" "twilio_call: [homeassistant/components/twilio_call/**, " "tests/components/twilio_call/**, homeassistant/components/twilio/**]\n"