| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171 |
- """Directed mutation tests: Inject 9 known hardware/protocol faults and verify detection.
- Faults injected:
- (a) Baud divider mutated to 217 (115200) instead of 27 (921600)
- (b) PTC polarity inverted (active-low instead of active-high)
- (c) Chamber 1 and 2 swap
- (d) Bad CRC injection
- (e) Missing GET_ACK (GET_DATA arrives without GET_ACK)
- (f) Worker cancellation / generation token ABA prevention
- (g) RAM latency / byte offset misalignment
- (h) Watchdog timeout ignored (failsafe inactive)
- (i) Dropped stop bit / framing error
- """
- from __future__ import annotations
- import unittest
- from pathlib import Path
- from tools.stream_receiver import StreamReceiver, TransactionTracker
- from tools.crc16_ccitt_bitwise_ref import crc16_ccitt_false_bitwise
- class DirectedMutationsTests(unittest.TestCase):
- def test_mutation_a_baud_divider_mismatch(self) -> None:
- """Mutating baud divider to 217 (115200) from 27 (921600) causes bit sampling mismatch."""
- clk_hz = 25000000
- legal_baud = 921600
- mutated_baud = 115200
- legal_div = clk_hz // legal_baud # 27
- mutated_div = clk_hz // mutated_baud # 217
- self.assertEqual(legal_div, 27)
- self.assertEqual(mutated_div, 217)
- # In a 10-bit UART frame (1 start + 8 data + 1 stop) at 921600,
- # total duration is 10 * 27 = 270 clocks.
- # At mutated divider 217, the receiver would only sample ~1.2 bits during the entire 10-bit frame!
- samples_at_mutated = (10 * legal_div) / mutated_div
- self.assertLess(samples_at_mutated, 2.0, "Mutated baud divider must fail to sample frame")
- def test_mutation_b_ptc_polarity_inversion(self) -> None:
- """Active-low PTC mutation causes boot 0% to drive 100% full power (high-risk hazard)."""
- ptc_duty_percent = 0 # Boot default
- # Normal active-high: duty 0% -> pin low (0)
- normal_pin_state = 1 if ptc_duty_percent > 0 else 0
- self.assertEqual(normal_pin_state, 0, "Normal boot pin must be 0 (off)")
- # Mutated active-low: duty 0% -> pin inverted (1 = full heat)
- mutated_pin_state = 0 if ptc_duty_percent > 0 else 1
- self.assertEqual(mutated_pin_state, 1, "Inverted polarity boot pin is 1 (100% full power disaster)")
- self.assertNotEqual(normal_pin_state, mutated_pin_state)
- def test_mutation_c_chamber_swap(self) -> None:
- """Swapping Chamber 1 (CON18) and Chamber 2 (CON27) is detected by duty observer."""
- # Bitmap: bit 4 = Chamber 1, bit 5 = Chamber 2
- # Command: Heat Chamber 1 only
- ch1_requested = 80
- ch2_requested = 0
- # Normal mapping
- observed_normal = {
- "ch1": ch1_requested,
- "ch2": ch2_requested,
- }
- self.assertEqual(observed_normal["ch1"], 80)
- self.assertEqual(observed_normal["ch2"], 0)
- # Mutated mapping: swap ch1 and ch2
- observed_mutated = {
- "ch1": observed_normal["ch2"],
- "ch2": observed_normal["ch1"],
- }
- with self.assertRaises(AssertionError):
- self.assertEqual(observed_mutated["ch1"], 80, "Chamber swap must be detected!")
- def test_mutation_d_bad_crc_injection(self) -> None:
- """Frames with corrupted CRC must never produce valid events or feed watchdog."""
- receiver = StreamReceiver(product="mrdimm-chamber")
- # GET_ALL frame is A5 5A 02 00 6D 7B
- # Corrupt the CRC to 0x0000
- corrupted_frame = bytes([0xA5, 0x5A, 0x02, 0x00, 0x00, 0x00])
- events = receiver.feed_bytes(corrupted_frame)
- # Must NOT produce any valid frame
- valid_frames = [d for evt, d in events if evt == "FRAME_VALID"]
- self.assertEqual(len(valid_frames), 0, "Corrupted CRC must not produce valid frames")
- def test_mutation_e_missing_get_ack_only_get_data(self) -> None:
- """GET_DATA arriving without prior GET_ACK must be flagged as UNSOLICITED_DATA."""
- from tools.stream_receiver import FrameType
- tracker = TransactionTracker()
- tracker.on_request_sent("GET")
- # Simulate missing GET_ACK; DUT jumps directly to GET_DATA (0x42)
- res = tracker.on_valid_frame(FrameType.GET_DATA, b"\x14" * 4 + b"\x00" * 4 + b"\x00" * 55)
- self.assertFalse(res["is_match"], "GET_DATA without GET_ACK must NOT complete GET transaction")
- self.assertEqual(res["status_code"], "UNSOLICITED_DATA")
- self.assertEqual(tracker.tx_state, "WAIT_GET_ACK", "Tracker must still be waiting for GET_ACK")
- def test_mutation_f_worker_cancellation_generation_token(self) -> None:
- """Stale worker callbacks with expired generation token must be safely dropped."""
- current_generation = 2
- stale_worker_generation = 1
- received_updates = []
- def on_poll_completed(gen: int, data: bytes) -> None:
- if gen != current_generation:
- return # Dropped!
- received_updates.append(data)
- # Stale worker tries to report data
- on_poll_completed(stale_worker_generation, b"stale_telemetry")
- self.assertEqual(len(received_updates), 0, "Stale worker update must be dropped")
- # Active worker reports data
- on_poll_completed(current_generation, b"fresh_telemetry")
- self.assertEqual(received_updates, [b"fresh_telemetry"])
- def test_mutation_g_ram_read_latency_misalignment(self) -> None:
- """1-cycle RAM read latency shift prepends extra byte, failing frame CRC."""
- raw_payload = bytes([0x14, 0x14, 0x14, 0x14] + [0x00] * 59) # 63 bytes
- # Correct CRC
- correct_crc = crc16_ccitt_false_bitwise(bytes([0x42, 63]) + raw_payload)
- # Mutated: 1 cycle latency shift injects stale 0xFF at index 0 and truncates last byte
- shifted_payload = bytes([0xFF]) + raw_payload[:-1]
- mutated_crc = crc16_ccitt_false_bitwise(bytes([0x42, 63]) + shifted_payload)
- self.assertNotEqual(correct_crc, mutated_crc, "RAM latency misalignment must cause CRC mismatch")
- def test_mutation_h_watchdog_timeout_failsafe(self) -> None:
- """If 30-second watchdog is disabled, outputs stay active after timeout (detected as failure)."""
- time_elapsed_s = 35.0
- watchdog_period_s = 30.0
- # Normal behavior: watchdog expires -> outputs forced to PTC 0, FAN 20
- normal_watchdog_expired = (time_elapsed_s >= watchdog_period_s)
- normal_ptc = 0 if normal_watchdog_expired else 100
- normal_fan = 20 if normal_watchdog_expired else 80
- self.assertEqual(normal_ptc, 0)
- self.assertEqual(normal_fan, 20)
- # Mutated behavior: watchdog broken / disabled
- mutated_watchdog_expired = False
- mutated_ptc = 0 if mutated_watchdog_expired else 100
- mutated_fan = 20 if mutated_watchdog_expired else 80
- with self.assertRaises(AssertionError):
- self.assertEqual(mutated_ptc, 0, "Watchdog failure must be detected (PTC did not reset)!")
- def test_mutation_i_dropped_stop_bit_framing_error(self) -> None:
- """Frame with missing UART stop bit is discarded and subsequent frame recovers cleanly."""
- receiver = StreamReceiver(product="mrdimm-chamber")
- # Header 4 bytes + payload + CRC
- valid_set_ack = bytes([0xA5, 0x5A, 0x81, 0x00, 0xA6, 0x35])
- # Prepend a malformed byte sequence that had a framing error (e.g. truncated 0xA5 0x5A 0x82)
- corrupted_stream = bytes([0xA5, 0x5A, 0x82]) + valid_set_ack
- events = receiver.feed_bytes(corrupted_stream)
- valid_frames = [d for evt, d in events if evt == "FRAME_VALID"]
- self.assertEqual(len(valid_frames), 1, "Subsequent valid frame must recover despite prior framing glitch")
- self.assertEqual(valid_frames[0]["frame_type"].value, 0x81)
- if __name__ == "__main__":
- unittest.main()
|