team-ljyzipelo

공개
389줄19 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_output_paths_reject_symlinks_outside_job(self):
97 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
98 work = Path(directory)
99 outside = TEST_WORK / "outside"
100 for name in ("tmp", "target"):
101 with self.subTest(name=name):
102 link = work / name
103 link.symlink_to(outside, target_is_directory=True)
104 with self.assertRaisesRegex(ValueError, "작업 폴더 밖"):
105 run_rust.output_directory(work, name, create=True)
106 self.assertFalse(outside.exists())
107 link.unlink()
108
109 def test_output_paths_allow_symlinks_within_job(self):
110 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
111 work = Path(directory)
112 inner = work / "inner"
113 inner.mkdir()
114 link = work / "tmp"
115 link.symlink_to(inner, target_is_directory=True)
116 self.assertEqual(run_rust.output_directory(work, "tmp", create=True), link)
117
118 def test_cargo_and_temp_paths_are_kept_in_job_directory(self):
119 if "ZIPELO_TEST_WORK_DIR" not in os.environ:
120 self.skipTest("러너가 설정한 작업 경로에서 검사함")
121 for key in ("CARGO_TARGET_DIR", "TMPDIR", "TMP", "TEMP", "ZIPELO_TEST_WORK_DIR"):
122 with self.subTest(key=key):
123 self.assertTrue(Path(os.environ[key]).resolve().is_relative_to(TEST_WORK))
124
125 def test_all_manifests_have_locks(self):
126 paths = run_rust.manifests(run_rust.ROOT)
127 expected = set(run_rust.ROOT.glob("experiments/*/Cargo.toml"))
128 expected |= set(run_rust.ROOT.glob("tests/*/Cargo.toml"))
129 self.assertEqual(set(paths), expected)
130
131 def test_failure_does_not_hide_later_crates(self):
132 paths = [
133 Path("/repo/experiments/a/Cargo.toml"),
134 Path("/repo/experiments/b/Cargo.toml"),
135 ]
136 with (
137 patch.object(run_rust, "manifests", return_value=paths),
138 patch.object(run_rust.subprocess, "run", side_effect=[
139 subprocess.CompletedProcess([], 7),
140 subprocess.CompletedProcess([], 0),
141 ]),
142 ):
143 results = run_rust.run(Path("/repo"), "build")
144 self.assertEqual([row["status"] for row in results], ["failed", "passed"])
145 self.assertEqual(results[0]["exit_code"], 7)
146
147 def test_windows_exclusion_is_explicit_and_only_for_linux_tests(self):
148 paths = [
149 Path("/repo/tests/rust-file-publication/Cargo.toml"),
150 Path("/repo/experiments/rust-file-publication/Cargo.toml"),
151 ]
152 with (
153 patch.object(run_rust, "manifests", return_value=paths),
154 patch.object(run_rust.sys, "platform", "win32"),
155 patch.object(
156 run_rust.subprocess, "run",
157 return_value=subprocess.CompletedProcess([], 0),
158 ) as execute,
159 ):
160 results = run_rust.run(Path("/repo"), "test")
161 self.assertEqual(
162 [row["status"] for row in results], ["not-applicable", "passed"]
163 )
164 self.assertEqual(execute.call_count, 1)
165
166 def test_fixture_bytes_match_git_blobs(self):
167 names = subprocess.check_output(
168 ["git", "ls-files", "-z", "tests/**/fixtures/*"], cwd=run_rust.ROOT
169 ).decode("utf-8").split("\0")
170 names = [name for name in names if name]
171 self.assertTrue(names, "검증할 fixture가 없음")
172 for name in names:
173 with self.subTest(path=name):
174 expected = subprocess.check_output(
175 ["git", "show", f"HEAD:{name}"], cwd=run_rust.ROOT
176 )
177 self.assertEqual((run_rust.ROOT / name).read_bytes(), expected)
178
179 def test_cross_build_never_executes_tests(self):
180 args = run_rust.command(Path("tests/example/Cargo.toml"), "cross-build")
181 self.assertEqual(args[2], "build")
182 self.assertIn(run_rust.WINDOWS_TARGET, args)
183 self.assertNotIn("--test-threads=1", args)
184
185 def test_preflight_failure_is_reported_without_hiding_other_phase(self):
186 with (
187 patch.object(run_rust, "prepare_cross_build", side_effect=ValueError("missing linker")),
188 patch.object(run_rust, "run", return_value=[{"manifest": "sample", "status": "passed"}]),
189 ):
190 results = run_rust.execute_phases(Path("/repo"), ["build", "cross-build"])
191 self.assertEqual([row["status"] for row in results], ["passed", "failed"])
192 self.assertEqual(results[1]["reason"], "missing linker")
193
194 def test_self_check_failure_replaces_previous_success_report(self):
195 for phase, platform in (("local", "linux"), ("test", "win32")):
196 with self.subTest(phase=phase), tempfile.TemporaryDirectory(
197 dir=TEST_WORK
198 ) as directory:
199 root = Path(directory)
200 (root / "work/tmp").mkdir(parents=True)
201 report_path = root / f"work/{phase}-results.json"
202 with (
203 patch.object(run_rust, "ROOT", root),
204 patch.object(run_rust, "work_directory", return_value=root / "work"),
205 patch.object(run_rust, "prepare_tools"),
206 patch.object(run_rust, "prepare_local_tools"),
207 patch.object(run_rust.sys, "argv", ["run_rust.py", phase]),
208 patch.object(run_rust.sys, "platform", platform),
209 patch.dict(run_rust.os.environ, {"GITHUB_STEP_SUMMARY": ""}),
210 patch.object(run_rust.subprocess, "run", side_effect=[
211 subprocess.CompletedProcess([], 0),
212 subprocess.CompletedProcess([], 7),
213 ]),
214 patch.object(run_rust.subprocess, "check_output", side_effect=[
215 "successful-head\n", "failed-head\n",
216 ]),
217 patch.object(run_rust, "execute_phases", return_value=[
218 {"phase": "test", "manifest": "sample", "status": "passed"},
219 ]) as execute,
220 redirect_stdout(StringIO()),
221 ):
222 self.assertEqual(run_rust.main(), 0)
223 successful = json.loads(report_path.read_text(encoding="utf-8"))
224 self.assertEqual(successful["results"][0]["status"], "passed")
225 self.assertEqual(run_rust.main(), 7)
226 failed = json.loads(report_path.read_text(encoding="utf-8"))
227 self.assertEqual(failed["head"], "failed-head")
228 self.assertEqual(failed["results"], [{
229 "phase": "self-check",
230 "manifest": "tests/ci",
231 "status": "failed",
232 "exit_code": 7,
233 }])
234 self.assertFalse(failed["windows_runtime_tested"])
235 execute.assert_called_once()
236
237 @unittest.skipUnless(sys.platform == "linux", "Linux MinGW 실행 파일 탐색 시험임")
238 def test_linked_worktree_finds_setup_tools_without_path_export(self):
239 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
240 base = Path(directory)
241 root = base / "linked"
242 tools = base / "tests/ci/tools"
243 binaries = tools / "mingw/usr/bin"
244 binaries.mkdir(parents=True)
245 for name in ("gcc", "g++"):
246 executable = binaries / f"x86_64-w64-mingw32-{name}-posix"
247 executable.write_text("#!/bin/sh\nexit 0\n")
248 executable.chmod(0o700)
249 rustup = tools / "rustup"
250 (rustup / "toolchains/1.99.1-x86_64-unknown-linux-gnu").mkdir(parents=True)
251 with (
252 patch.dict(run_rust.os.environ, {"PATH": ""}, clear=True),
253 patch.object(run_rust.subprocess, "check_output", return_value=str(base / ".git")),
254 ):
255 run_rust.prepare_tools(root)
256 run_rust.prepare_cross_build()
257 self.assertEqual(run_rust.os.environ["RUSTUP_HOME"], str(rustup))
258 self.assertEqual(
259 run_rust.os.environ["CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER"],
260 str(binaries / "x86_64-w64-mingw32-gcc-posix"),
261 )
262
263 @unittest.skipUnless(sys.platform == "linux", "Linux MinGW 실행 파일 탐색 시험임")
264 def test_default_checkout_reuses_existing_setup_tools(self):
265 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
266 root = Path(directory)
267 tools = root / "tests/ci/tools"
268 binaries = tools / "mingw/usr/bin"
269 binaries.mkdir(parents=True)
270 executable = binaries / "x86_64-w64-mingw32-gcc-posix"
271 executable.write_text("#!/bin/sh\nexit 0\n")
272 executable.chmod(0o700)
273 rustup = tools / "rustup"
274 (rustup / "toolchains/1.99.1-x86_64-unknown-linux-gnu").mkdir(parents=True)
275 with (
276 patch.dict(run_rust.os.environ, {"PATH": ""}, clear=True),
277 patch.object(run_rust.subprocess, "check_output", return_value=str(root / ".git")),
278 ):
279 run_rust.prepare_tools(root)
280 self.assertEqual(run_rust.os.environ["RUSTUP_HOME"], str(rustup))
281 self.assertTrue(run_rust.os.environ["PATH"].startswith(str(binaries)))
282 self.assertEqual(run_rust.shutil.which("x86_64-w64-mingw32-gcc-posix"),
283 str(executable))
284
285 def test_unconfigured_work_directory_uses_common_project(self):
286 with patch.dict(os.environ), patch.object(
287 run_rust, "work_directory", return_value=TEST_WORK
288 ) as directory:
289 os.environ.pop("ZIPELO_TEST_WORK_DIR", None)
290 os.environ.pop("ZIPELO_CI_JOB", None)
291 self.assertEqual(run_rust.test_work_directory(run_rust.ROOT), TEST_WORK)
292 directory.assert_called_once_with(run_rust.ROOT, "rust-local")
293
294 def test_local_bootstraps_missing_cross_tools_and_reloads_paths(self):
295 for root in (Path("/repo"), PurePosixPath("/repo"), PureWindowsPath("C:/repo")):
296 with self.subTest(root=root):
297 with (
298 patch.object(run_rust, "prepare_cross_build", side_effect=[ValueError("missing"), None]) as detect,
299 patch.object(run_rust.subprocess, "run") as setup,
300 patch.object(run_rust, "prepare_tools") as reload,
301 patch.object(run_rust, "test_work_directory", return_value=root / "tests/work/rust-local"),
302 ):
303 run_rust.prepare_local_tools(root)
304 setup.assert_called_once_with(
305 ["bash", str(root / "tests/ci/setup_windows.sh")], cwd=root, env=ANY, check=True,
306 )
307 reload.assert_called_once_with(root)
308 self.assertEqual(detect.call_count, 2)
309
310 def test_existing_cross_tools_do_not_trigger_downloads(self):
311 with (
312 patch.object(run_rust, "prepare_cross_build"),
313 patch.object(run_rust.subprocess, "run") as setup,
314 ):
315 run_rust.prepare_local_tools(Path("/repo"))
316 setup.assert_not_called()
317
318 def test_explicit_tools_directory_does_not_fall_back_to_other_worktree(self):
319 with (
320 patch.dict(run_rust.os.environ, {"PATH": "", "ZIPELO_CI_TOOLS": "/missing"}, clear=True),
321 patch.object(run_rust.subprocess, "check_output") as git,
322 ):
323 run_rust.prepare_tools(Path("/repo"))
324 git.assert_not_called()
325 with self.assertRaisesRegex(ValueError, "setup_windows.sh"):
326 run_rust.prepare_cross_build()
327
328 @unittest.skipUnless(sys.platform == "linux", "Linux 파일시스템과 소유권 검사 시험임")
329 def test_filesystem_skip_is_limited_to_publication_test_crates(self):
330 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
331 root = Path(directory)
332 work = root / "work"
333 work.mkdir()
334 paths = [
335 root / "tests/rust-file-publication/Cargo.toml",
336 root / "tests/rust-gzip-file-job/Cargo.toml",
337 root / "tests/rust-file-snapshot/Cargo.toml",
338 root / "experiments/rust-file-publication/Cargo.toml",
339 ]
340 with (
341 patch.object(run_rust, "manifests", return_value=paths),
342 patch.dict(run_rust.os.environ, {"ZIPELO_TEST_WORK_DIR": str(work)}),
343 patch.object(run_rust.subprocess, "check_output", return_value="1021994\n"),
344 patch.object(run_rust.subprocess, "run", return_value=subprocess.CompletedProcess([], 0)) as cargo,
345 ):
346 results = run_rust.run(root, "test")
347 self.assertEqual([row["status"] for row in results], [
348 "not-applicable", "not-applicable", "passed", "passed",
349 ])
350 self.assertIn("0x1021994", results[0]["reason"])
351 self.assertEqual(cargo.call_count, 2)
352 cargo.reset_mock()
353 results = run_rust.run(root, "cross-build")
354 self.assertTrue(all(row["status"] == "passed" for row in results))
355 self.assertEqual(cargo.call_count, 4)
356
357 @unittest.skipUnless(sys.platform == "linux", "Linux 소켓 경로 회귀 시험임")
358 def test_long_checkout_does_not_block_file_fixtures(self):
359 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
360 root = Path(directory) / ("long-checkout-" * 10)
361 work = Path(directory) / "work"
362 socket = root / "tests/rust-file-publication/runs/case-1-1/parent/output"
363 self.assertGreaterEqual(len(run_rust.os.fsencode(socket)), 108)
364 with (
365 patch.dict(run_rust.os.environ, {"ZIPELO_TEST_WORK_DIR": str(work)}),
366 patch.object(run_rust.subprocess, "check_output", return_value="ef53\n"),
367 ):
368 self.assertEqual(run_rust.prepare_fixtures(root), {})
369 for name in run_rust.FILE_FIXTURES:
370 self.assertEqual(list((work / "fixtures" / name).iterdir()), [])
371 self.assertFalse((root / "tests" / name / "runs").exists())
372
373 def test_unknown_filesystem_probe_error_is_failure(self):
374 with (
375 patch.object(run_rust, "prepare_fixtures", side_effect=subprocess.CalledProcessError(1, "stat")),
376 patch.object(run_rust.sys, "platform", "linux"),
377 ):
378 results = run_rust.execute_phases(run_rust.ROOT, ["test"])
379 self.assertEqual(results[0]["status"], "failed")
380
381 def test_cargo_contract(self):
382 args = run_rust.command(Path("tests/example/Cargo.toml"), "test")
383 self.assertIn("--locked", args)
384 self.assertIn("--all-features", args)
385 self.assertEqual(args[-2:], ["--", "--test-threads=1"])
386
387
388if __name__ == "__main__":
389 unittest.main()