import os import sys # Add src to path sys.path.append(os.path.join(os.getcwd(), 'src')) from teletext.models import Packet, Page from teletext.io import load_t42, save_t42 def create_dummy_t42(filename): # Create a 42-byte packet # Byte 0: Mag 1, Row 0. # M=1 (001), R=0 (00000) # Encoded: # B1: M1 M2 M3 R1 -> 1 0 0 0. With Hamming: P1, D1(1), P2, D2(0), P3, D3(0), P4, D4(0) # D1=1 -> P1=1 (1,3,5,7 parity). # Actually let's use a simpler way or pre-calculated bytes for testing. # Magazine 1, Row 0 is often: 0x15 0x15 (example guess, need real hamming) # Let's simple write 42 zero bytes, then set some manually to test "parsing" robustness # or just trust the load/save loop for raw data conservation. # We'll create a "Header" packet (Row 0) and a "Content" packet (Row 1). # Packet 1: Row 0. # We need to construct bytes that pass our minimal decoder. # decode_common: returns D1..D4 for bits 1,3,5,7. # Mag=1 => 001. R=0 => 00000. # B1 (Low row bits + Mag): M1, M2, M3, R1 -> 1, 0, 0, 0 # D1=1, D2=0, D3=0, D4=0. # Byte value: x1x0x0x0. # B2 (High row bits): R2, R3, R4, R5 -> 0, 0, 0, 0 # Byte value: x0x0x0x0. # Let's arbitrarily set parity bits to 0 for this test as my decoder ignores them (it only reads D bits). # B1: 0 1 0 0 0 0 0 0 -> 0x02 # B2: 0 0 0 0 0 0 0 0 -> 0x00 p1_data = bytearray(42) p1_data[0] = 0x02 p1_data[1] = 0x00 # Add some text in the rest p1_data[2:] = b'Header Packet' + b'\x00' * (40 - 13) # Packet 2: Row 1. # M=1, R=1. # B1: M1 M2 M3 R1 -> 1 0 0 1 # D1=1, D2=0, D3=0, D4=1. # Byte: x1x0x0x1 -> 0x82 (if bit 7 is D4). # Position: 0(P1) 1(D1-b0) 2(P2) 3(D2-b1) 4(P3) 5(D3-b2) 6(P4) 7(D4-b3) # My decoder keys off D1(bit1), D2(bit3), D3(bit5), D4(bit7). # So we want bits 1 and 7 set. 0x82 = 1000 0010. Correct. p2_data = bytearray(42) p2_data[0] = 0x82 p2_data[1] = 0x00 # Row high bits 0 p2_data[2:] = b'Content Row 1' + b'\x00' * (40 - 13) with open(filename, 'wb') as f: f.write(p1_data) f.write(p2_data) print(f"Created {filename}") def test_load_save(): fname = "test.t42" out_fname = "test_out.t42" create_dummy_t42(fname) service = load_t42(fname) print(f"Loaded {len(service.all_packets)} packets") print(f"Loaded {len(service.pages)} pages") if len(service.pages) > 0: p = service.pages[0] print(f"Page 0: Mag {p.magazine} Num {p.page_number}") print(f"Packets in page: {len(p.packets)}") save_t42(out_fname, service) # Verify binary identity with open(fname, 'rb') as f1, open(out_fname, 'rb') as f2: b1 = f1.read() b2 = f2.read() if b1 == b2: print("SUCCESS: Output matches input") else: print("FAILURE: Output differs") print(f"In: {len(b1)}, Out: {len(b2)}") if __name__ == "__main__": test_load_save()