"""cocotb tests for qpsk_tx.sv: every register output is compared bit-exactly with tx_reference() in qpsk_model.py, clock edge by clock edge.""" from __future__ import annotations import random import cocotb from cocotb.clock import Clock from cocotb.triggers import ClockCycles, FallingEdge, RisingEdge from qpsk_model import SPS, tuning_word, tx_reference async def run_tx(dut, valid: list[int], bits: list[int], tw: int) -> dict[str, list[int]]: """Drive one symbol slot per clock and record outputs after every edge.""" cocotb.start_soon(Clock(dut.clk, 10, unit="ns").start()) dut.rst.value = 1 dut.sym_valid.value = 0 dut.sym_bits.value = 0 dut.tuning_word.value = tw await ClockCycles(dut.clk, 4) await FallingEdge(dut.clk) dut.rst.value = 0 got: dict[str, list[int]] = {"i_bb": [], "q_bb": [], "s_out": []} for e in range(len(valid)): # Between edges: check the handshake, then set the inputs for edge e. assert int(dut.sym_ready.value) == int(e % SPS == 0), f"sym_ready wrong before edge {e}" dut.sym_valid.value = valid[e] dut.sym_bits.value = bits[e] await RisingEdge(dut.clk) await FallingEdge(dut.clk) for name in got: got[name].append(getattr(dut, name).value.to_signed()) return got def compare(got: dict[str, list[int]], ref: dict) -> None: for name, values in got.items(): expected = [int(v) for v in ref[name]] bad = [e for e, (a, b) in enumerate(zip(values, expected)) if a != b] assert not bad, f"{name}: first mismatch after edge {bad[0]}: got {values[bad[0]]}, expected {expected[bad[0]]}" @cocotb.test() async def continuous_symbols(dut) -> None: """A symbol in every slot, carrier at a quarter of the clock rate.""" rng = random.Random(18) n = 4000 valid = [1] * n bits = [rng.randrange(4) for _ in range(n)] tw = tuning_word(25e6, 100e6) got = await run_tx(dut, valid, bits, tw) compare(got, tx_reference(valid, bits, tw)) dut._log.info(f"{n} clock edges, {n // SPS} symbols: all samples match the model") @cocotb.test() async def gaps_and_odd_tuning_word(dut) -> None: """Random gaps in the symbol stream and a tuning word that is not a power of two.""" rng = random.Random(1018) n = 4000 valid = [int(rng.random() < 0.7) for _ in range(n)] bits = [rng.randrange(4) for _ in range(n)] tw = 0x1234_5679 got = await run_tx(dut, valid, bits, tw) compare(got, tx_reference(valid, bits, tw))