| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169 |
- """Reproduce startup residual-frame ACK starvation without hardware."""
- import io
- import json
- import types
- import unittest
- from unittest.mock import patch
- from tools import pwm_scope as scope
- ACK = bytes.fromhex('a5 5a 81 00 a6 35')
- GET_ACK = bytes.fromhex('a5 5a 82 00 f5 60')
- # Prefix seen in the user's 22:42:11.630955 BAD_CRC record, ending at SET_ACK.
- USER_RESIDUE = bytes.fromhex('a5 5a 42 56 ' + '00 '*16 + 'a6') + ACK
- class Clock:
- def __init__(self): self.now = 0.0
- def __call__(self): return self.now
- class Wire:
- def __init__(self, clock, initial=(), response=()):
- self.clock = clock
- self.chunks = list(initial)
- self.response = response
- self.writes = []
- @property
- def in_waiting(self):
- return len(self.chunks[0][1]) if self.chunks and self.chunks[0][0] <= self.clock.now else 0
- def read(self, count):
- limit = self.clock.now + 0.05
- if self.chunks and self.chunks[0][0] <= limit:
- due, data = self.chunks.pop(0)
- self.clock.now = max(self.clock.now, due)
- return data
- self.clock.now = limit
- return b''
- def write(self, raw):
- self.writes.append(raw)
- self.chunks.extend((self.clock.now + delta, data) for delta, data in self.response)
- self.chunks.sort(key=lambda x: x[0])
- return len(raw)
- def close(self): pass
- class ScopeStreamTests(unittest.TestCase):
- def setUp(self):
- self.clock = Clock()
- self.wire = Wire(self.clock)
- self.log = io.StringIO()
- self.time_patch = patch.object(scope.time, 'monotonic', self.clock)
- self.serial_patch = patch.dict('sys.modules', {'serial': types.SimpleNamespace(Serial=lambda *a, **k: self.wire)})
- self.time_patch.start(); self.serial_patch.start()
- self.addCleanup(self.time_patch.stop); self.addCleanup(self.serial_patch.stop)
- self.link = scope.Link('fixture', self.log)
- def events(self): return [json.loads(s) for s in self.log.getvalue().splitlines()]
- def test_user_residual_prefix_does_not_hide_valid_set_ack_until_next_auto_frame(self):
- self.wire.response = [(0.004, USER_RESIDUE)]
- self.assertEqual(self.link.request(1, 10), b'')
- self.assertLess(self.clock.now, 0.2)
- self.assertEqual(self.link.partial_timeouts, 1)
- self.assertEqual(len(self.wire.writes), 1) # no retry masking
- self.assertTrue(any(e['event'] == 'RX_PARTIAL_TIMEOUT' for e in self.events()))
- def test_startup_drain_is_before_first_tx_and_raw_bytes_remain_in_log(self):
- self.wire.chunks = [(0, USER_RESIDUE), (0.01, b'old tail')]
- self.link.synchronize(10)
- self.assertEqual(self.wire.writes, [])
- self.assertEqual(self.link.startup_bytes, len(USER_RESIDUE) + 8)
- self.assertEqual(self.link.bad_crc, 0)
- self.assertEqual(self.link.buf, b'')
- raw = b''.join(bytes.fromhex(e['hex']) for e in self.events() if e['event'] == 'STARTUP_RX')
- self.assertEqual(raw, USER_RESIDUE + b'old tail')
- self.wire.response = [(0.004, ACK)]
- self.assertEqual(self.link.request(1, 10), b'')
- def test_fragmented_valid_frame_with_embedded_ack_is_not_reinterpreted(self):
- payload = b'\x55'*12 + ACK + b'\x55'*68
- packet = scope.frame(0x42, payload)
- self.wire.response = [(0.004, packet[:24]), (0.044, packet[24:])]
- with self.assertRaises(TimeoutError): self.link.request(1, 10)
- self.assertEqual(self.link.bad_crc, 0)
- self.assertEqual(self.link.partial_timeouts, 0)
- self.assertIsNone(self.link.last_ack_at)
- def test_host_pause_does_not_discard_a_valid_frame_already_queued(self):
- payload = b'\x55'*12 + ACK + b'\x55'*68
- packet = scope.frame(0x42, payload)
- self.wire.chunks = [(0, packet[:24]), (0.04, packet[24:])]
- self.assertEqual(self.link.receive(), [])
- self.clock.now += 0.5
- self.assertEqual(self.link.receive(), [(0x42, payload)])
- self.assertEqual(self.link.partial_timeouts, 0)
- def test_split_header_and_ack_over_usb_reads(self):
- self.wire.response = [(0.004, ACK[:1]), (0.02, ACK[1:3]), (0.04, ACK[3:])]
- self.assertEqual(self.link.request(1, 10), b'')
- self.assertEqual(self.link.partial_timeouts, 0)
- def test_real_crc_failure_after_sync_is_counted_and_logged(self):
- self.link.synchronize(10)
- bad = bytearray(scope.frame(0x42, bytes(86))); bad[-1] ^= 1
- self.wire.response = [(0.004, bytes(bad) + ACK)]
- self.assertEqual(self.link.request(1, 10), b'')
- self.assertEqual(self.link.bad_crc, 1)
- self.assertTrue(any(e['event'] == 'BAD_CRC' for e in self.events()))
- def test_get_requires_ack_then_data_not_autonomous_data(self):
- wanted = bytes(range(86))
- self.wire.response = [(0.004, scope.frame(0x42, bytes(86))),
- (0.02, GET_ACK + scope.frame(0x42, wanted))]
- self.assertEqual(self.link.request(2, 10), wanted)
- def test_missing_ack_still_times_out_without_retry(self):
- self.wire.response = [(0.004, scope.frame(0x42, bytes(86)))]
- with self.assertRaises(TimeoutError): self.link.request(1, 10)
- self.assertGreaterEqual(self.clock.now, 0.7)
- self.assertEqual(len(self.wire.writes), 1)
- def test_expired_run_never_sends(self):
- with self.assertRaises(TimeoutError): self.link.request(1, 0)
- self.assertEqual(self.wire.writes, [])
- def test_timeout_panel_does_not_claim_good_feed_or_current_match(self):
- lines = scope.render_live_panel(scope.Style(False), cycles=1, total_cycles=900,
- elapsed=31, remaining=869, read_only=False, matches=None,
- outputs=scope.DUTIES, ct=None, errors=1, bad_crc=0,
- diag=None, diag_slots={}, last_error='SET等待应答超时', last_ack_age=31)
- text = '\n'.join(lines)
- self.assertIn('本轮应答未确认', text)
- self.assertIn('通信已超时', text)
- self.assertNotIn('✓', text)
- self.assertNotIn('喂狗正常', text)
- for line in lines: self.assertEqual(scope.disp_width(line), scope.BOX_WIDTH)
- def test_fan_pwm_alternates_5s_50_percent_and_5s_0_percent(self):
- for t in (0.0, 0.5, 1.0, 2.0, 3.0, 4.0, 4.999, 10.0, 14.0):
- self.assertEqual(scope.fan_duty_for_elapsed(t), 50, f"t={t}")
- for t in (5.0, 5.5, 6.0, 7.0, 8.0, 9.0, 9.999, 15.0, 19.0):
- self.assertEqual(scope.fan_duty_for_elapsed(t), 0, f"t={t}")
- self.assertEqual(list(scope.DUTIES[:24]), list(range(1, 25)))
- self.assertEqual(list(scope.DUTIES[24:32]), [50] * 8)
- self.assertEqual(list(scope.DUTIES[32:35]), [33, 34, 35])
- self.assertEqual(list(scope.DUTIES_FAN_ZERO[:24]), list(range(1, 25)))
- self.assertEqual(list(scope.DUTIES_FAN_ZERO[24:32]), [0] * 8)
- self.assertEqual(list(scope.DUTIES_FAN_ZERO[32:35]), [33, 34, 35])
- for expected in (scope.DUTIES, scope.DUTIES_FAN_ZERO):
- lines = scope.render_live_panel(
- scope.Style(False), cycles=6, total_cycles=900,
- elapsed=5.0, remaining=895.0, read_only=False, matches=True,
- outputs=expected, ct=[25] * 9, errors=0, bad_crc=0,
- diag=None, diag_slots={}, last_error=None, last_ack_age=0.1,
- expected_outputs=expected,
- )
- for line in lines:
- self.assertEqual(scope.disp_width(line), scope.BOX_WIDTH)
- def test_resolve_port_follows_replugged_usb1_and_rejects_usb0(self):
- old_path = "/dev/serial/by-path/pci-0000:00:14.0-usb-0:2:1.0-port0"
- new_path = "/dev/serial/by-path/pci-0000:00:14.0-usb-0:3:1.0-port0"
- with patch("os.path.exists", side_effect=lambda p: p == new_path), \
- patch("os.path.realpath", side_effect=lambda p: "/dev/ttyUSB1" if p == new_path else p):
- self.assertEqual(scope.resolve_port(old_path), new_path)
- with patch("os.path.realpath", return_value="/dev/ttyUSB0"):
- with self.assertRaises(RuntimeError):
- scope.resolve_port("/dev/serial/by-path/pci-0000:00:14.0-usb-0:6:1.0-port0")
- if __name__ == '__main__': unittest.main()
|