| 1 | """현재 사용자 설정을 보존하고 실제 패키지 설치와 창 실행을 검증함.""" |
| 2 | |
| 3 | import argparse |
| 4 | from contextlib import contextmanager |
| 5 | import json |
| 6 | import os |
| 7 | from pathlib import Path |
| 8 | import select |
| 9 | import subprocess |
| 10 | import tempfile |
| 11 | import time |
| 12 | import zipfile |
| 13 | |
| 14 | ROOT = Path(__file__).resolve().parents[2] |
| 15 | MIMES = ("application/zip", "application/x-7z-compressed", "application/x-compressed-tar") |
| 16 | CONFIGS = (Path.home() / ".config", Path.home() / ".local/share/applications") |
| 17 | |
| 18 | |
| 19 | def configs(): |
| 20 | return {p: p.read_bytes() for directory in CONFIGS for p in directory.glob("*mimeapps.list")} |
| 21 | |
| 22 | |
| 23 | def work_root(): |
| 24 | common = subprocess.check_output( |
| 25 | ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], cwd=ROOT, text=True |
| 26 | ).strip() |
| 27 | directory = Path(common).resolve() |
| 28 | if directory.name != ".git": |
| 29 | raise RuntimeError("프로젝트 Git 작업 폴더를 찾을 수 없음") |
| 30 | return directory.parent / "tests/work" |
| 31 | |
| 32 | |
| 33 | def selected_work_directory(requested, allowed_work_root): |
| 34 | runs = (requested or allowed_work_root / "ubuntu-package-smoke").resolve() |
| 35 | if runs.parent != allowed_work_root: |
| 36 | raise ValueError("작업 폴더는 프로젝트 tests/work 바로 아래에 있어야 함") |
| 37 | return runs |
| 38 | |
| 39 | |
| 40 | def ensure_no_existing_installation(): |
| 41 | status = subprocess.run( |
| 42 | ["dpkg-query", "-W", "-f=${db:Status-Status}", "zipelo"], |
| 43 | capture_output=True, |
| 44 | ) |
| 45 | if status.stdout == b"installed": |
| 46 | raise RuntimeError("기존 설치를 보존해야 함") |
| 47 | for name in ("/usr/lib/zipelo", "/usr/bin/zipelo", "/usr/share/applications/zipelo.desktop"): |
| 48 | if Path(name).exists(): |
| 49 | raise RuntimeError("기존 파일이 있어 설치를 중단함") |
| 50 | |
| 51 | |
| 52 | def isolated_environment(home): |
| 53 | home = home.resolve() |
| 54 | for directory in (home / ".config", home / ".local/share", home / ".local/state", home / ".cache"): |
| 55 | directory.mkdir(parents=True, exist_ok=True) |
| 56 | return { |
| 57 | **os.environ, |
| 58 | "HOME": str(home), |
| 59 | "XDG_CONFIG_HOME": str(home / ".config"), |
| 60 | "XDG_DATA_HOME": str(home / ".local/share"), |
| 61 | "XDG_STATE_HOME": str(home / ".local/state"), |
| 62 | "XDG_CACHE_HOME": str(home / ".cache"), |
| 63 | "XDG_DATA_DIRS": "/usr/local/share:/usr/share", |
| 64 | } |
| 65 | |
| 66 | |
| 67 | def ensure_host_configs_unchanged(before): |
| 68 | if configs() != before: |
| 69 | raise RuntimeError("실제 사용자 MIME 설정이 시험 중 변경됨") |
| 70 | |
| 71 | |
| 72 | @contextmanager |
| 73 | def installed_package(package, home): |
| 74 | before = configs() |
| 75 | isolated = isolated_environment(home) |
| 76 | package_environment = [ |
| 77 | "sudo", "-n", "env", "SUDO_USER=root", |
| 78 | f"HOME={isolated['HOME']}", |
| 79 | f"XDG_CONFIG_HOME={isolated['XDG_CONFIG_HOME']}", |
| 80 | f"XDG_DATA_HOME={isolated['XDG_DATA_HOME']}", |
| 81 | f"XDG_STATE_HOME={isolated['XDG_STATE_HOME']}", |
| 82 | f"XDG_CACHE_HOME={isolated['XDG_CACHE_HOME']}", |
| 83 | ] |
| 84 | defaults_started = False |
| 85 | failures = [] |
| 86 | try: |
| 87 | subprocess.run([*package_environment, "dpkg", "-i", str(package)], check=True) |
| 88 | ensure_host_configs_unchanged(before) |
| 89 | defaults_started = True |
| 90 | subprocess.run(["/usr/lib/zipelo/default-apps", "install"], env=isolated, check=True) |
| 91 | yield isolated |
| 92 | except BaseException as error: |
| 93 | failures.append(error) |
| 94 | finally: |
| 95 | if defaults_started: |
| 96 | try: |
| 97 | subprocess.run(["/usr/lib/zipelo/default-apps", "remove"], env=isolated, check=True) |
| 98 | except BaseException as error: |
| 99 | failures.append(error) |
| 100 | try: |
| 101 | subprocess.run([*package_environment, "dpkg", "-P", "zipelo"], check=True) |
| 102 | except BaseException as error: |
| 103 | failures.append(error) |
| 104 | try: |
| 105 | ensure_host_configs_unchanged(before) |
| 106 | except BaseException as error: |
| 107 | failures.append(error) |
| 108 | if failures: |
| 109 | raise BaseExceptionGroup("패키지 시험 또는 정리 실패", failures) |
| 110 | |
| 111 | |
| 112 | def ensure_app_running(app): |
| 113 | if app.poll() is not None: |
| 114 | raise RuntimeError("설치된 앱이 조기에 종료됨") |
| 115 | |
| 116 | |
| 117 | def wait_for_window(app, env, timeout=30): |
| 118 | deadline = time.monotonic() + timeout |
| 119 | while True: |
| 120 | ensure_app_running(app) |
| 121 | window = subprocess.run( |
| 122 | ["xdotool", "search", "--all", "--pid", str(app.pid), "--name", "Zipelo"], |
| 123 | env=env, capture_output=True, text=True, |
| 124 | ) |
| 125 | if window.returncode == 0: |
| 126 | return window |
| 127 | if time.monotonic() >= deadline: |
| 128 | raise RuntimeError("앱 창 표시 시간 초과") |
| 129 | time.sleep(0.2) |
| 130 | |
| 131 | |
| 132 | def main(): |
| 133 | parser = argparse.ArgumentParser(description=__doc__) |
| 134 | parser.add_argument("package", type=Path) |
| 135 | parser.add_argument("--work-dir", type=Path) |
| 136 | args = parser.parse_args() |
| 137 | package = args.package.resolve(strict=True) |
| 138 | allowed_work_root = work_root().resolve() |
| 139 | try: |
| 140 | runs = selected_work_directory(args.work_dir, allowed_work_root) |
| 141 | except ValueError as error: |
| 142 | parser.error(str(error)) |
| 143 | runs.mkdir(parents=True, exist_ok=False) |
| 144 | ensure_no_existing_installation() |
| 145 | app = None |
| 146 | display = None |
| 147 | with tempfile.TemporaryDirectory(dir=runs) as temporary_home: |
| 148 | with installed_package(package, Path(temporary_home)) as isolated: |
| 149 | try: |
| 150 | for mime in MIMES: |
| 151 | result = subprocess.check_output( |
| 152 | ["xdg-mime", "query", "default", mime], env=isolated, text=True |
| 153 | ).strip() |
| 154 | assert result == "zipelo.desktop", f"연결 실패: {mime}" |
| 155 | info = json.loads(Path("/usr/lib/zipelo/BUILD-INFO.json").read_text()) |
| 156 | assert info["profile"] == "release" |
| 157 | archive = runs / "sample archive.zip" |
| 158 | with zipfile.ZipFile(archive, "w") as output: |
| 159 | output.writestr("example.txt", "Zipelo package verification") |
| 160 | display = subprocess.Popen( |
| 161 | ["Xvfb", "-displayfd", "1", "-screen", "0", "1280x900x24", "-nolisten", "tcp"], |
| 162 | stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) |
| 163 | assert select.select([display.stdout], [], [], 15)[0], "Xvfb 준비 실패" |
| 164 | number = display.stdout.readline().decode().strip() |
| 165 | assert number.isdecimal() |
| 166 | env = {**isolated, "DISPLAY": ":" + number, "WINIT_UNIX_BACKEND": "x11", "XDG_SESSION_TYPE": "x11"} |
| 167 | env.pop("WAYLAND_DISPLAY", None) |
| 168 | with (runs / "app.stdout").open("wb") as stdout, (runs / "app.stderr").open("wb") as stderr: |
| 169 | app = subprocess.Popen(["/usr/bin/zipelo", str(archive)], env=env, stdout=stdout, stderr=stderr) |
| 170 | window = wait_for_window(app, env) |
| 171 | time.sleep(3) |
| 172 | ensure_app_running(app) |
| 173 | subprocess.run(["import", "-window", window.stdout.splitlines()[0], |
| 174 | str(runs / "installed-window.png")], env=env, check=True) |
| 175 | print("PASS installed package, ZIP/7z/TAR.GZ defaults and native X11 window") |
| 176 | finally: |
| 177 | for process in (app, display): |
| 178 | if process is not None and process.poll() is None: |
| 179 | process.terminate() |
| 180 | try: |
| 181 | process.wait(timeout=10) |
| 182 | except subprocess.TimeoutExpired: |
| 183 | process.kill() |
| 184 | process.wait() |
| 185 | assert not Path("/usr/bin/zipelo").exists() |
| 186 | assert not Path("/usr/lib/zipelo").exists() |
| 187 | print("PASS package removed and host MIME settings unchanged") |
| 188 | |
| 189 | |
| 190 | if __name__ == "__main__": |
| 191 | main() |