"""协议层单元测试:帧/价格差分/浮点/命令解析(黄金字节向量,对照 easy-tdx 已验证实现)""" from __future__ import annotations import struct import pytest from pytdxdata.protocol.frame import FrameHeader, decompress_body, parse_header from pytdxdata.protocol.price import get_price, put_price, decode_ohlc_diffs from pytdxdata.protocol.volume import decode_volume from pytdxdata.protocol.commands.ex_proto import GetExInstrumentBarsCmd from pytdxdata.protocol.commands.kline import GetSecurityBarsCmd from pytdxdata.protocol.commands.minute import GetHistoryMinuteTimeDataCmd from pytdxdata.protocol.commands.transaction import MacTransactionCmd # ---------- 变长有符号整数 ---------- @pytest.mark.parametrize("value", [0, 1, -1, 63, 64, -64, 127, -128, 1000, -100000, 2**20]) def test_price_roundtrip(value: int): enc = put_price(value) dec, pos = get_price(enc, 0) assert dec == value assert pos == len(enc) def test_price_negative_flag(): # 首字节 bit6=符号 enc = put_price(-5) assert enc[0] & 0x40 dec, _ = get_price(enc, 0) assert dec == -5 # ---------- OHLC 差分还原 ---------- def test_decode_ohlc_diffs(): # 手工构造:open_diff=100, close_diff=-20, high_diff=10, low_diff=-30 body = bytearray() for v in (100, -20, 10, -30): body.extend(put_price(v)) od, cd, hd, ld, pos = decode_ohlc_diffs(body, 0) assert (od, cd, hd, ld) == (100, -20, 10, -30) assert pos == len(body) # ---------- 自定义4字节浮点 ---------- def test_decode_volume_zero(): assert decode_volume(0) == 0.0 def test_decode_volume_known(): # 经验值:0x00000001 应为极小正数(非0) assert decode_volume(1) > 0 # ---------- 响应帧头 ---------- def test_frame_header(): # magic=7654321, 未压缩: zipsize==unzipsize buf = struct.pack(" bytes: """构造 0x23FF 响应体:20B头(count@18) + 每条32B(4B时间 + 28B行情)。""" body = bytearray(20 + len(raw_dates) * 32) struct.pack_into("