65 lines
2.0 KiB
Python
65 lines
2.0 KiB
Python
"""固件工具测试 — 以原始镜像为黄金样本(app/ 只读)。"""
|
|
import zlib
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from tools import fw
|
|
|
|
SAMPLE = Path(__file__).parent.parent / "app" / "firmware-PP_da14585_4.2_CH.img"
|
|
|
|
|
|
@pytest.fixture
|
|
def sample():
|
|
return SAMPLE.read_bytes()
|
|
|
|
|
|
class TestParse:
|
|
def test_header_fields(self, sample):
|
|
info = fw.parse_image(sample)
|
|
assert info["magic"] == 0x7051 # 'pQ'
|
|
assert info["flags"] == 0x01AA
|
|
assert info["body_size"] == len(sample) - 64
|
|
assert info["crc_stored"] == zlib.crc32(sample[64:]) & 0xFFFFFFFF
|
|
|
|
def test_crc_valid(self, sample):
|
|
assert fw.parse_image(sample)["crc_valid"] is True
|
|
|
|
def test_vector_table(self, sample):
|
|
info = fw.parse_image(sample)
|
|
assert info["initial_sp"] == 0x07FD2B58
|
|
assert info["reset_handler"] == 0x07FC0525
|
|
assert info["load_base"] == 0x07FC0000
|
|
|
|
def test_bad_magic_rejected(self):
|
|
with pytest.raises(ValueError):
|
|
fw.parse_image(b"\x00" * 128)
|
|
|
|
def test_bad_crc_reported(self, sample):
|
|
corrupted = bytearray(sample)
|
|
corrupted[100] ^= 0xFF
|
|
assert fw.parse_image(bytes(corrupted))["crc_valid"] is False
|
|
|
|
|
|
class TestPack:
|
|
def test_repack_roundtrip_byte_identical(self, sample):
|
|
"""解包→重打包 == 原文件(字节级)"""
|
|
body = fw.unpack_body(sample)
|
|
assert fw.pack_image(body, flags=0x01AA) == sample
|
|
|
|
def test_pack_computes_crc(self):
|
|
body = b"\x58\x2b\xfd\x07" + b"\x00" * 100
|
|
img = fw.pack_image(body)
|
|
info = fw.parse_image(img)
|
|
assert info["crc_valid"] is True
|
|
assert info["body_size"] == len(body)
|
|
|
|
def test_patch_and_repack(self, sample):
|
|
"""修改体→重打包→CRC 更新且可解析"""
|
|
body = bytearray(fw.unpack_body(sample))
|
|
body[0x1000] ^= 0xAA
|
|
img = fw.pack_image(bytes(body))
|
|
info = fw.parse_image(img)
|
|
assert info["crc_valid"] is True
|
|
assert img != sample
|