| 1 | """기본 앱 보존과 설치 실패 정리를 격리 검증함.""" |
| 2 | |
| 3 | import importlib.util |
| 4 | import os |
| 5 | import re |
| 6 | from pathlib import Path |
| 7 | import subprocess |
| 8 | import sys |
| 9 | import tempfile |
| 10 | import unittest |
| 11 | from unittest.mock import patch |
| 12 | |
| 13 | ROOT = Path(__file__).resolve().parents[2] |
| 14 | SPEC = importlib.util.spec_from_file_location("ubuntu_smoke", Path(__file__).with_name("ubuntu_smoke.py")) |
| 15 | SMOKE = importlib.util.module_from_spec(SPEC) |
| 16 | SPEC.loader.exec_module(SMOKE) |
| 17 | |
| 18 | |
| 19 | def test_work_root(): |
| 20 | job = os.environ.get("ZIPELO_CI_JOB", "rust-local") |
| 21 | if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}", job): |
| 22 | raise ValueError("안전한 작업명이 필요함") |
| 23 | return SMOKE.work_root() / job / "tmp" |
| 24 | |
| 25 | |
| 26 | class LifecycleTests(unittest.TestCase): |
| 27 | def setUp(self): |
| 28 | work = test_work_root() |
| 29 | work.mkdir(parents=True, exist_ok=True) |
| 30 | temporary = tempfile.TemporaryDirectory(dir=work) |
| 31 | self.addCleanup(temporary.cleanup) |
| 32 | self.directory = Path(temporary.name) |
| 33 | self.previous = self.directory / "mimeapps.list" |
| 34 | self.previous.write_bytes(b"previous-app.desktop\n") |
| 35 | self.created = self.directory / "added-mimeapps.list" |
| 36 | self.original = {self.previous: self.previous.read_bytes()} |
| 37 | settings = patch.object(SMOKE, "CONFIGS", (self.directory,)) |
| 38 | settings.start() |
| 39 | self.addCleanup(settings.stop) |
| 40 | |
| 41 | def test_default_work_path_uses_common_job_directory(self): |
| 42 | with patch.dict(os.environ, {"ZIPELO_CI_JOB": "lifecycle-regression"}): |
| 43 | os.environ.pop("TMPDIR", None) |
| 44 | os.environ.pop("ZIPELO_TEST_WORK_DIR", None) |
| 45 | self.assertEqual( |
| 46 | test_work_root(), SMOKE.work_root() / "lifecycle-regression/tmp" |
| 47 | ) |
| 48 | |
| 49 | def test_work_directory_rejects_nested_checkout_paths(self): |
| 50 | allowed = SMOKE.work_root().resolve() |
| 51 | self.assertEqual(SMOKE.selected_work_directory(None, allowed), |
| 52 | allowed / "ubuntu-package-smoke") |
| 53 | self.assertEqual(SMOKE.selected_work_directory(allowed / "custom", allowed), |
| 54 | allowed / "custom") |
| 55 | for requested in (allowed, allowed / "review/r/tests/work/nested", |
| 56 | allowed / "review/r/tests/work", allowed.parent / "outside"): |
| 57 | with self.subTest(requested=requested), self.assertRaisesRegex( |
| 58 | ValueError, "바로 아래" |
| 59 | ): |
| 60 | SMOKE.selected_work_directory(requested, allowed) |
| 61 | |
| 62 | def test_readme_commands_use_checkout_and_common_work_root(self): |
| 63 | readme = (ROOT / "tests/release-packages/README.md").read_text() |
| 64 | commands = readme.split("```sh\n", 1)[1].split("\n```", 1)[0] |
| 65 | result = subprocess.run( |
| 66 | ["bash", "-c", 'python3() { printf "<%s>\n" "$@"; }; ' + commands], |
| 67 | cwd=ROOT / "tests/release-packages", check=True, capture_output=True, text=True, |
| 68 | ) |
| 69 | output = result.stdout |
| 70 | self.assertIn(str(ROOT / "tests/ci/run_rust.py"), output) |
| 71 | self.assertIn(str(ROOT / "tests/release-packages/ubuntu_smoke.py"), output) |
| 72 | self.assertIn(str(SMOKE.work_root() / "v021-build-out/zipelo_0.2.1_amd64.deb"), |
| 73 | output) |
| 74 | self.assertIn(str(SMOKE.work_root() / "ubuntu-package-smoke"), output) |
| 75 | |
| 76 | def test_existing_installation_is_blocked_with_python_optimization(self): |
| 77 | script = """import importlib.util |
| 78 | import subprocess |
| 79 | import sys |
| 80 | from unittest.mock import patch |
| 81 | |
| 82 | spec = importlib.util.spec_from_file_location("ubuntu_smoke", sys.argv[1]) |
| 83 | module = importlib.util.module_from_spec(spec) |
| 84 | spec.loader.exec_module(module) |
| 85 | with patch.object(module.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, b"installed")): |
| 86 | try: |
| 87 | module.ensure_no_existing_installation() |
| 88 | except RuntimeError: |
| 89 | print("blocked") |
| 90 | else: |
| 91 | raise SystemExit("기존 설치를 통과시킴") |
| 92 | """ |
| 93 | environment = dict(os.environ, PYTHONDONTWRITEBYTECODE="1") |
| 94 | result = subprocess.run( |
| 95 | [sys.executable, "-O", "-c", script, str(SMOKE.ROOT / "tests/release-packages/ubuntu_smoke.py")], |
| 96 | env=environment, cwd=ROOT, capture_output=True, text=True, |
| 97 | ) |
| 98 | self.assertEqual(result.returncode, 0, result.stderr) |
| 99 | self.assertEqual(result.stdout.strip(), "blocked") |
| 100 | |
| 101 | def test_window_guards_stay_active_with_python_optimization(self): |
| 102 | script = """import importlib.util |
| 103 | import subprocess |
| 104 | import sys |
| 105 | from unittest.mock import Mock, patch |
| 106 | |
| 107 | spec = importlib.util.spec_from_file_location("ubuntu_smoke", sys.argv[1]) |
| 108 | module = importlib.util.module_from_spec(spec) |
| 109 | spec.loader.exec_module(module) |
| 110 | app = Mock(pid=123) |
| 111 | app.poll.return_value = 1 |
| 112 | with patch.object(module.subprocess, "run") as search: |
| 113 | try: |
| 114 | module.wait_for_window(app, {}, timeout=0.5) |
| 115 | except RuntimeError as error: |
| 116 | if "조기에 종료" not in str(error): |
| 117 | raise |
| 118 | else: |
| 119 | raise SystemExit("종료된 앱을 통과시킴") |
| 120 | search.assert_not_called() |
| 121 | app.poll.return_value = None |
| 122 | with patch.object(module.subprocess, "run", return_value=subprocess.CompletedProcess([], 1)): |
| 123 | with patch.object(module.time, "monotonic", side_effect=[0, 1]): |
| 124 | with patch.object(module.time, "sleep") as sleep: |
| 125 | try: |
| 126 | module.wait_for_window(app, {}, timeout=0.5) |
| 127 | except RuntimeError as error: |
| 128 | if "시간 초과" not in str(error): |
| 129 | raise |
| 130 | else: |
| 131 | raise SystemExit("창 탐색 제한 시간을 통과시킴") |
| 132 | sleep.assert_not_called() |
| 133 | print("guards active") |
| 134 | """ |
| 135 | result = subprocess.run( |
| 136 | [sys.executable, "-B", "-O", "-c", script, str(SMOKE.ROOT / "tests/release-packages/ubuntu_smoke.py")], |
| 137 | env=dict(os.environ, PYTHONDONTWRITEBYTECODE="1"), cwd=ROOT, |
| 138 | capture_output=True, text=True, timeout=10, |
| 139 | ) |
| 140 | self.assertEqual(result.returncode, 0, result.stderr) |
| 141 | self.assertEqual(result.stdout.strip(), "guards active") |
| 142 | |
| 143 | def test_existing_installation_files_are_blocked(self): |
| 144 | with ( |
| 145 | patch.object(SMOKE.subprocess, "run", return_value=subprocess.CompletedProcess([], 1, b"")), |
| 146 | patch.object(SMOKE.Path, "exists", return_value=True), |
| 147 | ): |
| 148 | with self.assertRaisesRegex(RuntimeError, "기존 파일"): |
| 149 | SMOKE.ensure_no_existing_installation() |
| 150 | |
| 151 | def test_only_first_configuration_sets_defaults(self): |
| 152 | commands = self.directory / "bin" |
| 153 | commands.mkdir() |
| 154 | log = self.directory / "calls" |
| 155 | scripts = { |
| 156 | "update-desktop-database": "#!/bin/sh\nexit 0\n", |
| 157 | "gtk-update-icon-cache": "#!/bin/sh\nexit 0\n", |
| 158 | "getent": '#!/bin/sh\nprintf "tester:x:1000:1000::%s:/bin/sh\\n" "$TEST_HOME"\n', |
| 159 | "runuser": '#!/bin/sh\nprintf "%s\\n" "$*" >> "$TEST_LOG"\n', |
| 160 | } |
| 161 | for name, content in scripts.items(): |
| 162 | executable = commands / name |
| 163 | executable.write_text(content) |
| 164 | executable.chmod(0o755) |
| 165 | env = { |
| 166 | **os.environ, |
| 167 | "PATH": str(commands) + os.pathsep + os.environ["PATH"], |
| 168 | "SUDO_USER": "tester", |
| 169 | "TEST_HOME": str(self.directory), |
| 170 | "TEST_LOG": str(log), |
| 171 | } |
| 172 | for arguments, count in ((["configure"], 1), (["configure", "0.1.0"], 0), |
| 173 | (["triggered", "desktop"], 0)): |
| 174 | with self.subTest(arguments=arguments): |
| 175 | log.write_text("") |
| 176 | subprocess.run(["sh", str(ROOT / "packaging/ubuntu/rust/postinst"), *arguments], |
| 177 | env=env, check=True) |
| 178 | self.assertEqual(len(log.read_text().splitlines()), count) |
| 179 | env["SUDO_USER"] = "root" |
| 180 | log.write_text("") |
| 181 | subprocess.run(["sh", str(ROOT / "packaging/ubuntu/rust/postinst"), "configure"], |
| 182 | env=env, check=True) |
| 183 | self.assertEqual(log.read_text(), "") |
| 184 | |
| 185 | def test_prerm_restores_only_on_remove_for_known_user(self): |
| 186 | commands = self.directory / "bin" |
| 187 | commands.mkdir() |
| 188 | log = self.directory / "calls" |
| 189 | for name, content in { |
| 190 | "getent": '#!/bin/sh\nprintf "tester:x:1000:1000::%s:/bin/sh\\n" "$TEST_HOME"\n', |
| 191 | "runuser": '#!/bin/sh\nprintf "%s\\n" "$*" >> "$TEST_LOG"\n', |
| 192 | }.items(): |
| 193 | executable = commands / name |
| 194 | executable.write_text(content) |
| 195 | executable.chmod(0o755) |
| 196 | env = {**os.environ, "PATH": str(commands) + os.pathsep + os.environ["PATH"], |
| 197 | "SUDO_USER": "tester", "TEST_HOME": str(self.directory), "TEST_LOG": str(log)} |
| 198 | for action, count in (("upgrade", 0), ("failed-upgrade", 0), ("remove", 1)): |
| 199 | with self.subTest(action=action): |
| 200 | log.write_text("") |
| 201 | subprocess.run(["sh", str(ROOT / "packaging/ubuntu/rust/prerm"), action], |
| 202 | env=env, check=True, capture_output=True) |
| 203 | calls = log.read_text().splitlines() |
| 204 | self.assertEqual(len(calls), count) |
| 205 | if count: |
| 206 | self.assertIn("HOME=" + str(self.directory), calls[0]) |
| 207 | self.assertTrue(calls[0].endswith("/usr/lib/zipelo/default-apps remove")) |
| 208 | env["SUDO_USER"] = "root" |
| 209 | log.write_text("") |
| 210 | subprocess.run(["sh", str(ROOT / "packaging/ubuntu/rust/prerm"), "remove"], |
| 211 | env=env, check=True, capture_output=True) |
| 212 | self.assertEqual(log.read_text(), "") |
| 213 | env.pop("SUDO_USER") |
| 214 | log.write_text("") |
| 215 | result = subprocess.run(["sh", str(ROOT / "packaging/ubuntu/rust/prerm"), "remove"], |
| 216 | env=env, check=True, capture_output=True, text=True) |
| 217 | self.assertEqual(log.read_text(), "") |
| 218 | self.assertIn("사용자를 확인할 수 없어", result.stdout) |
| 219 | |
| 220 | def check_smoke(self, install_fails=False, defaults_fail=False, purge_fails=False, body_fails=False): |
| 221 | calls = [] |
| 222 | home = self.directory / "isolated-home" |
| 223 | home.mkdir() |
| 224 | isolated_config = home / ".config/mimeapps.list" |
| 225 | isolated_config.parent.mkdir() |
| 226 | isolated_config.write_bytes(b"previous-app.desktop\n") |
| 227 | |
| 228 | def command(arguments, **options): |
| 229 | calls.append(arguments) |
| 230 | if arguments[0] == "sudo": |
| 231 | self.assertIn("SUDO_USER=root", arguments) |
| 232 | self.assertIn("HOME=" + str(home), arguments) |
| 233 | if "-i" in arguments and install_fails: |
| 234 | raise subprocess.CalledProcessError(1, arguments) |
| 235 | if "-P" in arguments and purge_fails: |
| 236 | raise subprocess.CalledProcessError(2, arguments) |
| 237 | else: |
| 238 | self.assertEqual(arguments[0], "/usr/lib/zipelo/default-apps") |
| 239 | self.assertEqual(options["env"]["HOME"], str(home)) |
| 240 | self.assertEqual(options["env"]["XDG_CONFIG_HOME"], str(home / ".config")) |
| 241 | self.assertEqual(options["env"]["XDG_DATA_HOME"], str(home / ".local/share")) |
| 242 | self.assertEqual(options["env"]["XDG_STATE_HOME"], str(home / ".local/state")) |
| 243 | if arguments[1] == "install": |
| 244 | isolated_config.write_bytes(b"zipelo.desktop\n") |
| 245 | if defaults_fail: |
| 246 | raise subprocess.CalledProcessError(3, arguments) |
| 247 | else: |
| 248 | isolated_config.write_bytes(b"previous-app.desktop\n") |
| 249 | return subprocess.CompletedProcess(arguments, 0) |
| 250 | |
| 251 | def exercise(): |
| 252 | with patch.object(SMOKE.subprocess, "run", side_effect=command): |
| 253 | with SMOKE.installed_package(self.directory / "sample.deb", home) as isolated: |
| 254 | self.assertEqual(isolated["HOME"], str(home)) |
| 255 | if body_fails: |
| 256 | raise RuntimeError("창 실행 실패") |
| 257 | |
| 258 | if install_fails or defaults_fail or purge_fails or body_fails: |
| 259 | with self.assertRaises(BaseExceptionGroup) as raised: |
| 260 | exercise() |
| 261 | self.assertEqual(len(raised.exception.exceptions), |
| 262 | int(install_fails) + int(defaults_fail) + int(purge_fails) + int(body_fails)) |
| 263 | else: |
| 264 | exercise() |
| 265 | self.assertEqual(SMOKE.configs(), self.original) |
| 266 | self.assertEqual(self.previous.read_bytes(), b"previous-app.desktop\n") |
| 267 | self.assertFalse(self.created.exists()) |
| 268 | if install_fails: |
| 269 | self.assertEqual([arguments[-2:] for arguments in calls], |
| 270 | [["-i", str(self.directory / "sample.deb")], ["-P", "zipelo"]]) |
| 271 | else: |
| 272 | self.assertEqual([arguments[-2:] for arguments in calls if arguments[0] == "sudo"], |
| 273 | [["-i", str(self.directory / "sample.deb")], ["-P", "zipelo"]]) |
| 274 | self.assertEqual([arguments[-1] for arguments in calls if arguments[0] != "sudo"], |
| 275 | ["install", "remove"]) |
| 276 | self.assertEqual(isolated_config.read_bytes(), b"previous-app.desktop\n") |
| 277 | |
| 278 | def test_success_keeps_real_user_settings_unchanged(self): |
| 279 | self.check_smoke() |
| 280 | |
| 281 | def test_partial_install_failure_keeps_real_user_settings_unchanged(self): |
| 282 | self.check_smoke(install_fails=True) |
| 283 | |
| 284 | def test_default_app_failure_still_cleans_isolated_settings(self): |
| 285 | self.check_smoke(defaults_fail=True) |
| 286 | |
| 287 | def test_purge_failure_keeps_real_user_settings_unchanged(self): |
| 288 | self.check_smoke(purge_fails=True) |
| 289 | |
| 290 | def test_install_and_purge_failures_are_reported(self): |
| 291 | self.check_smoke(install_fails=True, purge_fails=True) |
| 292 | |
| 293 | def test_window_failure_keeps_real_user_settings_unchanged(self): |
| 294 | self.check_smoke(body_fails=True) |
| 295 | |
| 296 | def test_host_change_is_detected_without_overwrite(self): |
| 297 | home = self.directory / "isolated-home" |
| 298 | home.mkdir() |
| 299 | calls = [] |
| 300 | |
| 301 | def command(arguments, **options): |
| 302 | calls.append(arguments) |
| 303 | if "-i" in arguments: |
| 304 | self.previous.write_bytes(b"external-choice.desktop\n") |
| 305 | return subprocess.CompletedProcess(arguments, 0) |
| 306 | |
| 307 | with patch.object(SMOKE.subprocess, "run", side_effect=command): |
| 308 | with self.assertRaises(BaseExceptionGroup) as raised: |
| 309 | with SMOKE.installed_package(self.directory / "sample.deb", home): |
| 310 | pass |
| 311 | self.assertTrue(any("실제 사용자 MIME 설정" in str(error) |
| 312 | for error in raised.exception.exceptions)) |
| 313 | self.assertEqual(self.previous.read_bytes(), b"external-choice.desktop\n") |
| 314 | self.assertEqual(len(calls), 2) |
| 315 | |
| 316 | |
| 317 | if __name__ == "__main__": |
| 318 | unittest.main() |