team-ljyzipelo

공개
437줄21 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", "TMPDIR", "TMP", "TEMP", "ZIPELO_TEST_WORK_DIR"):
170 with self.subTest(key=key):
171 self.assertTrue(Path(os.environ[key]).resolve().is_relative_to(TEST_WORK))
172
173 def test_all_manifests_have_locks(self):
174 paths = run_rust.manifests(run_rust.ROOT)
175 expected = set(run_rust.ROOT.glob("experiments/*/Cargo.toml"))
176 expected |= set(run_rust.ROOT.glob("tests/*/Cargo.toml"))
177 self.assertEqual(set(paths), expected)
178
179 def test_failure_does_not_hide_later_crates(self):
180 paths = [
181 Path("/repo/experiments/a/Cargo.toml"),
182 Path("/repo/experiments/b/Cargo.toml"),
183 ]
184 with (
185 patch.object(run_rust, "manifests", return_value=paths),
186 patch.object(run_rust.subprocess, "run", side_effect=[
187 subprocess.CompletedProcess([], 7),
188 subprocess.CompletedProcess([], 0),
189 ]),
190 ):
191 results = run_rust.run(Path("/repo"), "build")
192 self.assertEqual([row["status"] for row in results], ["failed", "passed"])
193 self.assertEqual(results[0]["exit_code"], 7)
194
195 def test_windows_exclusion_is_explicit_and_only_for_linux_tests(self):
196 paths = [
197 Path("/repo/tests/rust-file-publication/Cargo.toml"),
198 Path("/repo/experiments/rust-file-publication/Cargo.toml"),
199 ]
200 with (
201 patch.object(run_rust, "manifests", return_value=paths),
202 patch.object(run_rust.sys, "platform", "win32"),
203 patch.object(
204 run_rust.subprocess, "run",
205 return_value=subprocess.CompletedProcess([], 0),
206 ) as execute,
207 ):
208 results = run_rust.run(Path("/repo"), "test")
209 self.assertEqual(
210 [row["status"] for row in results], ["not-applicable", "passed"]
211 )
212 self.assertEqual(execute.call_count, 1)
213
214 def test_fixture_bytes_match_git_blobs(self):
215 names = subprocess.check_output(
216 ["git", "ls-files", "-z", "tests/**/fixtures/*"], cwd=run_rust.ROOT
217 ).decode("utf-8").split("\0")
218 names = [name for name in names if name]
219 self.assertTrue(names, "검증할 fixture가 없음")
220 for name in names:
221 with self.subTest(path=name):
222 expected = subprocess.check_output(
223 ["git", "show", f"HEAD:{name}"], cwd=run_rust.ROOT
224 )
225 self.assertEqual((run_rust.ROOT / name).read_bytes(), expected)
226
227 def test_cross_build_never_executes_tests(self):
228 args = run_rust.command(Path("tests/example/Cargo.toml"), "cross-build")
229 self.assertEqual(args[2], "build")
230 self.assertIn(run_rust.WINDOWS_TARGET, args)
231 self.assertNotIn("--test-threads=1", args)
232
233 def test_preflight_failure_is_reported_without_hiding_other_phase(self):
234 with (
235 patch.object(run_rust, "prepare_cross_build", side_effect=ValueError("missing linker")),
236 patch.object(run_rust, "run", return_value=[{"manifest": "sample", "status": "passed"}]),
237 ):
238 results = run_rust.execute_phases(Path("/repo"), ["build", "cross-build"])
239 self.assertEqual([row["status"] for row in results], ["passed", "failed"])
240 self.assertEqual(results[1]["reason"], "missing linker")
241
242 def test_self_check_failure_replaces_previous_success_report(self):
243 for phase, platform in (("local", "linux"), ("test", "win32")):
244 with self.subTest(phase=phase), tempfile.TemporaryDirectory(
245 dir=TEST_WORK
246 ) as directory:
247 root = Path(directory)
248 (root / "work/tmp").mkdir(parents=True)
249 report_path = root / f"work/{phase}-results.json"
250 with (
251 patch.object(run_rust, "ROOT", root),
252 patch.object(run_rust, "work_directory", return_value=root / "work"),
253 patch.object(run_rust, "prepare_tools"),
254 patch.object(run_rust, "prepare_local_tools"),
255 patch.object(run_rust.sys, "argv", ["run_rust.py", phase]),
256 patch.object(run_rust.sys, "platform", platform),
257 patch.dict(run_rust.os.environ, {"GITHUB_STEP_SUMMARY": ""}),
258 patch.object(run_rust.subprocess, "run", side_effect=[
259 subprocess.CompletedProcess([], 0),
260 subprocess.CompletedProcess([], 7),
261 ]),
262 patch.object(run_rust.subprocess, "check_output", side_effect=[
263 "successful-head\n", "failed-head\n",
264 ]),
265 patch.object(run_rust, "execute_phases", return_value=[
266 {"phase": "test", "manifest": "sample", "status": "passed"},
267 ]) as execute,
268 redirect_stdout(StringIO()),
269 ):
270 self.assertEqual(run_rust.main(), 0)
271 successful = json.loads(report_path.read_text(encoding="utf-8"))
272 self.assertEqual(successful["results"][0]["status"], "passed")
273 self.assertEqual(run_rust.main(), 7)
274 failed = json.loads(report_path.read_text(encoding="utf-8"))
275 self.assertEqual(failed["head"], "failed-head")
276 self.assertEqual(failed["results"], [{
277 "phase": "self-check",
278 "manifest": "tests/ci",
279 "status": "failed",
280 "exit_code": 7,
281 }])
282 self.assertFalse(failed["windows_runtime_tested"])
283 execute.assert_called_once()
284
285 @unittest.skipUnless(sys.platform == "linux", "Linux MinGW 실행 파일 탐색 시험임")
286 def test_linked_worktree_finds_setup_tools_without_path_export(self):
287 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
288 base = Path(directory)
289 root = base / "linked"
290 tools = base / "tests/ci/tools"
291 binaries = tools / "mingw/usr/bin"
292 binaries.mkdir(parents=True)
293 for name in ("gcc", "g++"):
294 executable = binaries / f"x86_64-w64-mingw32-{name}-posix"
295 executable.write_text("#!/bin/sh\nexit 0\n")
296 executable.chmod(0o700)
297 rustup = tools / "rustup"
298 (rustup / "toolchains/1.99.1-x86_64-unknown-linux-gnu").mkdir(parents=True)
299 with (
300 patch.dict(run_rust.os.environ, {"PATH": ""}, clear=True),
301 patch.object(run_rust.subprocess, "check_output", return_value=str(base / ".git")),
302 ):
303 run_rust.prepare_tools(root)
304 run_rust.prepare_cross_build()
305 self.assertEqual(run_rust.os.environ["RUSTUP_HOME"], str(rustup))
306 self.assertEqual(
307 run_rust.os.environ["CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER"],
308 str(binaries / "x86_64-w64-mingw32-gcc-posix"),
309 )
310
311 @unittest.skipUnless(sys.platform == "linux", "Linux MinGW 실행 파일 탐색 시험임")
312 def test_default_checkout_reuses_existing_setup_tools(self):
313 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
314 root = Path(directory)
315 tools = root / "tests/ci/tools"
316 binaries = tools / "mingw/usr/bin"
317 binaries.mkdir(parents=True)
318 executable = binaries / "x86_64-w64-mingw32-gcc-posix"
319 executable.write_text("#!/bin/sh\nexit 0\n")
320 executable.chmod(0o700)
321 rustup = tools / "rustup"
322 (rustup / "toolchains/1.99.1-x86_64-unknown-linux-gnu").mkdir(parents=True)
323 with (
324 patch.dict(run_rust.os.environ, {"PATH": ""}, clear=True),
325 patch.object(run_rust.subprocess, "check_output", return_value=str(root / ".git")),
326 ):
327 run_rust.prepare_tools(root)
328 self.assertEqual(run_rust.os.environ["RUSTUP_HOME"], str(rustup))
329 self.assertTrue(run_rust.os.environ["PATH"].startswith(str(binaries)))
330 self.assertEqual(run_rust.shutil.which("x86_64-w64-mingw32-gcc-posix"),
331 str(executable))
332
333 def test_unconfigured_work_directory_uses_common_project(self):
334 with patch.dict(os.environ), patch.object(
335 run_rust, "work_directory", return_value=TEST_WORK
336 ) as directory:
337 os.environ.pop("ZIPELO_TEST_WORK_DIR", None)
338 os.environ.pop("ZIPELO_CI_JOB", None)
339 self.assertEqual(run_rust.test_work_directory(run_rust.ROOT), TEST_WORK)
340 directory.assert_called_once_with(run_rust.ROOT, "rust-local")
341
342 def test_local_bootstraps_missing_cross_tools_and_reloads_paths(self):
343 for root in (Path("/repo"), PurePosixPath("/repo"), PureWindowsPath("C:/repo")):
344 with self.subTest(root=root):
345 with (
346 patch.object(run_rust, "prepare_cross_build", side_effect=[ValueError("missing"), None]) as detect,
347 patch.object(run_rust.subprocess, "run") as setup,
348 patch.object(run_rust, "prepare_tools") as reload,
349 patch.object(run_rust, "test_work_directory", return_value=root / "tests/work/rust-local"),
350 ):
351 run_rust.prepare_local_tools(root)
352 setup.assert_called_once_with(
353 ["bash", str(root / "tests/ci/setup_windows.sh")], cwd=root, env=ANY, check=True,
354 )
355 reload.assert_called_once_with(root)
356 self.assertEqual(detect.call_count, 2)
357
358 def test_existing_cross_tools_do_not_trigger_downloads(self):
359 with (
360 patch.object(run_rust, "prepare_cross_build"),
361 patch.object(run_rust.subprocess, "run") as setup,
362 ):
363 run_rust.prepare_local_tools(Path("/repo"))
364 setup.assert_not_called()
365
366 def test_explicit_tools_directory_does_not_fall_back_to_other_worktree(self):
367 with (
368 patch.dict(run_rust.os.environ, {"PATH": "", "ZIPELO_CI_TOOLS": "/missing"}, clear=True),
369 patch.object(run_rust.subprocess, "check_output") as git,
370 ):
371 run_rust.prepare_tools(Path("/repo"))
372 git.assert_not_called()
373 with self.assertRaisesRegex(ValueError, "setup_windows.sh"):
374 run_rust.prepare_cross_build()
375
376 @unittest.skipUnless(sys.platform == "linux", "Linux 파일시스템과 소유권 검사 시험임")
377 def test_filesystem_skip_is_limited_to_publication_test_crates(self):
378 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
379 root = Path(directory)
380 work = root / "work"
381 work.mkdir()
382 paths = [
383 root / "tests/rust-file-publication/Cargo.toml",
384 root / "tests/rust-gzip-file-job/Cargo.toml",
385 root / "tests/rust-file-snapshot/Cargo.toml",
386 root / "experiments/rust-file-publication/Cargo.toml",
387 ]
388 with (
389 patch.object(run_rust, "manifests", return_value=paths),
390 patch.dict(run_rust.os.environ, {"ZIPELO_TEST_WORK_DIR": str(work)}),
391 patch.object(run_rust.subprocess, "check_output", return_value="1021994\n"),
392 patch.object(run_rust.subprocess, "run", return_value=subprocess.CompletedProcess([], 0)) as cargo,
393 ):
394 results = run_rust.run(root, "test")
395 self.assertEqual([row["status"] for row in results], [
396 "not-applicable", "not-applicable", "passed", "passed",
397 ])
398 self.assertIn("0x1021994", results[0]["reason"])
399 self.assertEqual(cargo.call_count, 2)
400 cargo.reset_mock()
401 results = run_rust.run(root, "cross-build")
402 self.assertTrue(all(row["status"] == "passed" for row in results))
403 self.assertEqual(cargo.call_count, 4)
404
405 @unittest.skipUnless(sys.platform == "linux", "Linux 소켓 경로 회귀 시험임")
406 def test_long_checkout_does_not_block_file_fixtures(self):
407 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
408 root = Path(directory) / ("long-checkout-" * 10)
409 work = Path(directory) / "work"
410 socket = root / "tests/rust-file-publication/runs/case-1-1/parent/output"
411 self.assertGreaterEqual(len(run_rust.os.fsencode(socket)), 108)
412 with (
413 patch.dict(run_rust.os.environ, {"ZIPELO_TEST_WORK_DIR": str(work)}),
414 patch.object(run_rust.subprocess, "check_output", return_value="ef53\n"),
415 ):
416 self.assertEqual(run_rust.prepare_fixtures(root), {})
417 for name in run_rust.FILE_FIXTURES:
418 self.assertEqual(list((work / "fixtures" / name).iterdir()), [])
419 self.assertFalse((root / "tests" / name / "runs").exists())
420
421 def test_unknown_filesystem_probe_error_is_failure(self):
422 with (
423 patch.object(run_rust, "prepare_fixtures", side_effect=subprocess.CalledProcessError(1, "stat")),
424 patch.object(run_rust.sys, "platform", "linux"),
425 ):
426 results = run_rust.execute_phases(run_rust.ROOT, ["test"])
427 self.assertEqual(results[0]["status"], "failed")
428
429 def test_cargo_contract(self):
430 args = run_rust.command(Path("tests/example/Cargo.toml"), "test")
431 self.assertIn("--locked", args)
432 self.assertIn("--all-features", args)
433 self.assertEqual(args[-2:], ["--", "--test-threads=1"])
434
435
436if __name__ == "__main__":
437 unittest.main()