team-ljyzipelo

공개
508줄24 KB
1from contextlib import redirect_stdout
2from io import StringIO
3import json
4import os
5from pathlib import Path, PurePosixPath, PureWindowsPath
6import tempfile
7import subprocess
8import sys
9import unittest
10from unittest.mock import ANY, patch
11
12import run_rust
13
14
15TEST_WORK = run_rust.work_directory(
16 run_rust.ROOT, os.environ.get("ZIPELO_CI_JOB", "rust-local")
17)
18
19
20class RunnerTests(unittest.TestCase):
21 def test_job_directory_is_restricted_to_one_work_child(self):
22 for name in ("../escape", "other/job", "", ".hidden", "bad name"):
23 with self.subTest(name=name), self.assertRaises(ValueError):
24 run_rust.work_directory(run_rust.ROOT, name)
25 self.assertEqual(run_rust.work_directory(
26 run_rust.ROOT, os.environ.get("ZIPELO_CI_JOB", "rust-local")
27 ), TEST_WORK)
28
29 def test_work_directory_rejects_symlinked_parents_before_creation(self):
30 for link_name in ("tests", "tests/work"):
31 with self.subTest(link_name=link_name), tempfile.TemporaryDirectory(
32 dir=TEST_WORK
33 ) as directory:
34 base = Path(directory)
35 project = base / "project"
36 project.mkdir()
37 outside = base / "outside"
38 outside.mkdir()
39 link = project / link_name
40 link.parent.mkdir(parents=True, exist_ok=True)
41 link.symlink_to(outside, target_is_directory=True)
42 with patch.object(
43 run_rust.subprocess, "check_output", return_value=str(project / ".git")
44 ):
45 with self.assertRaisesRegex(ValueError, "안전한 작업 디렉터리"):
46 run_rust.work_directory(project, "task")
47 self.assertFalse((outside / "task").exists())
48 self.assertFalse((outside / "work").exists())
49
50 def test_fixture_parent_symlink_is_rejected_before_creating_children(self):
51 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
52 base = Path(directory)
53 work = base / "work"
54 work.mkdir()
55 outside = base / "outside"
56 outside.mkdir()
57 (work / "fixtures").symlink_to(outside, target_is_directory=True)
58 with (
59 patch.object(run_rust, "test_work_directory", return_value=work),
60 self.assertRaisesRegex(ValueError, "작업 폴더 밖"),
61 ):
62 run_rust.prepare_fixtures(run_rust.ROOT)
63 self.assertEqual(list(outside.iterdir()), [])
64
65 def test_windows_setup_rejects_symlinked_parent_before_creating_tools(self):
66 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
67 base = Path(directory)
68 project = base / "project"
69 ci = project / "tests/ci"
70 ci.mkdir(parents=True)
71 work = project / "tests/work/task"
72 work.mkdir(parents=True)
73 script = ci / "setup_windows.sh"
74 script.write_bytes((run_rust.ROOT / "tests/ci/setup_windows.sh").read_bytes())
75 commands = base / "bin"
76 commands.mkdir()
77 git = commands / "git"
78 git.write_text('#!/bin/sh\nprintf "%s\n" "$FAKE_GIT_COMMON"\n')
79 git.chmod(0o700)
80 outside = base / "outside"
81 outside.mkdir()
82 (work / "linked").symlink_to(outside, target_is_directory=True)
83 environment = {
84 **os.environ,
85 "PATH": str(commands) + os.pathsep + os.environ["PATH"],
86 "FAKE_GIT_COMMON": str(project / ".git"),
87 "ZIPELO_CI_JOB": "task",
88 "ZIPELO_CI_TOOLS": str(work / "linked/tools"),
89 }
90 result = subprocess.run(["bash", str(script)], env=environment,
91 capture_output=True, text=True)
92 self.assertNotEqual(result.returncode, 0)
93 self.assertIn("작업 폴더 밖", result.stderr)
94 self.assertEqual(list(outside.iterdir()), [])
95
96 def test_windows_setup_rejects_external_rustup_before_install(self):
97 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
98 base = Path(directory)
99 project = base / "project"
100 ci = project / "tests/ci"
101 ci.mkdir(parents=True)
102 work = project / "tests/work/task"
103 tools = work / "tools"
104 tools.mkdir(parents=True)
105 script = ci / "setup_windows.sh"
106 script.write_bytes((run_rust.ROOT / "tests/ci/setup_windows.sh").read_bytes())
107 commands = base / "bin"
108 commands.mkdir()
109 git = commands / "git"
110 git.write_text('#!/bin/sh\nprintf "%s\n" "$FAKE_GIT_COMMON"\n')
111 git.chmod(0o700)
112 for name in ("apt-get", "dpkg-deb"):
113 command = commands / name
114 command.write_text("#!/bin/sh\nexit 0\n")
115 command.chmod(0o700)
116 rustup = commands / "rustup"
117 rustup.write_text(
118 '#!/bin/sh\nmkdir -p "$RUSTUP_HOME"\nprintf marker > "$RUSTUP_HOME/marker"\n'
119 )
120 rustup.chmod(0o700)
121 outside = base / "outside"
122 outside.mkdir()
123 environment = {
124 **os.environ,
125 "PATH": str(commands) + os.pathsep + os.environ["PATH"],
126 "FAKE_GIT_COMMON": str(project / ".git"),
127 "ZIPELO_CI_JOB": "task",
128 "ZIPELO_CI_TOOLS": str(tools),
129 }
130 for name in ("rustup", "cargo", "downloads/nested"):
131 with self.subTest(name=name):
132 link = tools / name
133 link.parent.mkdir(parents=True, exist_ok=True)
134 link.symlink_to(outside, target_is_directory=True)
135 result = subprocess.run(
136 ["bash", str(script)], env=environment,
137 capture_output=True, text=True,
138 )
139 self.assertNotEqual(result.returncode, 0)
140 self.assertIn("작업 폴더 밖", result.stderr)
141 self.assertEqual(list(outside.iterdir()), [])
142 link.unlink()
143
144 def test_output_paths_reject_symlinks_outside_job(self):
145 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
146 work = Path(directory)
147 outside = TEST_WORK / "outside"
148 for name in ("tmp", "target"):
149 with self.subTest(name=name):
150 link = work / name
151 link.symlink_to(outside, target_is_directory=True)
152 with self.assertRaisesRegex(ValueError, "작업 폴더 밖"):
153 run_rust.output_directory(work, name, create=True)
154 self.assertFalse(outside.exists())
155 link.unlink()
156
157 def test_output_paths_allow_symlinks_within_job(self):
158 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
159 work = Path(directory)
160 inner = work / "inner"
161 inner.mkdir()
162 link = work / "tmp"
163 link.symlink_to(inner, target_is_directory=True)
164 self.assertEqual(run_rust.output_directory(work, "tmp", create=True), link)
165
166 def test_cargo_and_temp_paths_are_kept_in_job_directory(self):
167 if "ZIPELO_TEST_WORK_DIR" not in os.environ:
168 self.skipTest("러너가 설정한 작업 경로에서 검사함")
169 for key in ("CARGO_TARGET_DIR", "CARGO_HOME", "TMPDIR", "TMP", "TEMP",
170 "ZIPELO_TEST_WORK_DIR"):
171 with self.subTest(key=key):
172 self.assertTrue(Path(os.environ[key]).resolve().is_relative_to(TEST_WORK))
173
174 def test_cargo_home_rejects_external_symlink(self):
175 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
176 work = Path(directory)
177 tools = work / "tools"
178 tools.mkdir()
179 outside = TEST_WORK / "outside"
180 (tools / "cargo").symlink_to(outside, target_is_directory=True)
181 with self.assertRaisesRegex(ValueError, "작업 폴더 밖"):
182 run_rust.output_directory(tools, "cargo", create=True)
183 self.assertFalse(outside.exists())
184
185 def test_changed_crates_include_reverse_dependencies(self):
186 paths = run_rust.manifests(run_rust.ROOT)
187 by_name = {path.parent.name: path for path in paths}
188 self.assertEqual(
189 run_rust.select_manifests(
190 run_rust.ROOT, paths, {"README.md", "docs/PLANS.md"}
191 ),
192 [],
193 )
194 selected = set(run_rust.select_manifests(
195 run_rust.ROOT, paths, {"experiments/rust-archive-worker/src/zip_recovery.rs"}
196 ))
197 for name in ("rust-archive-worker", "rust-ui-memory-app",
198 "rust-app-real-worker", "rust-large-archive-fixtures",
199 "rust-zip64-compat"):
200 self.assertIn(by_name[name], selected)
201 self.assertNotIn(by_name["rust-ui-system-font-regressions"], selected)
202 self.assertEqual(
203 run_rust.select_manifests(run_rust.ROOT, paths, {"tests/ci/run_rust.py"}),
204 paths,
205 )
206
207 def test_included_ui_source_selects_font_regression_crate(self):
208 paths = run_rust.manifests(run_rust.ROOT)
209 by_name = {path.parent.name: path for path in paths}
210 selected = set(run_rust.select_manifests(
211 run_rust.ROOT, paths,
212 {"experiments/rust-ui-memory-app/src/system_font.rs"},
213 ))
214 self.assertIn(by_name["rust-ui-memory-app"], selected)
215 self.assertIn(by_name["rust-ui-system-font-regressions"], selected)
216
217 def test_included_ui_guide_selects_app_tests(self):
218 paths = run_rust.manifests(run_rust.ROOT)
219 by_name = {path.parent.name: path for path in paths}
220 selected = set(run_rust.select_manifests(
221 run_rust.ROOT, paths, {"docs/ui-scenario-guide.md"}
222 ))
223 self.assertEqual(selected, {by_name["rust-ui-memory-app"]})
224
225 def test_changed_file_list_includes_worktree_and_untracked_files(self):
226 with patch.object(run_rust.subprocess, "check_output", side_effect=[
227 "base\n",
228 b"experiments/rust-archive-worker/src/lib.rs\0",
229 b"tests/rust-app-ui/new_case.rs\0",
230 ]) as git:
231 changes = run_rust.changed_files(run_rust.ROOT)
232 self.assertEqual(changes, {
233 "experiments/rust-archive-worker/src/lib.rs",
234 "tests/rust-app-ui/new_case.rs",
235 })
236 self.assertEqual(git.call_count, 3)
237
238 def test_changed_file_list_ignores_runner_outputs_in_job_worktree(self):
239 with (
240 patch.dict(run_rust.os.environ, {"ZIPELO_TEST_WORK_DIR": str(run_rust.ROOT)}),
241 patch.object(run_rust.subprocess, "check_output", side_effect=[
242 "base\n",
243 b"README.md\0",
244 b"target/debug/app\0tools/cargo/config.toml\0"
245 b"tmp/result\0fixtures/data\0local-results.json\0",
246 ]),
247 ):
248 self.assertEqual(run_rust.changed_files(run_rust.ROOT), {"README.md"})
249
250 def test_empty_selection_does_not_require_cross_tools(self):
251 with patch.object(run_rust, "prepare_cross_build",
252 side_effect=AssertionError("도구를 준비하면 안 됨")):
253 self.assertEqual(
254 run_rust.execute_phases(run_rust.ROOT, ["build", "test", "cross-build"], []),
255 [],
256 )
257
258 def test_runner_sets_cargo_home_in_job_before_execution(self):
259 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
260 work = Path(directory)
261 with (
262 patch.object(run_rust, "work_directory", return_value=work),
263 patch.object(run_rust, "prepare_tools"),
264 patch.object(run_rust.sys, "argv", ["run_rust.py", "build"]),
265 patch.object(run_rust.subprocess, "run",
266 return_value=subprocess.CompletedProcess([], 0)),
267 patch.object(run_rust.subprocess, "check_output",
268 return_value="tested-head\n"),
269 patch.object(run_rust, "execute_phases", return_value=[]) as execute,
270 patch.dict(run_rust.os.environ, {"GITHUB_STEP_SUMMARY": ""}),
271 redirect_stdout(StringIO()),
272 ):
273 self.assertEqual(run_rust.main(), 0)
274 self.assertEqual(
275 run_rust.os.environ["CARGO_HOME"], str(work / "tools/cargo")
276 )
277 self.assertTrue((work / "tools/cargo").is_dir())
278 execute.assert_called_once()
279
280 def test_all_manifests_have_locks(self):
281 paths = run_rust.manifests(run_rust.ROOT)
282 expected = set(run_rust.ROOT.glob("experiments/*/Cargo.toml"))
283 expected |= set(run_rust.ROOT.glob("tests/*/Cargo.toml"))
284 self.assertEqual(set(paths), expected)
285
286 def test_failure_does_not_hide_later_crates(self):
287 paths = [
288 Path("/repo/experiments/a/Cargo.toml"),
289 Path("/repo/experiments/b/Cargo.toml"),
290 ]
291 with (
292 patch.object(run_rust, "manifests", return_value=paths),
293 patch.object(run_rust.subprocess, "run", side_effect=[
294 subprocess.CompletedProcess([], 7),
295 subprocess.CompletedProcess([], 0),
296 ]),
297 ):
298 results = run_rust.run(Path("/repo"), "build")
299 self.assertEqual([row["status"] for row in results], ["failed", "passed"])
300 self.assertEqual(results[0]["exit_code"], 7)
301
302 def test_windows_exclusion_is_explicit_and_only_for_linux_tests(self):
303 paths = [
304 Path("/repo/tests/rust-ui-system-font-regressions/Cargo.toml"),
305 Path("/repo/experiments/rust-archive-worker/Cargo.toml"),
306 ]
307 with (
308 patch.object(run_rust, "manifests", return_value=paths),
309 patch.object(run_rust.sys, "platform", "win32"),
310 patch.object(
311 run_rust.subprocess, "run",
312 return_value=subprocess.CompletedProcess([], 0),
313 ) as execute,
314 ):
315 results = run_rust.run(Path("/repo"), "test")
316 self.assertEqual(
317 [row["status"] for row in results], ["not-applicable", "passed"]
318 )
319 self.assertEqual(execute.call_count, 1)
320
321 def test_fixture_bytes_match_git_blobs(self):
322 names = subprocess.check_output(
323 ["git", "ls-files", "-z", "tests/**/fixtures/*"], cwd=run_rust.ROOT
324 ).decode("utf-8").split("\0")
325 names = [name for name in names if name]
326 self.assertTrue(names, "검증할 fixture가 없음")
327 for name in names:
328 with self.subTest(path=name):
329 expected = subprocess.check_output(
330 ["git", "show", f"HEAD:{name}"], cwd=run_rust.ROOT
331 )
332 self.assertEqual((run_rust.ROOT / name).read_bytes(), expected)
333
334 def test_cross_build_never_executes_tests(self):
335 args = run_rust.command(Path("tests/example/Cargo.toml"), "cross-build")
336 self.assertEqual(args[2], "build")
337 self.assertIn(run_rust.WINDOWS_TARGET, args)
338 self.assertNotIn("--test-threads=1", args)
339
340 def test_preflight_failure_is_reported_without_hiding_other_phase(self):
341 with (
342 patch.object(run_rust, "prepare_cross_build", side_effect=ValueError("missing linker")),
343 patch.object(run_rust, "run", return_value=[{"manifest": "sample", "status": "passed"}]),
344 ):
345 results = run_rust.execute_phases(Path("/repo"), ["build", "cross-build"])
346 self.assertEqual([row["status"] for row in results], ["passed", "failed"])
347 self.assertEqual(results[1]["reason"], "missing linker")
348
349 def test_self_check_failure_replaces_previous_success_report(self):
350 for phase, platform in (("local", "linux"), ("test", "win32")):
351 with self.subTest(phase=phase), tempfile.TemporaryDirectory(
352 dir=TEST_WORK
353 ) as directory:
354 root = Path(directory)
355 (root / "work/tmp").mkdir(parents=True)
356 report_path = root / f"work/{phase}-results.json"
357 with (
358 patch.object(run_rust, "ROOT", root),
359 patch.object(run_rust, "work_directory", return_value=root / "work"),
360 patch.object(run_rust, "prepare_tools"),
361 patch.object(run_rust, "prepare_local_tools"),
362 patch.object(run_rust.sys, "argv", ["run_rust.py", phase]),
363 patch.object(run_rust.sys, "platform", platform),
364 patch.dict(run_rust.os.environ, {"GITHUB_STEP_SUMMARY": ""}),
365 patch.object(run_rust.subprocess, "run", side_effect=[
366 subprocess.CompletedProcess([], 0),
367 subprocess.CompletedProcess([], 7),
368 ]),
369 patch.object(run_rust.subprocess, "check_output", side_effect=[
370 "successful-head\n", "failed-head\n",
371 ]),
372 patch.object(run_rust, "execute_phases", return_value=[
373 {"phase": "test", "manifest": "sample", "status": "passed"},
374 ]) as execute,
375 redirect_stdout(StringIO()),
376 ):
377 self.assertEqual(run_rust.main(), 0)
378 successful = json.loads(report_path.read_text(encoding="utf-8"))
379 self.assertEqual(successful["results"][0]["status"], "passed")
380 self.assertEqual(run_rust.main(), 7)
381 failed = json.loads(report_path.read_text(encoding="utf-8"))
382 self.assertEqual(failed["head"], "failed-head")
383 self.assertEqual(failed["results"], [{
384 "phase": "self-check",
385 "manifest": "tests/ci",
386 "status": "failed",
387 "exit_code": 7,
388 }])
389 self.assertFalse(failed["windows_runtime_tested"])
390 execute.assert_called_once()
391
392 @unittest.skipUnless(sys.platform == "linux", "Linux MinGW 실행 파일 탐색 시험임")
393 def test_linked_worktree_finds_setup_tools_without_path_export(self):
394 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
395 base = Path(directory)
396 root = base / "linked"
397 tools = base / "tests/ci/tools"
398 binaries = tools / "mingw/usr/bin"
399 binaries.mkdir(parents=True)
400 for name in ("gcc", "g++"):
401 executable = binaries / f"x86_64-w64-mingw32-{name}-posix"
402 executable.write_text("#!/bin/sh\nexit 0\n")
403 executable.chmod(0o700)
404 rustup = tools / "rustup"
405 (rustup / "toolchains/1.99.1-x86_64-unknown-linux-gnu").mkdir(parents=True)
406 with (
407 patch.dict(run_rust.os.environ, {"PATH": ""}, clear=True),
408 patch.object(run_rust.subprocess, "check_output", return_value=str(base / ".git")),
409 ):
410 run_rust.prepare_tools(root)
411 run_rust.prepare_cross_build()
412 self.assertEqual(run_rust.os.environ["RUSTUP_HOME"], str(rustup))
413 self.assertEqual(
414 run_rust.os.environ["CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER"],
415 str(binaries / "x86_64-w64-mingw32-gcc-posix"),
416 )
417
418 @unittest.skipUnless(sys.platform == "linux", "Linux MinGW 실행 파일 탐색 시험임")
419 def test_default_checkout_reuses_existing_setup_tools(self):
420 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
421 root = Path(directory)
422 tools = root / "tests/ci/tools"
423 binaries = tools / "mingw/usr/bin"
424 binaries.mkdir(parents=True)
425 executable = binaries / "x86_64-w64-mingw32-gcc-posix"
426 executable.write_text("#!/bin/sh\nexit 0\n")
427 executable.chmod(0o700)
428 rustup = tools / "rustup"
429 (rustup / "toolchains/1.99.1-x86_64-unknown-linux-gnu").mkdir(parents=True)
430 with (
431 patch.dict(run_rust.os.environ, {"PATH": ""}, clear=True),
432 patch.object(run_rust.subprocess, "check_output", return_value=str(root / ".git")),
433 ):
434 run_rust.prepare_tools(root)
435 self.assertEqual(run_rust.os.environ["RUSTUP_HOME"], str(rustup))
436 self.assertTrue(run_rust.os.environ["PATH"].startswith(str(binaries)))
437 self.assertEqual(run_rust.shutil.which("x86_64-w64-mingw32-gcc-posix"),
438 str(executable))
439
440 def test_unconfigured_work_directory_uses_common_project(self):
441 with patch.dict(os.environ), patch.object(
442 run_rust, "work_directory", return_value=TEST_WORK
443 ) as directory:
444 os.environ.pop("ZIPELO_TEST_WORK_DIR", None)
445 os.environ.pop("ZIPELO_CI_JOB", None)
446 self.assertEqual(run_rust.test_work_directory(run_rust.ROOT), TEST_WORK)
447 directory.assert_called_once_with(run_rust.ROOT, "rust-local")
448
449 def test_local_bootstraps_missing_cross_tools_and_reloads_paths(self):
450 for root in (Path("/repo"), PurePosixPath("/repo"), PureWindowsPath("C:/repo")):
451 with self.subTest(root=root):
452 with (
453 patch.object(run_rust, "prepare_cross_build", side_effect=[ValueError("missing"), None]) as detect,
454 patch.object(run_rust.subprocess, "run") as setup,
455 patch.object(run_rust, "prepare_tools") as reload,
456 patch.object(run_rust, "test_work_directory", return_value=root / "tests/work/rust-local"),
457 ):
458 run_rust.prepare_local_tools(root)
459 setup.assert_called_once_with(
460 ["bash", str(root / "tests/ci/setup_windows.sh")], cwd=root, env=ANY, check=True,
461 )
462 reload.assert_called_once_with(root)
463 self.assertEqual(detect.call_count, 2)
464
465 def test_existing_cross_tools_do_not_trigger_downloads(self):
466 with (
467 patch.object(run_rust, "prepare_cross_build"),
468 patch.object(run_rust.subprocess, "run") as setup,
469 ):
470 run_rust.prepare_local_tools(Path("/repo"))
471 setup.assert_not_called()
472
473 def test_explicit_tools_directory_does_not_fall_back_to_other_worktree(self):
474 with (
475 patch.dict(run_rust.os.environ, {"PATH": "", "ZIPELO_CI_TOOLS": "/missing"}, clear=True),
476 patch.object(run_rust.subprocess, "check_output") as git,
477 ):
478 run_rust.prepare_tools(Path("/repo"))
479 git.assert_not_called()
480 with self.assertRaisesRegex(ValueError, "setup_windows.sh"):
481 run_rust.prepare_cross_build()
482
483 def test_long_checkout_keeps_fixture_directory_in_work(self):
484 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
485 root = Path(directory) / ("long-checkout-" * 10)
486 work = Path(directory) / "work"
487 with patch.dict(run_rust.os.environ, {"ZIPELO_TEST_WORK_DIR": str(work)}):
488 self.assertEqual(run_rust.prepare_fixtures(root), {})
489 self.assertTrue((work / "fixtures").is_dir())
490 self.assertFalse((root / "tests").exists())
491
492 def test_fixture_preflight_error_is_failure(self):
493 with (
494 patch.object(run_rust, "prepare_fixtures", side_effect=ValueError("bad fixture path")),
495 patch.object(run_rust.sys, "platform", "linux"),
496 ):
497 results = run_rust.execute_phases(run_rust.ROOT, ["test"])
498 self.assertEqual(results[0]["status"], "failed")
499
500 def test_cargo_contract(self):
501 args = run_rust.command(Path("tests/example/Cargo.toml"), "test")
502 self.assertIn("--locked", args)
503 self.assertIn("--all-features", args)
504 self.assertEqual(args[-2:], ["--", "--test-threads=1"])
505
506
507if __name__ == "__main__":
508 unittest.main()