team-ljyzipelo

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