| 1 | import argparse |
| 2 | import importlib.util |
| 3 | from pathlib import Path |
| 4 | import struct |
| 5 | import tempfile |
| 6 | import unittest |
| 7 | |
| 8 | ROOT = Path(__file__).resolve().parents[2] |
| 9 | SPEC = importlib.util.spec_from_file_location("windows_installer", ROOT / "packaging/windows/rust/build.py") |
| 10 | MODULE = importlib.util.module_from_spec(SPEC) |
| 11 | SPEC.loader.exec_module(MODULE) |
| 12 | |
| 13 | |
| 14 | class InstallerInputTests(unittest.TestCase): |
| 15 | def setUp(self): |
| 16 | runs = ROOT / "tests/windows-installer/runs" |
| 17 | runs.mkdir(parents=True, exist_ok=True) |
| 18 | self.directory = tempfile.TemporaryDirectory(dir=runs) |
| 19 | self.addCleanup(self.directory.cleanup) |
| 20 | self.root = Path(self.directory.name) |
| 21 | |
| 22 | def test_truncated_and_non_pe_payloads_are_rejected(self): |
| 23 | for content in (b"", b"MZ", b"not an executable" * 8, |
| 24 | b"MZ" + bytes(58) + struct.pack("<I", 65535)): |
| 25 | payload = self.root / "invalid.exe" |
| 26 | payload.write_bytes(content) |
| 27 | with self.assertRaises(ValueError): |
| 28 | MODULE.pe_machine(payload) |
| 29 | |
| 30 | def test_x64_coff_machine_is_read_from_pe_offset(self): |
| 31 | payload = self.root / "header.exe" |
| 32 | payload.write_bytes(b"MZ" + bytes(58) + struct.pack("<I", 128) |
| 33 | + bytes(64) + b"PE\0\0" + struct.pack("<H", 0x8664)) |
| 34 | self.assertEqual(MODULE.pe_machine(payload), 0x8664) |
| 35 | payload.write_bytes(payload.read_bytes()[:128] + b"badPE!") |
| 36 | with self.assertRaises(ValueError): |
| 37 | MODULE.pe_machine(payload) |
| 38 | |
| 39 | def test_existing_output_is_preserved_before_any_build(self): |
| 40 | output = self.root / "output" |
| 41 | output.mkdir() |
| 42 | sentinel = output / "user-data" |
| 43 | sentinel.write_bytes(b"preserve") |
| 44 | args = argparse.Namespace(output=output, target_dir=self.root / "target") |
| 45 | with self.assertRaises(FileExistsError): |
| 46 | MODULE.build(args) |
| 47 | self.assertEqual(sentinel.read_bytes(), b"preserve") |
| 48 | self.assertEqual(list(output.iterdir()), [sentinel]) |
| 49 | self.assertFalse(args.target_dir.exists()) |