"""cocotb tests for crc.sv: check value and random messages against crc_model.py. The CRC variant is chosen from the width of crc_out, so one test module covers every build made by test_cocotb_crc.py. """ from __future__ import annotations import random import cocotb from cocotb.clock import Clock from cocotb.triggers import ClockCycles, FallingEdge, ReadOnly, RisingEdge from crc_model import CRC8_SMBUS, CRC16_IBM3740, CRC32_ISOHDLC, CrcSpec, crc SPECS = {8: CRC8_SMBUS, 16: CRC16_IBM3740, 32: CRC32_ISOHDLC} async def setup(dut) -> CrcSpec: cocotb.start_soon(Clock(dut.clk, 10, unit="ns").start()) dut.rst.value = 1 dut.start.value = 0 dut.valid.value = 0 dut.data.value = 0 await ClockCycles(dut.clk, 2) await FallingEdge(dut.clk) dut.rst.value = 0 return SPECS[len(dut.crc_out)] async def send(dut, msg: bytes, rng: random.Random | None = None) -> int: """Send msg with start on the first byte; return crc_out after the last byte.""" if not msg: dut.start.value = 1 await RisingEdge(dut.clk) await FallingEdge(dut.clk) dut.start.value = 0 for i, b in enumerate(msg): while rng is not None and rng.random() < 0.3: # idle cycles between bytes dut.valid.value = 0 dut.start.value = 0 await FallingEdge(dut.clk) dut.start.value = int(i == 0) dut.valid.value = 1 dut.data.value = b await FallingEdge(dut.clk) dut.start.value = 0 dut.valid.value = 0 await ReadOnly() value = dut.crc_out.value.to_unsigned() await FallingEdge(dut.clk) return value @cocotb.test() async def check_value(dut) -> None: spec = await setup(dut) assert await send(dut, b"123456789") == spec.check @cocotb.test() async def random_messages(dut) -> None: spec = await setup(dut) rng = random.Random(8 * spec.width) for i in range(100): length = 0 if i == 0 else rng.randrange(1, 48) # the first message is empty msg = bytes(rng.getrandbits(8) for _ in range(length)) assert await send(dut, msg, rng) == crc(msg, spec), msg.hex()