From 523352c97e79d5a3c973541c89d0ec2295671206 Mon Sep 17 00:00:00 2001 From: Joakim Plate Date: Tue, 16 Jan 2024 13:38:47 +0100 Subject: [PATCH] Avoid keeping config dir in path (#107760) --- homeassistant/loader.py | 8 ++++++-- tests/test_loader.py | 11 +++++++++++ tests/testing_config/check_config_not_in_path.py | 1 + 3 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 tests/testing_config/check_config_not_in_path.py diff --git a/homeassistant/loader.py b/homeassistant/loader.py index 0a44ccb05c9..a4f1a862c45 100644 --- a/homeassistant/loader.py +++ b/homeassistant/loader.py @@ -1177,8 +1177,12 @@ def _async_mount_config_dir(hass: HomeAssistant) -> None: Async friendly but not a coroutine. """ - if hass.config.config_dir not in sys.path: - sys.path.insert(0, hass.config.config_dir) + + sys.path.insert(0, hass.config.config_dir) + with suppress(ImportError): + import custom_components # pylint: disable=import-outside-toplevel # noqa: F401 + sys.path.remove(hass.config.config_dir) + sys.path_importer_cache.pop(hass.config.config_dir, None) def _lookup_path(hass: HomeAssistant) -> list[str]: diff --git a/tests/test_loader.py b/tests/test_loader.py index 7959ddb4684..501764bd022 100644 --- a/tests/test_loader.py +++ b/tests/test_loader.py @@ -873,3 +873,14 @@ async def test_async_suggest_report_issue( ) == report_issue ) + + +async def test_config_folder_not_in_path(hass): + """Test that config folder is not in path.""" + + # Verify that we are unable to import this file from top level + with pytest.raises(ImportError): + import check_config_not_in_path # noqa: F401 + + # Verify that we are able to load the file with absolute path + import tests.testing_config.check_config_not_in_path # noqa: F401 diff --git a/tests/testing_config/check_config_not_in_path.py b/tests/testing_config/check_config_not_in_path.py new file mode 100644 index 00000000000..312adec324e --- /dev/null +++ b/tests/testing_config/check_config_not_in_path.py @@ -0,0 +1 @@ +"""File that should not be possible to import via direct import."""