diff --git a/.github/workflows/installer_roundtrip.yml b/.github/workflows/installer_roundtrip.yml new file mode 100644 index 0000000..a707655 --- /dev/null +++ b/.github/workflows/installer_roundtrip.yml @@ -0,0 +1,89 @@ +name: Installer round trip + +# Builds a real installer of a small demo app made from this template (tests/smoke/make_demo_app.py: the placeholders filled in, the +# release scripts run as release_constructor.yml runs them, the same constructor environment and build script), installs it silently, +# checks the install, uninstalls it silently and checks what is left (tests/smoke/installer_roundtrip.py). On Windows a second round trip +# keeps a Python of the app running during the uninstall and prints what stays of the folder (diagnosis only). +# It runs on the pull requests that change what an installer is made of, and by hand. It does not run in the apps created from the template. +on: + pull_request: + paths: + - 'app/**' + - 'construct.yaml' + - 'environment.yaml' + - 'setup.py' + - 'requirements*.txt' + - '.tools/bash/**' + - '.tools/python/**' + - '.tools/templates/**' + - 'tests/smoke/**' + - '.github/workflows/installer_roundtrip.yml' + - '.github/workflows/release_constructor.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: installer-roundtrip-${{ github.ref }} + cancel-in-progress: true + +jobs: + roundtrip: + if: github.repository == 'CellMigrationLab/LabConstrictor' + name: Install and uninstall (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 75 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + defaults: + run: + shell: bash -l {0} + env: + CONSTRUCTOR_ENV: constructor-env + DEMO: ${{ github.workspace }}/../demo-app + ARTIFACTS: ${{ github.workspace }}/artifacts + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + + - uses: actions/setup-python@7f4fc3e22c37d6ff65e88745f38bd3157c663f7c # v4 + with: + python-version: '3.11' + + - name: Make the demo app from the template (placeholders filled in, release scripts run) + run: | + pip install -r .tools/requirements.txt pillow==11.3.0 + python tests/smoke/make_demo_app.py "$DEMO" --version 1.2.3 + + - name: Set up Miniconda + uses: conda-incubator/setup-miniconda@fc2d68f6413eb2d87b895e92f8584b5b94a10167 # v3 + with: + auto-activate: true + miniforge-version: latest + use-mamba: true + + - name: Create the constructor environment (the release's script) + run: bash .tools/bash/create_constructor_environment.sh + + - name: Build the installer (the release's script) + working-directory: ${{ env.DEMO }} + env: + OUTPUT_DIR: dist + run: bash .tools/bash/build_installer_with_constructor.sh && ls -la dist + + - name: Install, check, uninstall, check + run: python tests/smoke/installer_roundtrip.py "$DEMO/dist" "${{ runner.temp }}/rt/Demo_App" --logs "$ARTIFACTS" + + - name: 'Windows: uninstall while a Python of the app runs (prints what stays)' + if: runner.os == 'Windows' && !cancelled() + run: python tests/smoke/installer_roundtrip.py "$DEMO/dist" "${{ runner.temp }}/rt/Demo_App_busy" --busy --logs "$ARTIFACTS" + + - name: Upload the logs + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: installer-roundtrip-${{ matrix.os }}-logs + path: artifacts/ + if-no-files-found: ignore diff --git a/tests/smoke/installer_roundtrip.py b/tests/smoke/installer_roundtrip.py new file mode 100644 index 0000000..75f5afe --- /dev/null +++ b/tests/smoke/installer_roundtrip.py @@ -0,0 +1,241 @@ +"""Install and uninstall a real installer of the demo app (tests/smoke/make_demo_app.py), silently, and check what each leaves behind. + +Install (Windows: the .exe with /S /InstallationType=JustMe; Linux and macOS: the .sh with -b -p), then: + * the post-install log ends with "Post-install completed successfully."; + * the tools registry has the app's entry (/apps/Demo App.json): the tools were registered; + * Windows: "Installed apps" lists the app exactly once, under its own name, with the publisher and the version of the release, and + that entry's uninstaller exists. +Uninstall (Windows: Uninstall-Demo_App.exe /S, which hands over to a copy of itself and returns at once, so the folder is watched; +Linux and macOS: the bundled uninstall.sh), then: + * the install folder is gone, the registry entry of the app is gone and the entry of another app is still there (user data is kept); + * Windows: no "Installed apps" entry points to the folder any more. + +--busy (Windows): a Python process started from the install folder runs during the uninstall, as Jupyter, Napari or Fiji's tool worker +may. What stays of the folder is printed (files in use cannot be deleted; the uninstaller marks them for removal at the next restart), and +only the "Installed apps" and registry checks fail the run: this mode diagnoses, it does not decide what the uninstaller should do. + +Usage: python tests/smoke/installer_roundtrip.py INSTALLER_DIR PREFIX [--busy] [--logs DIR] + (PREFIX: a folder that does not exist yet, without spaces; LC_HOME is set to a fresh folder next to it) +""" +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +import time +from pathlib import Path + +APP = "Demo App" +FOLDER = "Demo_App" +OWNER = "CellMigrationLab" +WINDOWS = sys.platform == "win32" +SUCCESS = "Post-install completed successfully." +INSTALL_TIMEOUT = 45 * 60 +UNINSTALL_TIMEOUT = 20 * 60 +UNINSTALL_ROOT = r"Software\Microsoft\Windows\CurrentVersion\Uninstall" + + +def step(message: str) -> None: + print(f"\n=== {message}", flush=True) + + +def ok(message: str) -> None: + print(f"OK {message}", flush=True) + + +def find_installer(folder: Path) -> Path: + pattern = "*.exe" if WINDOWS else "*.sh" + found = sorted(folder.rglob(pattern)) + if len(found) != 1: + raise AssertionError(f"expected one {pattern} installer in {folder}, found {[str(p) for p in found]}") + return found[0] + + +def apps_entries(prefix: Path) -> list[dict[str, str]]: + """Windows: the "Installed apps" entries (HKCU and HKLM) named after the app or whose uninstaller is in the install folder.""" + if sys.platform != "win32": # also tells mypy that winreg is used on Windows only + return [] + import winreg + + found = [] + for hive, hive_name in ((winreg.HKEY_CURRENT_USER, "HKCU"), (winreg.HKEY_LOCAL_MACHINE, "HKLM")): + try: + uninstall = winreg.OpenKey(hive, UNINSTALL_ROOT) + except OSError: + continue + with uninstall: + for index in range(winreg.QueryInfoKey(uninstall)[0]): + name = winreg.EnumKey(uninstall, index) + values: dict[str, str] = {"key": f"{hive_name}\\{name}"} + with winreg.OpenKey(uninstall, name) as key: + for value in ("DisplayName", "DisplayVersion", "Publisher", "UninstallString"): + try: + values[value] = str(winreg.QueryValueEx(key, value)[0]) + except OSError: + values[value] = "" + if name.startswith(FOLDER) or str(prefix).lower() in values["UninstallString"].lower(): + found.append(values) + return found + + +def tail(path: Path, lines: int = 80) -> str: + try: + return "\n".join(path.read_text(encoding="utf-8", errors="replace").splitlines()[-lines:]) + except OSError as exc: + return f"(cannot read {path}: {exc})" + + +def install(installer: Path, prefix: Path, version: str, env: dict[str, str], logs: Path) -> None: + step(f"Install {installer.name} into {prefix}") + if WINDOWS: + # /D must be last and unquoted (NSIS). + command = [str(installer), "/S", "/InstallationType=JustMe", "/RegisterPython=0", "/AddToPath=0", f"/D={prefix}"] + else: + command = ["bash", str(installer), "-b", "-p", str(prefix)] + started = time.monotonic() + result = subprocess.run(command, env=env, timeout=INSTALL_TIMEOUT, check=False) + print(f"installer exit code {result.returncode} after {time.monotonic() - started:.0f} s", flush=True) + log = prefix / "menuinst_debug.log" + if log.is_file(): + shutil.copyfile(log, logs / f"post_install_{'busy' if 'busy' in prefix.name else 'plain'}.log") + if result.returncode != 0: + raise AssertionError(f"the installer failed (exit code {result.returncode}); end of the post-install log:\n{tail(log)}") + text = log.read_text(encoding="utf-8", errors="replace") if log.is_file() else "" + if SUCCESS not in text: + raise AssertionError(f"the post-install log does not say {SUCCESS!r}; its end:\n{tail(log)}") + ok("the post-install script completed") + entry = Path(env["LC_HOME"]) / "apps" / f"{APP}.json" + if not entry.is_file(): + raise AssertionError(f"no registry entry {entry} (the tools were not registered); end of the post-install log:\n{tail(log)}") + data = json.loads(entry.read_text(encoding="utf-8")) + ok(f"registry entry {entry.name}: version {data.get('version')!r}, module {data.get('module')!r}") + if WINDOWS: + check_one_apps_entry(prefix, version) + + +def check_one_apps_entry(prefix: Path, version: str) -> None: + entries = apps_entries(prefix) + for entry in entries: + print(f" Installed apps: {entry}", flush=True) + if len(entries) != 1: + raise AssertionError(f"Installed apps must list the app once, it lists {len(entries)} entries: {entries}") + entry = entries[0] + expected = {"DisplayName": APP, "Publisher": OWNER, "DisplayVersion": version} + wrong = {name: entry[name] for name, value in expected.items() if entry[name] != value} + if wrong: + raise AssertionError(f"the Installed apps entry has {wrong}, expected {expected}") + uninstaller = Path(entry["UninstallString"].strip('"')) + if not uninstaller.is_file(): + raise AssertionError(f"the uninstaller of the Installed apps entry does not exist: {uninstaller}") + ok(f"Installed apps lists {APP!r} once (publisher {OWNER}, version {version}), and its uninstaller exists") + + +def start_busy_process(prefix: Path) -> subprocess.Popen[bytes]: + """A Python of the app that keeps running, as a Jupyter server or a tool worker does.""" + python = prefix / ("python.exe" if WINDOWS else "bin/python") + process = subprocess.Popen([str(python), "-c", "import time; time.sleep(3600)"], cwd=prefix) + time.sleep(5) + if process.poll() is not None: + raise AssertionError(f"the busy process of {python} ended at once (exit code {process.returncode})") + print(f"busy process {process.pid} runs {python}", flush=True) + return process + + +def uninstall(prefix: Path, env: dict[str, str]) -> None: + step(f"Uninstall {prefix}") + started = time.monotonic() + if WINDOWS: + uninstaller = prefix / f"Uninstall-{FOLDER}.exe" + if not uninstaller.is_file(): + raise AssertionError(f"no uninstaller {uninstaller}") + subprocess.run([str(uninstaller), "/S"], env=env, timeout=UNINSTALL_TIMEOUT, check=False) + # The uninstaller copies itself to %TEMP% and returns at once; the copy removes the folder. Wait until it is done. + while time.monotonic() - started < UNINSTALL_TIMEOUT: + if not uninstaller.exists() and not apps_entries(prefix): + break + time.sleep(10) + time.sleep(20) # the last files and the folder itself go after the uninstaller + else: + result = subprocess.run(["bash", str(prefix / "uninstall.sh")], env=env, stdin=subprocess.DEVNULL, timeout=UNINSTALL_TIMEOUT, check=False) + if result.returncode != 0: + raise AssertionError(f"uninstall.sh failed (exit code {result.returncode})") + print(f"uninstall took {time.monotonic() - started:.0f} s", flush=True) + + +def leftovers(prefix: Path) -> list[str]: + if not prefix.exists(): + return [] + files = [p for p in prefix.rglob("*") if p.is_file()] + size = sum(p.stat().st_size for p in files if p.exists()) + top: dict[str, int] = {} + for path in files: + part = path.relative_to(prefix).parts[0] + top[part] = top.get(part, 0) + 1 + lines = [f"{prefix} still holds {len(files)} file(s), {size / 1e6:.1f} MB"] + lines += [f" {name}: {count} file(s)" for name, count in sorted(top.items(), key=lambda item: -item[1])[:25]] + return lines + + +def check_uninstalled(prefix: Path, env: dict[str, str], other: Path, strict_folder: bool) -> None: + left = leftovers(prefix) + for line in left: + print(line, flush=True) + if left and strict_folder: + raise AssertionError(f"the uninstall left the install folder: {left[0]}") + if not left: + ok("the install folder is gone") + entry = Path(env["LC_HOME"]) / "apps" / f"{APP}.json" + if entry.exists(): + raise AssertionError(f"the registry entry of the app is still there: {entry}") + ok("the registry entry of the app is gone") + if not other.is_file(): + raise AssertionError(f"the uninstall removed another app's registry entry: {other}") + ok("another app's registry entry is kept") + if WINDOWS: + entries = apps_entries(prefix) + if entries: + raise AssertionError(f"Installed apps still lists the app after the uninstall: {entries}") + ok("Installed apps no longer lists the app") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("installer_dir", type=Path) + parser.add_argument("prefix", type=Path) + parser.add_argument("--version", default="1.2.3") + parser.add_argument("--busy", action="store_true", help="Windows: a Python of the app runs during the uninstall (diagnosis)") + parser.add_argument("--logs", type=Path, default=Path("artifacts")) + args = parser.parse_args() + prefix: Path = args.prefix.absolute() + if prefix.exists() or " " in str(prefix): + raise SystemExit(f"{prefix}: give a new folder without spaces") + args.logs.mkdir(parents=True, exist_ok=True) + lc_home = prefix.parent / f"{prefix.name}_lc_home" + shutil.rmtree(lc_home, ignore_errors=True) + other = lc_home / "apps" / "Other App.json" + other.parent.mkdir(parents=True) + other.write_text('{"name": "Other App"}\n', encoding="utf-8") + env = {**os.environ, "LC_HOME": str(lc_home)} + + install(find_installer(args.installer_dir), prefix, args.version, env, args.logs) + busy = start_busy_process(prefix) if args.busy else None + try: + uninstall(prefix, env) + check_uninstalled(prefix, env, other, strict_folder=busy is None) + finally: + if busy is not None: + busy.kill() + busy.wait() + time.sleep(5) + step("After the busy process ended") + for line in leftovers(prefix) or [f"{prefix} is gone"]: + print(line, flush=True) + print("\ninstaller round trip: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/smoke/make_demo_app.py b/tests/smoke/make_demo_app.py new file mode 100644 index 0000000..25ea7de --- /dev/null +++ b/tests/smoke/make_demo_app.py @@ -0,0 +1,185 @@ +"""Make a small demo app from the LIVE template, ready for constructor, as an app repository is just before its release build. + +Used by the installer round trip (.github/workflows/installer_roundtrip.yml, tests/smoke/installer_roundtrip.py): the installer built from +this folder is the one a release of an app would build, with the same construct.yaml, post_install / pre_uninstall scripts and release scripts. + +What stands in for the setup form (LabConstrictor_streamlit fills in the placeholders of a new repository): the placeholders are filled in +with the demo values below, the images are drawn here (Pillow), the launcher icons are bundled as the form bundles them, and +app/python_scripts/hide_code_cells.py is made from its template. One notebook +(notebooks/Demo/Demo.ipynb) is added and notebooks/notebook_latest_versions.yaml written, as update_on_notebook_change.yml does. The app has Python code in src/ (package `demoapp`, tools module +`demoapp_lc_tools` with one tool), so the installer installs the package and registers the app for Napari and Fiji. Then the release scripts +run as release_constructor.yml runs them: bump_version.py, bump_constructor.py, bump_Welcome_notebook.py and check_placeholders.py. + +Usage: python tests/smoke/make_demo_app.py DEST [--version 1.2.3] (env: GITHUB_REPOSITORY_OWNER, the publisher of the Windows entry) +""" +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +APP = "Demo App" +FOLDER = "Demo_App" # UNDERSCORED_PROJECT_NAME: the installer's name, Uninstall-Demo_App.exe +PACKAGE = "demoapp" +OWNER = "CellMigrationLab" +REPO = "LabConstrictor-DemoApp" +PYTHON_VERSION = "3.11" +JUPYTERLAB_VERSION = "4.4.0" +LOGO = "app/logo" +# Longest first: a placeholder that contains another one is replaced before it (ICON_IMAGE_PATH before ICON_IMAGE). +PLACEHOLDERS = ( + ("UNDERSCORED_PROJECT_NAME", FOLDER), + ("ICON_ICNS_IMAGE_PATH", f"BASE_PATH_KEYWORD/{APP}/demoapp.icns"), + ("ICON_ICO_IMAGE_PATH", f"BASE_PATH_KEYWORD/{APP}/demoapp.ico"), + ("ICON_IMAGE_PATH", f"BASE_PATH_KEYWORD/{APP}/demoapp.png"), + ("HIDE_CODE_DISABLED", "False"), + ("GITHUB_REPO_NAME", REPO), + ("PYTHON_PROJ_NAME", PACKAGE), + ("LOWER_PROJ_NAME", "demo_app"), + ("PROJECT_NAME", APP), + ("WELCOME_IMAGE", f"{LOGO}/demoapp_banner.png"), + ("HEADER_IMAGE", f"{LOGO}/demoapp_header.png"), + ("ICON_IMAGE", f"{LOGO}/demoapp.png"), + ("VERSION_NUMBER", "0.0.1"), # the initialisation value; bump_version.py writes the release version + ("GITHUB_OWNER", OWNER), + ("PYTHON_VERSION", PYTHON_VERSION), + ("JUPYTERLAB_VERSION", JUPYTERLAB_VERSION), +) +# The files the form fills in (what the installer ships, and the templates the release scripts read); not .tools/python itself. +FILLED_FILES = ("construct.yaml", "setup.py", "environment.yaml", "README.md") +FILLED_FOLDERS = ("app", ".tools/templates") +SKIPPED = {".git", "tests", ".template_sync", "artifacts", "dist", "__pycache__", ".mypy_cache", ".ruff_cache", ".pytest_cache"} +TOOLS_MODULE = ( + "from labconstrictor_tools import Scalars, tool\n\n\n" + '@tool("Double a number")\n' + "def double(x: float = 2.0) -> Scalars:\n" + ' return {"y": x * 2}\n' +) + + +def copy_template(dest: Path) -> None: + def ignore(_folder: str, names: list[str]) -> set[str]: + return {name for name in names if name in SKIPPED} + + shutil.copytree(ROOT, dest, ignore=ignore) + + +def fill(text: str) -> str: + for name, value in PLACEHOLDERS: + text = text.replace(name, value) + return text + + +def fill_files(dest: Path) -> None: + paths = [dest / name for name in FILLED_FILES if (dest / name).is_file()] + for folder in FILLED_FOLDERS: + paths.extend(p for p in (dest / folder).rglob("*") if p.is_file()) + for path in paths: + try: + data = path.read_bytes().decode("utf-8") + except UnicodeDecodeError: + continue # images + new = fill(data) + if new != data: + path.write_bytes(new.encode("utf-8")) + + +def draw_images(dest: Path) -> None: + from PIL import Image, ImageDraw + + logo = dest / LOGO + logo.mkdir(parents=True, exist_ok=True) + + def picture(size: tuple[int, int]) -> Image.Image: + image = Image.new("RGB", size, (32, 96, 160)) + ImageDraw.Draw(image).text((8, 8), "Demo", fill=(255, 255, 255)) + return image + + icon = picture((256, 256)) + icon.save(logo / "demoapp.png") + icon.save(logo / "demoapp.ico", sizes=[(16, 16), (32, 32), (48, 48), (256, 256)]) + icon.save(logo / "demoapp.icns") + picture((164, 314)).save(logo / "demoapp_banner.png") + picture((150, 57)).save(logo / "demoapp_header.png") + + +def add_icons_to_construct(dest: Path) -> None: + """The form bundles the launcher icons next to the app's files (the paths of notebook_launcher.json).""" + path = dest / "construct.yaml" + lines = "".join(f"- {LOGO}/demoapp.{ext}: {APP}/demoapp.{ext}\n" for ext in ("icns", "ico", "png")) + text = path.read_text(encoding="utf-8").replace("extra_files:\n", "extra_files:\n" + lines, 1) + path.write_text(text, encoding="utf-8") + + +def add_package(dest: Path) -> None: + """src/ with more than __init__.py files: bump_constructor.py then bundles setup.py, and the installer installs the package.""" + for relative, body in ( + (f"{PACKAGE}/__init__.py", '"""The demo app."""\n'), + (f"{PACKAGE}/core.py", "def double(x: float) -> float:\n return x * 2\n"), + (f"{PACKAGE}_lc_tools/__init__.py", TOOLS_MODULE), + ): + path = dest / "src" / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(body, encoding="utf-8") + + +NOTEBOOK = { + "cells": [{"cell_type": "code", "execution_count": None, "id": "version", "metadata": {}, "outputs": [], "source": ['current_version = "1.0"\n']}], + "metadata": {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}}, + "nbformat": 4, + "nbformat_minor": 5, +} + + +def add_notebook(dest: Path) -> None: + """One notebook, as an app has; update_on_notebook_change.yml then writes notebooks/notebook_latest_versions.yaml (here: its script).""" + path = dest / "notebooks/Demo/Demo.ipynb" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(NOTEBOOK, indent=1) + "\n", encoding="utf-8") + subprocess.run([sys.executable, ".tools/python/sync_notebook_versions.py"], cwd=dest, check=True) + + +def add_hide_code_cells(dest: Path) -> None: + shutil.copyfile(dest / ".tools/templates/hide_code_cells.py", dest / "app/python_scripts/hide_code_cells.py") + + +def run_release_scripts(dest: Path, version: str) -> None: + env = dict(os.environ) + env.setdefault("GITHUB_REPOSITORY_OWNER", OWNER) + for command in ( + [".tools/python/bump_version.py", version], + [".tools/python/bump_constructor.py"], + [".tools/python/bump_Welcome_notebook.py", OWNER, REPO], + [".tools/python/check_placeholders.py"], + ): + print("+ python " + " ".join(command), flush=True) + subprocess.run([sys.executable, *command], cwd=dest, env=env, check=True) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("dest", type=Path) + parser.add_argument("--version", default="1.2.3") + args = parser.parse_args() + dest: Path = args.dest.resolve() + if dest.exists(): + raise SystemExit(f"{dest} exists; give a new folder") + copy_template(dest) + fill_files(dest) + draw_images(dest) + add_icons_to_construct(dest) + add_package(dest) + add_hide_code_cells(dest) + add_notebook(dest) + run_release_scripts(dest, args.version) + print(f"demo app ready for constructor in {dest}") + return 0 + + +if __name__ == "__main__": + sys.exit(main())