-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_codec.py
More file actions
297 lines (218 loc) · 10.2 KB
/
test_codec.py
File metadata and controls
297 lines (218 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# tests/test_codec.py
import os
import sys
from _base_test import BaseTest, MockTestHelper
from _mocks import MockMachine
# Add parent directory to path to import URST
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from urst.codec import URSTCodec
class TestCodec(BaseTest):
"""Test suite for URST Codec"""
def __init__(self):
super().__init__("Codec")
self.helper = MockTestHelper()
def test_codec(self):
"""Test frame encoding/decoding"""
mock_uart = MockMachine.UART()
codec = URSTCodec(mock_uart)
# Test basic encode/decode
test_data = b"Hello Frame Codec"
bytes_sent = codec.send_frame(test_data)
self.assert_true(bytes_sent > 0, "Frame sent successfully")
# Simulate receiving the same data
mock_uart.rx_buffer = mock_uart.tx_buffer.copy()
mock_uart.rx_pos = 0
received_data = codec.recv_frame()
self.assert_equal(received_data, test_data, "Basic encode/decode roundtrip")
# Test data with zero bytes
mock_uart.tx_buffer.clear()
mock_uart.rx_buffer.clear()
mock_uart.rx_pos = 0
zero_data = b"\x00\x01\x00\x02\x00"
codec.send_frame(zero_data)
mock_uart.rx_buffer = mock_uart.tx_buffer.copy()
mock_uart.rx_pos = 0
received_zero = codec.recv_frame()
self.assert_equal(received_zero, zero_data, "Data with zero bytes")
# Test corrupted CRC
mock_uart.tx_buffer.clear()
mock_uart.rx_buffer.clear()
mock_uart.rx_pos = 0
codec.send_frame(b"test")
corrupted = bytearray(mock_uart.tx_buffer)
corrupted[-2] ^= 0xFF # Corrupt CRC
mock_uart.rx_buffer = bytes(corrupted)
mock_uart.rx_pos = 0
bad_data = codec.recv_frame()
self.assert_equal(bad_data, None, "Corrupted CRC rejected")
def test_cobs_encoding(self):
"""Test COBS encoding specifically"""
mock_uart = MockMachine.UART()
codec = URSTCodec(mock_uart)
# Test that encoded data has no internal zeros
test_cases = [
b"No zeros",
b"\x00\x00\x00", # All zeros
b"Before\x00After", # Zero in middle
b"\x00Start", # Zero at start
b"End\x00", # Zero at end
]
for test_data in test_cases:
mock_uart.tx_buffer.clear()
codec.send_frame(test_data)
# Check encoded frame (between delimiters)
frame = mock_uart.tx_buffer
# Find content between delimiters
if len(frame) >= 3:
content = frame[1:-1] # Strip delimiters
# COBS guarantees no zero bytes in content
has_zeros = 0x00 in content
self.assert_false(has_zeros, f"COBS encoding removes zeros: {test_data!r}")
# Verify roundtrip
mock_uart.rx_buffer = frame.copy()
mock_uart.rx_pos = 0
received = codec.recv_frame()
self.assert_equal(received, test_data, f"COBS roundtrip: {test_data!r}")
def test_crc_validation(self):
"""Test CRC calculation and validation"""
mock_uart = MockMachine.UART()
codec = URSTCodec(mock_uart)
# Test that same data produces same CRC
data1 = b"Test data"
crc1 = codec._calculate_crc(data1)
crc2 = codec._calculate_crc(data1)
self.assert_equal(crc1, crc2, "CRC is consistent")
# Test that different data produces different CRC
data2 = b"Different"
crc3 = codec._calculate_crc(data2)
self.assert_true(crc1 != crc3, "Different data produces different CRC")
# Test CRC detects single bit flip
mock_uart.tx_buffer.clear()
codec.send_frame(b"Important data")
# Flip a bit in the middle
corrupted = bytearray(mock_uart.tx_buffer)
if len(corrupted) > 5:
corrupted[5] ^= 0x01 # Flip one bit
mock_uart.rx_buffer = bytes(corrupted)
mock_uart.rx_pos = 0
result = codec.recv_frame()
self.assert_equal(result, None, "CRC detects bit flip")
def test_empty_send_returns_zero(self):
"""send_frame with empty payload should return 0 bytes written."""
mock_uart = MockMachine.UART()
codec = URSTCodec(mock_uart)
# Empty payload -> nothing should be written
bytes_written = codec.send_frame(b"")
self.assert_equal(bytes_written, 0, "Empty send returns 0")
def test_invalid_cobs_decode_is_handled(self):
"""Invalid COBS content should be handled and return None (no crash)."""
# Craft a frame with an invalid COBS code byte (0x00 inside content)
# Frame format: [0x00][COBS payload][0x00]
invalid_cobs = bytes([0x00, 0x01, 0x02])
raw_frame = bytes([0x00]) + invalid_cobs + bytes([0x00])
mock_uart = MockMachine.UART()
mock_uart.rx_buffer = bytearray(raw_frame)
mock_uart.rx_pos = 0
codec = URSTCodec(mock_uart)
result = codec.recv_frame()
# Should gracefully return None (and not raise), exercising error path
self.assert_none(result, "Invalid COBS returns None")
def test_rx_buffer_overflow_is_trimmed(self):
"""RX buffer should trim to max size when overflowing."""
mock_uart = MockMachine.UART()
# Create large incoming stream with no delimiters to force accumulation
mock_uart.rx_buffer = bytearray(b"A" * 512)
mock_uart.rx_pos = 0
small_max = 32
codec = URSTCodec(mock_uart, rx_buffer_size=small_max)
# Trigger buffer update
_ = codec.recv_frame()
# Internal buffer should not exceed configured max
self.assert_true(len(codec._rx_buffer) <= small_max, "RX buffer trimmed to max size")
def test_empty_cobs_frame_decodes_to_empty_and_is_ignored(self):
"""An empty COBS payload (0x00 0x00) should return None after decode."""
# Build an empty payload frame: [DELIM][cobs(empty) -> 0x00][DELIM]
raw_frame = bytes([0x00, 0x00, 0x00])
mock_uart = MockMachine.UART()
mock_uart.rx_buffer = bytearray(raw_frame)
mock_uart.rx_pos = 0
codec = URSTCodec(mock_uart)
result = codec.recv_frame()
self.assert_none(result, "Empty decoded payload ignored")
def test_send_frame_exception_returns_zero(self):
"""If UART.write raises, send_frame should log and return 0."""
class BoomUART(MockMachine.UART):
def write(self, data):
raise RuntimeError("boom")
codec = URSTCodec(BoomUART())
written = codec.send_frame(b"data")
self.assert_equal(written, 0, "send_frame returns 0 on exception")
def test_cobs_encode_empty_returns_single_zero(self):
"""_cobs_encode of empty bytes returns a single 0x00 byte."""
mock_uart = MockMachine.UART()
codec = URSTCodec(mock_uart)
encoded = codec._cobs_encode(b"")
self.assert_bytes_equal(encoded, b"\x00", "COBS encode empty -> 0x00")
def test_logger_injection_path(self):
"""Providing a custom logger should exercise the else branch in __init__."""
class DummyLogger:
def __init__(self):
self.messages = []
def error(self, message):
self.messages.append(message)
logger = DummyLogger()
codec = URSTCodec(MockMachine.UART(), logger=logger)
# Trigger an error to ensure logger is used
class BoomUART(MockMachine.UART):
def write(self, data):
raise RuntimeError("boom2")
codec.uart = BoomUART()
_ = codec.send_frame(b"x")
self.assert_true(len(logger.messages) >= 1, "Custom logger used for errors")
def test_recv_frame_exception_path(self):
"""Exceptions during recv_frame should be caught and return None."""
class BadUART(MockMachine.UART):
def any(self):
raise RuntimeError("bad any")
codec = URSTCodec(BadUART())
result = codec.recv_frame()
self.assert_none(result, "recv_frame exception path returns NoneXX")
def test_decoded_less_than_two_returns_none(self):
"""If COBS-decoded data is < 2 bytes, recv_frame returns None."""
# Content [0x02, 0xAA] decodes to single byte 0xAA
content = bytes([0x02, 0xAA])
raw_frame = bytes([0x00]) + content + bytes([0x00])
mock_uart = MockMachine.UART()
mock_uart.rx_buffer = bytearray(raw_frame)
mock_uart.rx_pos = 0
codec = URSTCodec(mock_uart)
result = codec.recv_frame()
self.assert_none(result, "Decoded length < 2 yields None")
def test_cobs_decode_invalid_code_zero_returns_none(self):
"""_cobs_decode returns None when first code byte is zero."""
codec = URSTCodec(MockMachine.UART())
out = codec._cobs_decode(b"\x00\x01")
self.assert_true(out is None, "Invalid code 0 returns None")
def test_cobs_encode_block_boundary_0xFF(self):
"""COBS encoding path where code reaches 0xFF and resets."""
mock_uart = MockMachine.UART()
codec = URSTCodec(mock_uart)
# 254 non-zero bytes (e.g., 1..254) followed by a zero to force block close
data = bytes([i % 255 or 1 for i in range(1, 255)]) + b"\x00"
encoded = codec._cobs_encode(data)
self.assert_true(len(encoded) > 0, "COBS encoded output produced")
def test_cobs_decode_empty_input(self):
"""_cobs_decode should return empty bytes for empty input."""
codec = URSTCodec(MockMachine.UART())
out = codec._cobs_decode(b"")
self.assert_bytes_equal(out, b"", "Empty input decodes to empty bytes")
def test_cobs_decode_truncated_block_breaks_gracefully(self):
"""COBS decode loop hits break when block length exceeds remaining bytes."""
codec = URSTCodec(MockMachine.UART())
# code=3 but only one data byte present -> triggers break path
out = codec._cobs_decode(bytes([3, 0xAA]))
self.assert_bytes_equal(out, b"\xaa", "Truncated block handled")
if __name__ == "__main__":
test_suite = TestCodec()
results = test_suite.run_all_tests()
sys.exit(0 if results["failed"] == 0 else 1)