Files
nvdriver/tests/test_native_shader_receipt.py

85 lines
3.3 KiB
Python

"""Exercise the native shader receipt checks with files in a relocated checkout."""
import contextlib
import io
import json
from pathlib import Path
import runpy
import shutil
import sys
import tempfile
import types
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
SCRIPT = "tools/check_native_shader.py"
CHECKPOINT = Path("reports/checkpoints/native-hello-baseline-2da2fe783377")
RECEIPT = CHECKPOINT / "reports/native-hello-original-580/validation.json"
CUBIN = CHECKPOINT / "target/hardware-hello/native_hello.sm70.cubin"
SOURCE = Path("tests/hardware/native_hello.cu")
EMBEDDED = Path("src/nvidia/src/compute/native_hello_sm70.bin")
class ReceiptTests(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
self.root = Path(directory.name) / "different checkout"
for fixture in (SCRIPT, RECEIPT, CUBIN, SOURCE, EMBEDDED):
destination = self.root / fixture
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ROOT / fixture, destination)
self.receipt = json.loads((self.root / RECEIPT).read_text())
def audit(self):
def elf_fixture(_stream):
# Receipt checks are independent of ELF parsing. Stub that
# optional dependency while keeping the real file hashes.
embedded = (self.root / EMBEDDED).read_bytes()
class TextSection(dict):
def data(self):
return embedded
sections = {
".text.native_hello": TextSection(sh_addralign=128, sh_info=8 << 24),
".nv.constant0.native_hello": types.SimpleNamespace(data=lambda: bytes(368)),
}
return types.SimpleNamespace(get_section_by_name=sections.get, iter_sections=lambda: [])
(self.root / RECEIPT).write_text(json.dumps(self.receipt))
module = types.SimpleNamespace(ELFFile=elf_fixture)
with (
patch.dict(sys.modules, {"elftools.elf.elffile": module}),
contextlib.redirect_stdout(io.StringIO()),
):
runpy.run_path(str(self.root / SCRIPT), run_name="__main__")
return json.loads((self.root / "reports/native-shader-baseline-check.json").read_text())
def test_archive_receipt_survives_checkout_relocation(self):
self.assertIs(self.audit()["passed"], True)
def use_local_source_path(self):
artifacts = self.receipt["artifacts"]
source_key = next(path for path in artifacts if path.endswith(str(SOURCE)))
artifacts[str((self.root / SOURCE).resolve())] = artifacts.pop(source_key)
def test_receipt_without_runs_cannot_pass(self):
self.use_local_source_path()
self.receipt["runs"] = []
with self.assertRaisesRegex(SystemExit, "runs are missing or incomplete"):
self.audit()
def test_receipt_must_identify_the_same_cubin(self):
self.use_local_source_path()
artifacts = self.receipt["artifacts"]
cubin_key = next(path for path in artifacts if path.endswith(CUBIN.name))
artifacts[cubin_key] = "0" * 64
with self.assertRaisesRegex(SystemExit, "identifies a different cubin"):
self.audit()
if __name__ == "__main__":
unittest.main()