@@ -16014,6 +16014,117 @@ def test_ubuntu_rootfs_digest_and_erofs_uuid_are_deterministic(self):
1601416014 ubuntu.erofs_uuid(second_digest),
1601516015 )
1601616016
16017+ @staticmethod
16018+ def _python_tree(root: Path, library_name: str) -> Path:
16019+ library = root / "usr" / "lib" / library_name
16020+ (library / "package").mkdir(parents=True)
16021+ (library / "os.py").write_text("PATH = 'os'\n", encoding="utf-8")
16022+ (library / "package" / "__init__.py").write_text(
16023+ "def value():\n return 1\n", encoding="utf-8"
16024+ )
16025+ return library
16026+
16027+ def test_python_precompile_is_deterministic_unchecked_hash_bytecode(self):
16028+ if sys.version_info.releaselevel != "final":
16029+ self.skipTest("byte-compiling needs a final-release interpreter")
16030+ name = f"python{sys.version_info.major}.{sys.version_info.minor}"
16031+ runs: list[dict[str, bytes]] = []
16032+ roots: list[str] = []
16033+ for _ in range(2):
16034+ with tempfile.TemporaryDirectory() as temporary:
16035+ root = Path(temporary)
16036+ roots.append(str(root))
16037+ library = self._python_tree(root, name)
16038+ ubuntu.precompile_python(root)
16039+ runs.append(
16040+ {
16041+ path.relative_to(library).as_posix(): path.read_bytes()
16042+ for path in sorted(library.rglob("*.pyc"))
16043+ }
16044+ )
16045+ self.assertEqual(len(runs[0]), 2)
16046+ self.assertEqual(runs[0], runs[1])
16047+ for relative, data in runs[0].items():
16048+ with self.subTest(relative=relative):
16049+ # Bytes 4..8 are the flags: 0b01 is a hash-based file that is
16050+ # not checked against its source.
16051+ self.assertEqual(int.from_bytes(data[4:8], "little"), 0b01)
16052+ # The recorded source path is the one inside the guest, never the
16053+ # build directory.
16054+ os_module = runs[0][f"__pycache__/os.{sys.implementation.cache_tag}.pyc"]
16055+ guest_path = os.path.join(f"/usr/lib/{name}", "os.py")
16056+ self.assertIn(guest_path.encode(), os_module)
16057+ for run, root in zip(runs, roots, strict=True):
16058+ for data in run.values():
16059+ self.assertNotIn(root.encode(), data)
16060+
16061+ def _precompile_in_subprocess(
16062+ self, root: Path, *interpreter_flags: str, env: Mapping[str, str] | None = None
16063+ ) -> None:
16064+ code = (
16065+ "import sys; from pathlib import Path; "
16066+ "from nvx_tools import ubuntu; "
16067+ "ubuntu.precompile_python(Path(sys.argv[1]))"
16068+ )
16069+ scripts = Path(__file__).resolve().parent
16070+ environment = {**os.environ, "PYTHONPATH": str(scripts), **(env or {})}
16071+ subprocess.run(
16072+ [sys.executable, *interpreter_flags, "-c", code, str(root)],
16073+ check=True,
16074+ env=environment,
16075+ )
16076+
16077+ def test_python_precompile_ignores_the_build_optimization_level(self):
16078+ if sys.version_info.releaselevel != "final":
16079+ self.skipTest("byte-compiling needs a final-release interpreter")
16080+ name = f"python{sys.version_info.major}.{sys.version_info.minor}"
16081+ with tempfile.TemporaryDirectory() as temporary:
16082+ root = Path(temporary)
16083+ library = self._python_tree(root, name)
16084+ self._precompile_in_subprocess(root, "-O")
16085+ names = sorted(path.name for path in library.rglob("*.pyc"))
16086+ tag = sys.implementation.cache_tag
16087+ self.assertEqual(names, [f"__init__.{tag}.pyc", f"os.{tag}.pyc"])
16088+
16089+ def test_python_precompile_ignores_the_build_cache_prefix(self):
16090+ if sys.version_info.releaselevel != "final":
16091+ self.skipTest("byte-compiling needs a final-release interpreter")
16092+ name = f"python{sys.version_info.major}.{sys.version_info.minor}"
16093+ with tempfile.TemporaryDirectory() as temporary:
16094+ root = Path(temporary) / "root"
16095+ prefix = Path(temporary) / "host-cache"
16096+ library = self._python_tree(root, name)
16097+ self._precompile_in_subprocess(
16098+ root, env={"PYTHONPYCACHEPREFIX": str(prefix)}
16099+ )
16100+ self.assertEqual(len(list(library.rglob("*.pyc"))), 2)
16101+ # The interpreter that runs this build imports its own modules
16102+ # under the prefix; only the root's modules, which the prefix
16103+ # mirrors under the root's own path, must stay out of it.
16104+ leaked = [
16105+ p
16106+ for p in prefix.rglob("*.pyc")
16107+ if Path(temporary).name in p.relative_to(prefix).parts
16108+ ]
16109+ self.assertEqual(leaked, [])
16110+
16111+ def test_python_precompile_needs_the_matching_interpreter(self):
16112+ with tempfile.TemporaryDirectory() as temporary:
16113+ root = Path(temporary)
16114+ self._python_tree(root, f"python3.{sys.version_info.minor + 1}")
16115+ with self.assertRaisesRegex(
16116+ common.ScriptError, "needs a final-release Python"
16117+ ):
16118+ ubuntu.precompile_python(root)
16119+
16120+ def test_python_precompile_ignores_a_root_without_python(self):
16121+ with tempfile.TemporaryDirectory() as temporary:
16122+ root = Path(temporary)
16123+ ubuntu.precompile_python(root)
16124+ (root / "usr" / "lib").mkdir(parents=True)
16125+ ubuntu.precompile_python(root)
16126+ self.assertEqual(sorted(root.rglob("*.pyc")), [])
16127+
1601716128 def test_ubuntu_prepare_root_normalizes_root_directory_mode(self):
1601816129 with tempfile.TemporaryDirectory() as temporary:
1601916130 temporary_root = Path(temporary)
0 commit comments