"""Game-free extraction boundary regressions: python -I nx2/test_nup_paths.py.""" from contextlib import contextmanager, ExitStack, redirect_stdout import errno import importlib.util import io import os from pathlib import Path import re import stat import struct import subprocess import sys import tempfile import unittest from unittest.mock import patch sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import nup class WriteAttempt(AssertionError): pass @contextmanager def guard_io(root): """Keep unsafe probes inside this fixture, without faking successful metadata reads.""" def normalized(path): path = os.path.normcase(os.path.abspath(path)) # Compare equivalent filesystem paths; keep the original spelling for the real metadata call. if os.name == "nt": if path.startswith("\\\\?\\unc\\"): return "\\\\" + path[8:] if path.startswith("\\\\?\\") and path[5:7] == ":\\": return path[4:] return path roots = {normalized(root), normalized(os.path.realpath(root))} attempts = [] def metadata(function): def checked(path, *args, **kwargs): candidate = normalized(path) for owned in roots: try: common = os.path.commonpath((candidate, owned)) except ValueError: continue if common in (candidate, owned): # realpath may inspect the fixture's ancestors return function(path, *args, **kwargs) raise AssertionError("metadata access outside fixture: %r" % path) return checked def writing(name): def blocked(*args, **kwargs): attempts.append(name) raise WriteAttempt(name) return blocked with ExitStack() as stack: for name in ("stat", "lstat"): stack.enter_context(patch.object(os, name, side_effect=metadata(getattr(os, name)))) for name in ("makedirs", "mkdir", "open", "replace", "rename", "renames", "link", "symlink", "unlink", "remove", "rmdir", "removedirs"): stack.enter_context(patch.object(os, name, side_effect=writing("os." + name))) stack.enter_context(patch("builtins.open", side_effect=writing("builtins.open"))) stack.enter_context(patch.object(io, "open", side_effect=writing("io.open"))) yield attempts def snapshot(root): """Record directories and link targets too; never descend into a link or junction.""" result = {} pending = [root] while pending: for path in pending.pop().iterdir(): info = path.lstat() relative = path.relative_to(root) if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0): result[relative] = ("link", os.readlink(path)) elif stat.S_ISDIR(info.st_mode): result[relative] = ("directory",) pending.append(path) else: result[relative] = ("file", path.read_bytes()) return result class Package: def __init__(self, names, data=b"authored fixture"): self.names, self.data = names, data def walk(self, directory): for name in self.names: yield name, (0, 0, len(self.data), 0, len(self.data)) def copy_to(self, record, output, name): output.write(self.data) class HealingPackage(Package): """The selected update is missing main; the base has an authored module.""" titles = [dict(index=0, id=0, version=0, exefs=0, romfs=1), dict(index=1, id=0, version=1, exefs=2, romfs=3)] file_size, nd, nf = 0, 4, 1 def __init__(self, data=b"NSO0authored module"): super().__init__(["main"], data) def walk(self, directory): if directory == 0: yield from super().walk(directory) def read(self, record, n=None): return self.data if n is None else self.data[:n] class ExtractionPaths(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory() self.addCleanup(self.temporary.cleanup) self.root = Path(self.temporary.name) self.out = self.root / "out" self.out.mkdir() self.sentinel = self.root / "outside.bin" self.sentinel.write_bytes(b"keep outside data") def extract(self, names): return nup.extract(Package(names), {"romfs": 0}, str(self.out), only="romfs", quiet=True) def test_cli_measures_space_at_the_extraction_destination(self): package = Package(["authored.bin"]) package.titles = [dict(index=0, id=0, version=1, exefs=0, romfs=1)] package.file_size, package.nd, package.nf = 0, 2, 1 for destination in (self.out, self.out / "new" / "nested"): with self.subTest(destination=destination), \ patch.object(nup, "Nup", return_value=package), \ patch.object(nup.shutil, "disk_usage", wraps=nup.shutil.disk_usage) as usage, \ patch.object(sys, "argv", ["nup.py", "authored.nup", "--extract", str(destination), "--only", "romfs"]), \ redirect_stdout(io.StringIO()): nup.main() usage.assert_called_once_with(str(self.out.resolve())) self.assertEqual((destination / "romfs" / "authored.bin").read_bytes(), package.data) def heal(self): package = HealingPackage() with redirect_stdout(io.StringIO()): nup.heal(package, package.titles[-1], str(self.out), ["main"]) def unpack(self): # This authored empty-segment NSO exercises the real unpack writer, without compressed game data. raw = bytearray(0x100) raw[:4] = b"NSO0" struct.pack_into("