team-ljyzipelo

공개
123줄6.1 KB
1import gzip
2import importlib.util
3import io
4import os
5import subprocess
6import sys
7from pathlib import Path
8import tarfile
9import tempfile
10import unittest
11from unittest.mock import patch
12import zipfile
13
14
15ROOT = Path(__file__).resolve().parents[2]
16SPEC = importlib.util.spec_from_file_location(
17 "large_fixture_generator", ROOT / "tests/large-archive-fixtures/generate.py"
18)
19GENERATOR = importlib.util.module_from_spec(SPEC)
20SPEC.loader.exec_module(GENERATOR)
21
22
23class LargeArchiveFixtureTests(unittest.TestCase):
24 def test_standalone_generator_uses_common_work_directory(self):
25 expected = Path(os.environ["ZIPELO_TEST_WORK_DIR"])
26 with tempfile.TemporaryDirectory(dir=expected) as scratch:
27 relative = Path(scratch).name + "/corpus"
28 environment = dict(os.environ, ZIPELO_CI_JOB=expected.name)
29 environment.pop("ZIPELO_TEST_WORK_DIR", None)
30 result = subprocess.run(
31 ["python3", str(ROOT / "tests/large-archive-fixtures/generate.py"),
32 "--output", relative],
33 cwd=ROOT, env=environment, capture_output=True, text=True, check=True,
34 )
35 self.assertTrue((Path(scratch) / "corpus/expectations.json").is_file())
36 self.assertIn("11 cases", result.stdout)
37
38 def test_standalone_verifier_uses_work_target(self):
39 job = Path(os.environ["ZIPELO_TEST_WORK_DIR"]).name
40 with patch.dict(os.environ, {"ZIPELO_CI_JOB": job}), patch.dict(sys.modules, {"generate": GENERATOR}):
41 os.environ.pop("ZIPELO_TEST_WORK_DIR", None)
42 os.environ.pop("CARGO_TARGET_DIR", None)
43 spec = importlib.util.spec_from_file_location(
44 "large_fixture_verifier", ROOT / "tests/large-archive-fixtures/verify.py"
45 )
46 verifier = importlib.util.module_from_spec(spec)
47 spec.loader.exec_module(verifier)
48 self.assertEqual(verifier.default_target(), GENERATOR.work_root() / "target/debug")
49
50 def test_boundary_archives_are_valid_and_expectations_straddle_limit(self):
51 with tempfile.TemporaryDirectory(dir=os.environ["ZIPELO_TEST_WORK_DIR"]) as scratch:
52 directory = Path(scratch) / "corpus"
53 manifest = GENERATOR.build(directory)
54 self.assertEqual(len(manifest["cases"]), 11)
55 self.assertFalse(manifest["worker_execution_verified"])
56 for name in ("boundary.zip", "boundary.tar.gz"):
57 artifact = manifest["artifacts"][name]
58 path = directory / name
59 self.assertEqual(GENERATOR.digest(path), artifact["sha256"])
60 if name.endswith(".zip"):
61 with zipfile.ZipFile(path) as archive:
62 self.assertIsNone(archive.testzip())
63 payload = archive.read(GENERATOR.NAME)
64 decoded = len(payload)
65 else:
66 data = gzip.decompress(path.read_bytes())
67 decoded = len(data)
68 with tarfile.open(fileobj=io.BytesIO(data), mode="r:") as archive:
69 payload = archive.extractfile(GENERATOR.NAME).read()
70 self.assertEqual(payload, bytes(artifact["payload_bytes"]))
71 self.assertEqual(decoded, artifact["decoded_bytes"])
72 self.assertEqual(decoded, 65536)
73 self.assertGreater(decoded / artifact["archive_bytes"], 100)
74 for case in manifest["cases"]:
75 decoded = manifest["artifacts"][case["file"]]["decoded_bytes"]
76 exceeded = GENERATOR.violations(manifest["artifacts"][case["file"]], case["limits"])
77 self.assertEqual(exceeded, case["violated_limits"])
78 self.assertLessEqual(len(exceeded), 1)
79 self.assertEqual(case["limits"]["input"], 2 ** 64 - 1)
80 failed = bool(exceeded)
81 self.assertEqual(case["expected"]["error"], "Limit" if failed else "None")
82 self.assertEqual(case["expected"]["created_count"], 0 if failed else 1)
83
84 def test_former_ratio_samples_all_expect_success(self):
85 with tempfile.TemporaryDirectory(dir=os.environ["ZIPELO_TEST_WORK_DIR"]) as scratch:
86 manifest = GENERATOR.build(Path(scratch) / "corpus")
87 for suffix, delta in (("below", -1), ("equal", 0), ("above", 1)):
88 name = "ratio-" + suffix + ".gz"
89 artifact = manifest["artifacts"][name]
90 self.assertEqual(artifact["decoded_bytes"] - 1000 * artifact["ratio_input_bytes"], delta)
91 self.assertLess(artifact["decoded_bytes"], GENERATOR.OUTPUT_LIMIT)
92 case = next(c for c in manifest["cases"] if c["file"] == name)
93 self.assertEqual(case["expected"]["outcome"], "Completed")
94 self.assertIsNone(manifest["policy"]["ratio"])
95 payload = gzip.decompress((Path(scratch) / "corpus" / name).read_bytes())
96 self.assertEqual(payload, bytes(artifact["payload_bytes"]))
97
98 def test_generator_rejects_existing_destination_without_changes(self):
99 with tempfile.TemporaryDirectory(dir=os.environ["ZIPELO_TEST_WORK_DIR"]) as scratch:
100 directory = Path(scratch)
101 marker = directory / "keep"
102 marker.write_bytes(b"preserve")
103 with self.assertRaises(FileExistsError):
104 GENERATOR.build(directory)
105 self.assertEqual(list(directory.iterdir()), [marker])
106 self.assertEqual(marker.read_bytes(), b"preserve")
107
108 def test_generator_requires_project_test_directory(self):
109 with self.assertRaises(ValueError):
110 GENERATOR.build(Path(os.environ["ZIPELO_TEST_WORK_DIR"]).parent / "outside-tests")
111
112 def test_payload_source_enforces_bounded_reads(self):
113 source = GENERATOR.ZeroStream(GENERATOR.GIB)
114 with self.assertRaises(ValueError):
115 source.read()
116 with self.assertRaises(ValueError):
117 source.read(GENERATOR.CHUNK + 1)
118 self.assertEqual(source.read(GENERATOR.CHUNK), bytes(GENERATOR.CHUNK))
119 self.assertEqual(source.remaining, GENERATOR.GIB - GENERATOR.CHUNK)
120
121
122if __name__ == "__main__":
123 unittest.main()