team-ljyzipelo

공개
329줄16 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(run_rust.ROOT, os.environ["ZIPELO_CI_JOB"]), TEST_WORK)
26
27 def test_work_directory_rejects_symlinked_parents_before_creation(self):
28 for link_name in ("tests", "tests/work"):
29 with self.subTest(link_name=link_name), tempfile.TemporaryDirectory(
30 dir=TEST_WORK
31 ) as directory:
32 base = Path(directory)
33 project = base / "project"
34 project.mkdir()
35 outside = base / "outside"
36 outside.mkdir()
37 link = project / link_name
38 link.parent.mkdir(parents=True, exist_ok=True)
39 link.symlink_to(outside, target_is_directory=True)
40 with patch.object(
41 run_rust.subprocess, "check_output", return_value=str(project / ".git")
42 ):
43 with self.assertRaisesRegex(ValueError, "안전한 작업 디렉터리"):
44 run_rust.work_directory(project, "task")
45 self.assertFalse((outside / "task").exists())
46 self.assertFalse((outside / "work").exists())
47
48 def test_output_paths_reject_symlinks_outside_job(self):
49 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
50 work = Path(directory)
51 outside = TEST_WORK / "outside"
52 for name in ("tmp", "target"):
53 with self.subTest(name=name):
54 link = work / name
55 link.symlink_to(outside, target_is_directory=True)
56 with self.assertRaisesRegex(ValueError, "작업 폴더 밖"):
57 run_rust.output_directory(work, name, create=True)
58 self.assertFalse(outside.exists())
59 link.unlink()
60
61 def test_output_paths_allow_symlinks_within_job(self):
62 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
63 work = Path(directory)
64 inner = work / "inner"
65 inner.mkdir()
66 link = work / "tmp"
67 link.symlink_to(inner, target_is_directory=True)
68 self.assertEqual(run_rust.output_directory(work, "tmp", create=True), link)
69
70 def test_cargo_and_temp_paths_are_kept_in_job_directory(self):
71 for key in ("CARGO_TARGET_DIR", "TMPDIR", "TMP", "TEMP", "ZIPELO_TEST_WORK_DIR"):
72 with self.subTest(key=key):
73 self.assertTrue(Path(os.environ[key]).resolve().is_relative_to(TEST_WORK))
74
75 def test_all_manifests_have_locks(self):
76 paths = run_rust.manifests(run_rust.ROOT)
77 expected = set(run_rust.ROOT.glob("experiments/*/Cargo.toml"))
78 expected |= set(run_rust.ROOT.glob("tests/*/Cargo.toml"))
79 self.assertEqual(set(paths), expected)
80
81 def test_failure_does_not_hide_later_crates(self):
82 paths = [
83 Path("/repo/experiments/a/Cargo.toml"),
84 Path("/repo/experiments/b/Cargo.toml"),
85 ]
86 with (
87 patch.object(run_rust, "manifests", return_value=paths),
88 patch.object(run_rust.subprocess, "run", side_effect=[
89 subprocess.CompletedProcess([], 7),
90 subprocess.CompletedProcess([], 0),
91 ]),
92 ):
93 results = run_rust.run(Path("/repo"), "build")
94 self.assertEqual([row["status"] for row in results], ["failed", "passed"])
95 self.assertEqual(results[0]["exit_code"], 7)
96
97 def test_windows_exclusion_is_explicit_and_only_for_linux_tests(self):
98 paths = [
99 Path("/repo/tests/rust-file-publication/Cargo.toml"),
100 Path("/repo/experiments/rust-file-publication/Cargo.toml"),
101 ]
102 with (
103 patch.object(run_rust, "manifests", return_value=paths),
104 patch.object(run_rust.sys, "platform", "win32"),
105 patch.object(
106 run_rust.subprocess, "run",
107 return_value=subprocess.CompletedProcess([], 0),
108 ) as execute,
109 ):
110 results = run_rust.run(Path("/repo"), "test")
111 self.assertEqual(
112 [row["status"] for row in results], ["not-applicable", "passed"]
113 )
114 self.assertEqual(execute.call_count, 1)
115
116 def test_fixture_bytes_match_git_blobs(self):
117 names = subprocess.check_output(
118 ["git", "ls-files", "-z", "tests/**/fixtures/*"], cwd=run_rust.ROOT
119 ).decode("utf-8").split("\0")
120 names = [name for name in names if name]
121 self.assertTrue(names, "검증할 fixture가 없음")
122 for name in names:
123 with self.subTest(path=name):
124 expected = subprocess.check_output(
125 ["git", "show", f"HEAD:{name}"], cwd=run_rust.ROOT
126 )
127 self.assertEqual((run_rust.ROOT / name).read_bytes(), expected)
128
129 def test_cross_build_never_executes_tests(self):
130 args = run_rust.command(Path("tests/example/Cargo.toml"), "cross-build")
131 self.assertEqual(args[2], "build")
132 self.assertIn(run_rust.WINDOWS_TARGET, args)
133 self.assertNotIn("--test-threads=1", args)
134
135 def test_preflight_failure_is_reported_without_hiding_other_phase(self):
136 with (
137 patch.object(run_rust, "prepare_cross_build", side_effect=ValueError("missing linker")),
138 patch.object(run_rust, "run", return_value=[{"manifest": "sample", "status": "passed"}]),
139 ):
140 results = run_rust.execute_phases(Path("/repo"), ["build", "cross-build"])
141 self.assertEqual([row["status"] for row in results], ["passed", "failed"])
142 self.assertEqual(results[1]["reason"], "missing linker")
143
144 def test_self_check_failure_replaces_previous_success_report(self):
145 for phase, platform in (("local", "linux"), ("test", "win32")):
146 with self.subTest(phase=phase), tempfile.TemporaryDirectory(
147 dir=TEST_WORK
148 ) as directory:
149 root = Path(directory)
150 (root / "work/tmp").mkdir(parents=True)
151 report_path = root / f"work/{phase}-results.json"
152 with (
153 patch.object(run_rust, "ROOT", root),
154 patch.object(run_rust, "work_directory", return_value=root / "work"),
155 patch.object(run_rust, "prepare_tools"),
156 patch.object(run_rust, "prepare_local_tools"),
157 patch.object(run_rust.sys, "argv", ["run_rust.py", phase]),
158 patch.object(run_rust.sys, "platform", platform),
159 patch.dict(run_rust.os.environ, {"GITHUB_STEP_SUMMARY": ""}),
160 patch.object(run_rust.subprocess, "run", side_effect=[
161 subprocess.CompletedProcess([], 0),
162 subprocess.CompletedProcess([], 7),
163 ]),
164 patch.object(run_rust.subprocess, "check_output", side_effect=[
165 "successful-head\n", "failed-head\n",
166 ]),
167 patch.object(run_rust, "execute_phases", return_value=[
168 {"phase": "test", "manifest": "sample", "status": "passed"},
169 ]) as execute,
170 redirect_stdout(StringIO()),
171 ):
172 self.assertEqual(run_rust.main(), 0)
173 successful = json.loads(report_path.read_text(encoding="utf-8"))
174 self.assertEqual(successful["results"][0]["status"], "passed")
175 self.assertEqual(run_rust.main(), 7)
176 failed = json.loads(report_path.read_text(encoding="utf-8"))
177 self.assertEqual(failed["head"], "failed-head")
178 self.assertEqual(failed["results"], [{
179 "phase": "self-check",
180 "manifest": "tests/ci",
181 "status": "failed",
182 "exit_code": 7,
183 }])
184 self.assertFalse(failed["windows_runtime_tested"])
185 execute.assert_called_once()
186
187 @unittest.skipUnless(sys.platform == "linux", "Linux MinGW 실행 파일 탐색 시험임")
188 def test_linked_worktree_finds_setup_tools_without_path_export(self):
189 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
190 base = Path(directory)
191 root = base / "linked"
192 tools = base / "tests/ci/tools"
193 binaries = tools / "mingw/usr/bin"
194 binaries.mkdir(parents=True)
195 for name in ("gcc", "g++"):
196 executable = binaries / f"x86_64-w64-mingw32-{name}-posix"
197 executable.write_text("#!/bin/sh\nexit 0\n")
198 executable.chmod(0o700)
199 rustup = tools / "rustup"
200 (rustup / "toolchains/1.99.1-x86_64-unknown-linux-gnu").mkdir(parents=True)
201 with (
202 patch.dict(run_rust.os.environ, {"PATH": ""}, clear=True),
203 patch.object(run_rust.subprocess, "check_output", return_value=str(base / ".git")),
204 ):
205 run_rust.prepare_tools(root)
206 run_rust.prepare_cross_build()
207 self.assertEqual(run_rust.os.environ["RUSTUP_HOME"], str(rustup))
208 self.assertEqual(
209 run_rust.os.environ["CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER"],
210 str(binaries / "x86_64-w64-mingw32-gcc-posix"),
211 )
212
213 @unittest.skipUnless(sys.platform == "linux", "Linux MinGW 실행 파일 탐색 시험임")
214 def test_default_checkout_reuses_existing_setup_tools(self):
215 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
216 root = Path(directory)
217 tools = root / "tests/ci/tools"
218 binaries = tools / "mingw/usr/bin"
219 binaries.mkdir(parents=True)
220 executable = binaries / "x86_64-w64-mingw32-gcc-posix"
221 executable.write_text("#!/bin/sh\nexit 0\n")
222 executable.chmod(0o700)
223 rustup = tools / "rustup"
224 (rustup / "toolchains/1.99.1-x86_64-unknown-linux-gnu").mkdir(parents=True)
225 with (
226 patch.dict(run_rust.os.environ, {"PATH": ""}, clear=True),
227 patch.object(run_rust.subprocess, "check_output", return_value=str(root / ".git")),
228 ):
229 run_rust.prepare_tools(root)
230 self.assertEqual(run_rust.os.environ["RUSTUP_HOME"], str(rustup))
231 self.assertTrue(run_rust.os.environ["PATH"].startswith(str(binaries)))
232 self.assertEqual(run_rust.shutil.which("x86_64-w64-mingw32-gcc-posix"),
233 str(executable))
234
235 def test_local_bootstraps_missing_cross_tools_and_reloads_paths(self):
236 for root in (Path("/repo"), PurePosixPath("/repo"), PureWindowsPath("C:/repo")):
237 with self.subTest(root=root):
238 with (
239 patch.object(run_rust, "prepare_cross_build", side_effect=[ValueError("missing"), None]) as detect,
240 patch.object(run_rust.subprocess, "run") as setup,
241 patch.object(run_rust, "prepare_tools") as reload,
242 ):
243 run_rust.prepare_local_tools(root)
244 setup.assert_called_once_with(
245 ["bash", str(root / "tests/ci/setup_windows.sh")], cwd=root, env=ANY, check=True,
246 )
247 reload.assert_called_once_with(root)
248 self.assertEqual(detect.call_count, 2)
249
250 def test_existing_cross_tools_do_not_trigger_downloads(self):
251 with (
252 patch.object(run_rust, "prepare_cross_build"),
253 patch.object(run_rust.subprocess, "run") as setup,
254 ):
255 run_rust.prepare_local_tools(Path("/repo"))
256 setup.assert_not_called()
257
258 def test_explicit_tools_directory_does_not_fall_back_to_other_worktree(self):
259 with (
260 patch.dict(run_rust.os.environ, {"PATH": "", "ZIPELO_CI_TOOLS": "/missing"}, clear=True),
261 patch.object(run_rust.subprocess, "check_output") as git,
262 ):
263 run_rust.prepare_tools(Path("/repo"))
264 git.assert_not_called()
265 with self.assertRaisesRegex(ValueError, "setup_windows.sh"):
266 run_rust.prepare_cross_build()
267
268 @unittest.skipUnless(sys.platform == "linux", "Linux 파일시스템과 소유권 검사 시험임")
269 def test_filesystem_skip_is_limited_to_publication_test_crates(self):
270 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
271 root = Path(directory)
272 work = root / "work"
273 work.mkdir()
274 paths = [
275 root / "tests/rust-file-publication/Cargo.toml",
276 root / "tests/rust-gzip-file-job/Cargo.toml",
277 root / "tests/rust-file-snapshot/Cargo.toml",
278 root / "experiments/rust-file-publication/Cargo.toml",
279 ]
280 with (
281 patch.object(run_rust, "manifests", return_value=paths),
282 patch.dict(run_rust.os.environ, {"ZIPELO_TEST_WORK_DIR": str(work)}),
283 patch.object(run_rust.subprocess, "check_output", return_value="1021994\n"),
284 patch.object(run_rust.subprocess, "run", return_value=subprocess.CompletedProcess([], 0)) as cargo,
285 ):
286 results = run_rust.run(root, "test")
287 self.assertEqual([row["status"] for row in results], [
288 "not-applicable", "not-applicable", "passed", "passed",
289 ])
290 self.assertIn("0x1021994", results[0]["reason"])
291 self.assertEqual(cargo.call_count, 2)
292 cargo.reset_mock()
293 results = run_rust.run(root, "cross-build")
294 self.assertTrue(all(row["status"] == "passed" for row in results))
295 self.assertEqual(cargo.call_count, 4)
296
297 @unittest.skipUnless(sys.platform == "linux", "Linux 소켓 경로 회귀 시험임")
298 def test_long_checkout_does_not_block_file_fixtures(self):
299 with tempfile.TemporaryDirectory(dir=TEST_WORK) as directory:
300 root = Path(directory) / ("long-checkout-" * 10)
301 work = Path(directory) / "work"
302 socket = root / "tests/rust-file-publication/runs/case-1-1/parent/output"
303 self.assertGreaterEqual(len(run_rust.os.fsencode(socket)), 108)
304 with (
305 patch.dict(run_rust.os.environ, {"ZIPELO_TEST_WORK_DIR": str(work)}),
306 patch.object(run_rust.subprocess, "check_output", return_value="ef53\n"),
307 ):
308 self.assertEqual(run_rust.prepare_fixtures(root), {})
309 for name in run_rust.FILE_FIXTURES:
310 self.assertEqual(list((work / "fixtures" / name).iterdir()), [])
311 self.assertFalse((root / "tests" / name / "runs").exists())
312
313 def test_unknown_filesystem_probe_error_is_failure(self):
314 with (
315 patch.object(run_rust, "prepare_fixtures", side_effect=subprocess.CalledProcessError(1, "stat")),
316 patch.object(run_rust.sys, "platform", "linux"),
317 ):
318 results = run_rust.execute_phases(run_rust.ROOT, ["test"])
319 self.assertEqual(results[0]["status"], "failed")
320
321 def test_cargo_contract(self):
322 args = run_rust.command(Path("tests/example/Cargo.toml"), "test")
323 self.assertIn("--locked", args)
324 self.assertIn("--all-features", args)
325 self.assertEqual(args[-2:], ["--", "--test-threads=1"])
326
327
328if __name__ == "__main__":
329 unittest.main()