async def test_async_add_sensor(): hacs = get_hacs() hacs.hass = HomeAssistant() hacs.hass.config_entries = ConfigEntries(HomeAssistant(), {}) hacs.configuration.config = {"key": "value"} await async_add_sensor() hacs.configuration.config_type = "yaml" await async_add_sensor() # Reset hacs.hass = HomeAssistant()
async def test_extra_stores_theme(): hacs = get_hacs() hacs.hass = HomeAssistant() await async_setup_extra_stores() assert "theme" not in hacs.common.categories hacs.hass.services._services["frontend"] = {"reload_themes": "dummy"} await async_setup_extra_stores() assert "theme" in hacs.common.categories # Reset hacs.hass = HomeAssistant()
async def test_extra_stores_python_script(): hacs = get_hacs() hacs.hass = HomeAssistant() await async_setup_extra_stores() assert "python_script" not in hacs.common.categories hacs.hass.config.components.add("python_script") await async_setup_extra_stores() assert "python_script" in hacs.common.categories hacs.hass.services._services["frontend"] = {"reload_themes": "dummy"} # Reset hacs.hass = HomeAssistant()
def run(args): """Handle ensure config commandline script.""" parser = argparse.ArgumentParser(description=( "Ensure a Home Assistant config exists, creates one if necessary.")) parser.add_argument( "-c", "--config", metavar="path_to_config_dir", default=config_util.get_default_config_dir(), help="Directory that contains the Home Assistant configuration", ) parser.add_argument("--script", choices=["ensure_config"]) args = parser.parse_args() config_dir = os.path.join(os.getcwd(), args.config) # Test if configuration directory exists if not os.path.isdir(config_dir): print("Creating directory", config_dir) os.makedirs(config_dir) hass = HomeAssistant() config_path = hass.loop.run_until_complete(async_run(hass, config_dir)) print("Configuration file:", config_path) return 0
async def test_frontend_debug(): hacs = get_hacs() hacs.hass = HomeAssistant() hacs.configuration = Configuration() hacs.configuration.debug = True await async_serve_frontend() hacs.configuration = Configuration()
async def test_update_repository(): hacs = get_hacs() hacs.hass = HomeAssistant() repository = HacsNetdaemon("test/test") repository.hacs = hacs with pytest.raises(HacsException): await repository.update_repository(True)
def __init__(self): _LOGGER.info("Started") self._data = None self._config_manager = ConfigManager() data = {CONF_HOST: "", CONF_NAME: DEFAULT_NAME} config_entry: ConfigEntry = ConfigEntry( version=0, domain=DOMAIN, title=DEFAULT_NAME, data=data, source="", connection_class="", system_options={}, ) print("1.1") self._config_manager.update(config_entry) print("1.2") self._config_manager.data.file_reader = self.file_data_provider print("1.3") hass = HomeAssistant() print("1.4") self._device_data = HPDeviceData(hass, self._config_manager)
async def test_reload_custom_components(): hacs = get_hacs() hacs.hass = HomeAssistant() hacs.hass.data["custom_components"] = [] repository = HacsIntegration("test/test") repository.hacs = hacs await repository.reload_custom_components()
async def test_hacs(tmpdir): hacs = Hacs() hacs.hass = HomeAssistant() hacs.hass.config.config_dir = tmpdir hacs.repositories = [None] assert hacs.get_by_id(None) is None repo = dummy_repository_base() repo.data.id = "1337" hacs.repositories = [repo] assert hacs.get_by_id("1337").data.full_name == "test/test" assert hacs.get_by_id("1337").data.full_name_lower == "test/test" hacs.repositories = [None] assert hacs.get_by_name(None) is None hacs.repositories = [repo] assert hacs.get_by_name("test/test").data.id == "1337" assert hacs.is_known("1337") hacs.sorted_by_name hacs.sorted_by_repository_name await hacs.prosess_queue() await hacs.clear_out_removed_repositories()
async def test_validate_repository(): hacs = get_hacs() hacs.hass = HomeAssistant() repository = HacsTheme("test/test") repository.hacs = hacs with pytest.raises(HacsException): await repository.validate_repository()
async def async_run(config_dir): """Make sure config exists.""" hass = HomeAssistant() hass.config.config_dir = config_dir path = await config_util.async_ensure_config_exists(hass) await hass.async_stop(force=True) return path
async def test_hacs_data_async_write2(tmpdir): data = HacsData() hacs = get_hacs() hacs.hass = HomeAssistant() hacs.hass.config.config_dir = tmpdir hacs.configuration = Configuration() hacs.system.status.background_task = False hacs.system.disabled = False await data.async_write()
async def test_load(tmpdir): hass = HomeAssistant() hass.config.config_dir = tmpdir.dirname repositories = await async_load_from_store(hass, "repositories") assert repositories["999999"]["name"] == "test1" repositories = await async_load_from_store(hass, "does_not_exist") assert not repositories
async def test_frontend_view_class(): hacs = get_hacs() hacs.hass = HomeAssistant() hacs.configuration = Configuration() frontend = HacsFrontend() await frontend.get({}, "test") await frontend.get({}, "class-map.js.map") await frontend.get({}, "frontend-test") await frontend.get({}, "iconset.js")
async def test_get_package_content(): hacs = get_hacs() hacs.hass = HomeAssistant() repository = HacsPlugin("test/test") repository.hacs = hacs await repository.get_package_content() repository.repository_object = MockRepositoryObject() await repository.get_package_content()
async def test_clear_storage(tmpdir): hacs = get_hacs() hacs.hass = HomeAssistant() hacs.system.config_path = tmpdir.dirname os.makedirs(f"{hacs.system.config_path}/.storage") with open(f"{hacs.system.config_path}/.storage/hacs", "w") as h_f: h_f.write("") await async_clear_storage() os.makedirs(f"{hacs.system.config_path}/.storage/hacs") await async_clear_storage()
def get_ha_config(): """ Duplicate enough of the HA startup sequence to extract the config *really* early. """ args = get_arguments() hass = HomeAssistant() hass.config.config_dir = os.path.abspath(os.path.join(os.getcwd(), args.config)) return load_yaml_config_file(hass.config.path(YAML_CONFIG_FILE))
async def test_hacs_data_async_write1(tmpdir): data = HacsData() hacs = get_hacs() repository = dummy_repository_base() repository.data.installed = True repository.data.installed_version = "1" hacs.repositories = [repository] hacs.hass = HomeAssistant() hacs.hass.config.config_dir = tmpdir hacs.configuration = Configuration() await data.async_write()
async def test_async_post_installation(): hacs = get_hacs() hacs.hass = HomeAssistant() repository = HacsIntegration("test/test") repository.hacs = hacs await repository.async_post_installation() repository.data.config_flow = True repository.data.first_install = True hacs.hass.data["custom_components"] = [] await repository.async_post_installation()
async def test_frontend_setup(tmpdir): hacs = get_hacs() hacs.system.config_path = tmpdir hacs.hass = HomeAssistant() hacs.hass.components = MockComponents() hacs.hass.http = MockHTTP() content = {} os.makedirs(f"{hacs.system.config_path}/custom_components/hacs", exist_ok=True) with open( f"{hacs.system.config_path}/custom_components/hacs/manifest.json", "w") as manifest: manifest.write(json.dumps(content)) await async_setup_frontend() # Reset hacs.hass = HomeAssistant()
async def validate_repository(repository, category, ref=None): """Validate.""" async with aiohttp.ClientSession() as session: hacs = get_hacs() hacs.hass = HomeAssistant() hacs.session = session hacs.configuration = Configuration() hacs.configuration.token = TOKEN hacs.github = GitHub(hacs.configuration.token, hacs.session) try: await register_repository(repository, category, ref=ref) except HacsException as exception: error(exception)
def run(args: List) -> int: """Run a script.""" scripts = [] path = os.path.dirname(__file__) for fil in os.listdir(path): if fil == '__pycache__': continue elif os.path.isdir(os.path.join(path, fil)): scripts.append(fil) elif fil != '__init__.py' and fil.endswith('.py'): scripts.append(fil[:-3]) if not args: print('Please specify a script to run.') print('Available scripts:', ', '.join(scripts)) return 1 if args[0] not in scripts: print('Invalid script specified.') print('Available scripts:', ', '.join(scripts)) return 1 script = importlib.import_module('homeassistant.scripts.' + args[0]) config_dir = extract_config_dir() loop = asyncio.get_event_loop() if not is_virtual_env(): loop.run_until_complete(async_mount_local_lib_path(config_dir)) _pip_kwargs = pip_kwargs(config_dir) logging.basicConfig(stream=sys.stdout, level=logging.INFO) hass = HomeAssistant(loop) pkgload = PackageLoadable(hass) for req in getattr(script, 'REQUIREMENTS', []): try: loop.run_until_complete(pkgload.loadable(req)) continue except ImportError: pass returncode = install_package(req, **_pip_kwargs) if not returncode: print('Aborting script, could not install dependency', req) return 1 return script.run(args[1:]) # type: ignore
def dummy_repository_base(repository=None): if repository is None: repository = HacsRepository() repository.hacs.hass = HomeAssistant() repository.hacs.hass.data = {"custom_components": []} repository.logger = Logger("hacs.test.test") repository.data.full_name = "test/test" repository.versions.available = "3" repository.status.selected_tag = "3" repository.ref = version_to_install(repository) repository.integration_manifest = {"config_flow": False, "domain": "test"} repository.releases.published_tags = ["1", "2", "3"] repository.data.update_data(repository_data) return repository
async def test_frontend_repo(tmpdir): hacs = get_hacs() hacs.hass = HomeAssistant() hacs.configuration = Configuration() hacs.configuration.frontend_repo = tmpdir await async_serve_frontend() os.makedirs(f"{tmpdir}/hacs_frontend", exist_ok=True) with open(f"{tmpdir}/hacs_frontend/main.js", "w") as target: target.write("") await async_serve_frontend() hacs.configuration = Configuration()
async def run_command(args): """Run the command.""" hass = HomeAssistant() hass.config.config_dir = os.path.join(os.getcwd(), args.config) hass.auth = await auth_manager_from_config(hass, [{ "type": "homeassistant" }], []) provider = hass.auth.auth_providers[0] await provider.async_initialize() await args.func(hass, provider, args) # Triggers save on used storage helpers with delay (core auth) logging.getLogger("homeassistant.core").setLevel(logging.WARNING) await hass.async_stop()
async def test_categpry(tmpdir): hacs = get_hacs() hacs.system.config_path = tmpdir hacs.hass = HomeAssistant() await async_serve_category_file("test") await async_serve_category_file("themes/test") await async_serve_category_file(None) os.makedirs(f"{tmpdir}", exist_ok=True) os.makedirs(f"{tmpdir}/www/community", exist_ok=True) with open(f"{tmpdir}/test.gz", "w") as test: test.write("") with open(f"{tmpdir}/www/community/test.gz", "w") as test: test.write("") await async_serve_category_file("test")
def dummy_repository_base(repository=None): if repository is None: repository = HacsRepository() repository.hacs.hass = HomeAssistant() repository.hacs.hass.data = {"custom_components": []} repository.hacs.system.config_path = tempfile.gettempdir() repository.logger = getLogger("test.test") repository.data.full_name = "test/test" repository.data.domain = "test" repository.data.last_version = "3" repository.data.selected_tag = "3" repository.ref = version_to_install(repository) repository.integration_manifest = {"config_flow": False, "domain": "test"} repository.data.published_tags = ["1", "2", "3"] repository.data.update_data(repository_data) return repository
async def validate_repository(repository, category, ref=None): """Validate.""" async with aiohttp.ClientSession() as session: hacs = get_hacs() hacs.hass = HomeAssistant() hacs.session = session hacs.configuration = Configuration() hacs.configuration.token = TOKEN hacs.core.config_path = None hacs.github = GitHub(hacs.configuration.token, hacs.session) print( "::warning::Use hacs/integration/action@main instead of hacs/integration/action@master" ) try: await register_repository(repository, category, ref=ref) except HacsException as exception: error(exception)
async def test_frontend_frontend_repo_url(aresponses, event_loop): aresponses.add( "127.0.0.1", "/main.js", "get", "", ) hacs = get_hacs() hacs.hass = HomeAssistant() hacs.configuration = Configuration() hacs.configuration.frontend_repo_url = "http://127.0.0.1" await async_serve_frontend() async with aiohttp.ClientSession(loop=event_loop) as session: hacs.session = session await async_serve_frontend() hacs.configuration = Configuration()
async def test_check_local_path(tmpdir): hacs = get_hacs() connection = MockConnection() hacs.hass = HomeAssistant() os.makedirs(tmpdir, exist_ok=True) check_local_path(hacs.hass, connection, {"path": tmpdir, "id": 1}) check_local_path(hacs.hass, connection, {"id": 1}) get_critical_repositories(hacs.hass, connection, {"id": 1}) hacs_config(hacs.hass, connection, {"id": 1}) hacs_removed(hacs.hass, connection, {"id": 1}) hacs_repositories(hacs.hass, connection, {"id": 1}) hacs_repository(hacs.hass, connection, {"id": 1}) hacs_repository_data(hacs.hass, connection, {"id": 1}) hacs_settings(hacs.hass, connection, {"id": 1}) hacs_status(hacs.hass, connection, {"id": 1}) acknowledge_critical_repository(hacs.hass, connection, { "repository": "test/test", "id": 1 })