"""Guard the administrator-only image catalog and card-based VM image picker.""" from __future__ import annotations from dataclasses import dataclass from html.parser import HTMLParser from pathlib import Path import re from xml.etree import ElementTree import pytest STATIC = Path(__file__).resolve().parents[1] / "static" VOID_TAGS = { "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", } @dataclass(frozen=True) class Element: tag: str attrs: dict[str, str | None] ancestor_ids: tuple[str, ...] class CatalogPageParser(HTMLParser): def __init__(self) -> None: super().__init__(convert_charrefs=True) self.elements: list[Element] = [] self.stack: list[Element] = [] def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: element = Element( tag, dict(attrs), tuple(item.attrs["id"] for item in self.stack if item.attrs.get("id")), ) self.elements.append(element) if tag not in VOID_TAGS: self.stack.append(element) def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: self.handle_starttag(tag, attrs) if tag not in VOID_TAGS: self.stack.pop() def handle_endtag(self, tag: str) -> None: for index in range(len(self.stack) - 1, -1, -1): if self.stack[index].tag == tag: del self.stack[index:] return @pytest.fixture(scope="module") def page() -> tuple[list[Element], dict[str, Element]]: parser = CatalogPageParser() parser.feed((STATIC / "index.html").read_text(encoding="utf-8")) assert not parser.stack, "Unclosed HTML element in the dashboard page" by_id = {element.attrs["id"]: element for element in parser.elements if element.attrs.get("id")} assert len(by_id) == sum(bool(element.attrs.get("id")) for element in parser.elements) return parser.elements, by_id def test_image_import_is_on_a_dedicated_admin_page(page) -> None: _, by_id = page workspace = by_id["template-workspace"] assert "hidden" in workspace.attrs assert "dashboard-view" in workspace.ancestor_ids form = by_id["template-import-form"] assert form.tag == "form" assert "template-workspace" in form.ancestor_ids for element_id in ("template-name", "template-url", "template-sha256", "template-import-button"): assert "template-import-form" in by_id[element_id].ancestor_ids assert "create-view" not in by_id[element_id].ancestor_ids assert "reinstall-view" not in by_id[element_id].ancestor_ids assert "template-workspace" in by_id["template-admin-list"].ancestor_ids assert "template-import" not in by_id, "The old inline import details must be removed" @pytest.mark.parametrize( ("form_id", "field_id", "catalog_id"), [ ("create-form", "vm-template", "vm-template-catalog"), ("reinstall-form", "reinstall-template", "reinstall-template-catalog"), ], ) def test_vm_image_selection_uses_cards_not_selects( page, form_id: str, field_id: str, catalog_id: str ) -> None: elements, by_id = page field = by_id[field_id] catalog = by_id[catalog_id] assert field.tag == "input" assert field.attrs.get("type") == "hidden" assert field.attrs.get("name") == "template_id" assert form_id in field.ancestor_ids assert catalog.tag == "div" assert "template-catalog" in (catalog.attrs.get("class") or "").split() assert form_id in catalog.ancestor_ids assert not any( element.tag == "select" and element.attrs.get("name") == "template_id" and form_id in element.ancestor_ids for element in elements ) def test_catalog_renders_expandable_family_and_version_cards() -> None: script = (STATIC / "app.js").read_text(encoding="utf-8") assert 'makeElement("details", "template-family-card")' in script assert 'makeElement("button", "template-version-option")' in script assert 'option.dataset.templateId = id;' in script assert 'option.setAttribute("aria-pressed"' in script assert 'input.value = id;' in script @pytest.mark.parametrize( ("family", "filename"), [ ("AlmaLinux", "almalinux-icon.svg"), ("Debian", "debian-icon.svg"), ("CentOS", "centos-icon.svg"), ("Ubuntu", "ubuntu-icon.svg"), ], ) def test_system_cards_use_bundled_vector_logos(family: str, filename: str) -> None: script = (STATIC / "app.js").read_text(encoding="utf-8") logo = STATIC / filename assert logo.is_file() artwork = logo.read_text(encoding="utf-8") root = ElementTree.fromstring(artwork) assert root.tag == "{http://www.w3.org/2000/svg}svg" assert any(element.tag.endswith("}path") for element in root.iter()) assert f'{family}: "/static/{filename}"' in script icon_code = script.split("function templateIcon(family, className) {", 1)[1].split( "function renderTemplateCatalog(inputId) {", 1 )[0] assert "TEMPLATE_ICON_PATHS[family]" in icon_code assert 'makeElement("img", "template-system-logo")' in icon_code assert "logo.src = logoPath;" in icon_code assert 'icon.append(logo);' in icon_code assert 'icon.textContent = "A"' not in icon_code catalog_code = script.split("function renderTemplateCatalog(inputId) {", 1)[1].split( "function renderTemplateAdminList() {", 1 )[0] admin_code = script.split("function renderTemplateAdminList() {", 1)[1].split( "function fillTemplateViews", 1 )[0] assert 'templateIcon(family, "template-family-icon")' in catalog_code assert 'templateIcon(family, "template-admin-icon")' in admin_code def test_system_family_metadata_recognizes_debian_centos_and_ubuntu() -> None: script = (STATIC / "app.js").read_text(encoding="utf-8") names = script.split("const TEMPLATE_FAMILY_NAMES = {", 1)[1].split("};", 1)[0] for metadata, family in ( ("debian", "Debian"), ("centos", "CentOS"), ("centosstream", "CentOS"), ("ubuntu", "Ubuntu"), ): assert f'{metadata}: "{family}"' in names system_code = script.split("function templateSystem(item) {", 1)[1].split( "function templateIcon(family, className) {", 1 )[0] assert "item?.os_family" in system_code assert "TEMPLATE_FAMILY_NAMES[familyKey]" in system_code def test_version_cards_show_only_centered_template_name() -> None: script = (STATIC / "app.js").read_text(encoding="utf-8") catalog_code = script.split("function renderTemplateCatalog(inputId) {", 1)[1].split( "function renderTemplateAdminList() {", 1 )[0] option_code = catalog_code.split('const name = String(item.name || id);', 1)[1].split( 'option.addEventListener("click"', 1 )[0] visible_lines = [ line for line in option_code.splitlines() if "option.append(" in line or "option.textContent" in line ] assert len(visible_lines) == 1 assert 'makeElement("strong", "", name)' in visible_lines[0] assert "versionLabel" not in visible_lines[0] assert 'makeElement("small"' not in visible_lines[0] styles = (STATIC / "styles.css").read_text(encoding="utf-8") version_rules = re.findall(r"\.template-version-option\{([^}]*)\}", styles) text_align = [ match.group(1) for rule in version_rules for match in re.finditer(r"text-align:([^;}]*)", rule) ] assert text_align[-1] == "center" def test_admin_only_catalog_navigation_and_rename_control() -> None: script = (STATIC / "app.js").read_text(encoding="utf-8") session_code = script.split("function applySession(session) {", 1)[1].split( "async function continueAfterLogin", 1 )[0] for element_id in ("template-settings-button", "template-settings-mobile-button"): assert f'"{element_id}"' in session_code assert 'byId(id).hidden = !state.admin;' in session_code rename_code = script.split("function renderTemplateAdminList() {", 1)[1].split( "function fillTemplateViews", 1 )[0] assert 'makeElement("form", "template-admin-row")' in rename_code assert 'name.type = "text";' in rename_code assert 'method: "PATCH"' in rename_code assert 'encodeURIComponent(id)' in rename_code