team-ljyzipelo

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