import { describe, it, expect } from 'vitest'; import { encodeTPKT, parseTPKTHeader, isValidTPKTHeader } from '../../src/protocol/tpkt.js'; import { TPKT_VERSION, TPKT_HEADER_LEN } from '../../src/protocol/constants.js'; describe('TPKT', () => { describe('encodeTPKT', () => { it('should encode empty payload', () => { const payload = Buffer.alloc(0); const frame = encodeTPKT(payload); expect(frame.length).toBe(4); expect(frame[0]).toBe(TPKT_VERSION); expect(frame[1]).toBe(0x00); expect(frame.readUInt16BE(2)).toBe(4); // length = header + empty payload }); it('should encode payload with data', () => { const payload = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05]); const frame = encodeTPKT(payload); expect(frame.length).toBe(9); expect(frame[0]).toBe(TPKT_VERSION); expect(frame[1]).toBe(0x00); expect(frame.readUInt16BE(2)).toBe(9); expect(frame.subarray(4)).toEqual(payload); }); it('should encode large payload', () => { const payload = Buffer.alloc(1000, 0xAB); const frame = encodeTPKT(payload); expect(frame.length).toBe(1004); expect(frame.readUInt16BE(2)).toBe(1004); expect(frame.subarray(4).length).toBe(1000); }); }); describe('parseTPKTHeader', () => { it('should parse valid header', () => { const header = Buffer.from([0x03, 0x00, 0x00, 0x08]); const result = parseTPKTHeader(header); expect(result.version).toBe(TPKT_VERSION); expect(result.length).toBe(8); }); it('should parse maximum length', () => { const header = Buffer.from([0x03, 0x00, 0xFF, 0xFF]); const result = parseTPKTHeader(header); expect(result.length).toBe(65535); }); }); describe('isValidTPKTHeader', () => { it('should return true for valid header', () => { const header = Buffer.from([0x03, 0x00, 0x00, 0x08]); expect(isValidTPKTHeader(header)).toBe(true); }); it('should return false for wrong version', () => { const header = Buffer.from([0x02, 0x00, 0x00, 0x08]); expect(isValidTPKTHeader(header)).toBe(false); }); it('should return false for too short buffer', () => { const header = Buffer.from([0x03, 0x00]); expect(isValidTPKTHeader(header)).toBe(false); }); }); describe('roundtrip', () => { it('should roundtrip encode and parse', () => { const payload = Buffer.from([0xE0, 0x01, 0x02]); const frame = encodeTPKT(payload); const parsed = parseTPKTHeader(frame); expect(parsed.version).toBe(TPKT_VERSION); expect(parsed.length).toBe(frame.length); expect(frame.subarray(TPKT_HEADER_LEN)).toEqual(payload); }); }); });