"""cocotb tests for accum8.sv: directed cases plus a seeded random test. Inputs change on the falling clock edge, half a cycle away from the rising edge where the DUT samples them. Outputs are checked in the ReadOnly phase after each rising edge, when every signal has settled. """ from __future__ import annotations import random import cocotb from cocotb.clock import Clock from cocotb.triggers import ClockCycles, FallingEdge, ReadOnly, RisingEdge from models import Accum8Model async def start(dut) -> Accum8Model: """Start a 100 MHz clock, hold reset for two cycles, return a fresh model.""" cocotb.start_soon(Clock(dut.clk, 10, unit="ns").start()) dut.rst.value = 1 dut.clr.value = 0 dut.en.value = 0 dut.din.value = 0 await ClockCycles(dut.clk, 2) return Accum8Model() async def cycle(dut, model: Accum8Model, rst: int = 0, clr: int = 0, en: int = 0, din: int = 0) -> None: """Apply one set of inputs for one clock cycle and check the outputs.""" await FallingEdge(dut.clk) dut.rst.value = rst dut.clr.value = clr dut.en.value = en dut.din.value = din await RisingEdge(dut.clk) # the DUT samples the inputs here model.step(rst, clr, en, din) await ReadOnly() # wait until all signals are stable got = (int(dut.acc.value), int(dut.carry.value)) assert got == (model.acc, model.carry), ( f"inputs rst={rst} clr={clr} en={en} din={din}: " f"DUT (acc, carry) = {got}, model = {(model.acc, model.carry)}") @cocotb.test() async def directed(dut) -> None: """Hand-picked cases: plain add, overflow, hold, clear priority, reset.""" model = await start(dut) await cycle(dut, model, rst=1) await cycle(dut, model, en=1, din=200) await cycle(dut, model, en=1, din=100) # 300 wraps to 44, carry 1 await cycle(dut, model, en=0, din=77) # hold await cycle(dut, model, en=1, din=0) # carry clears on next add await cycle(dut, model, clr=1, en=1, din=5) # clr beats en await cycle(dut, model, en=1, din=255) await cycle(dut, model, en=1, din=1) # exactly 256: acc 0, carry 1 await cycle(dut, model, rst=1, en=1, din=9) # reset beats everything @cocotb.test() async def random_stimulus(dut) -> None: """2000 cycles of random inputs. cocotb seeds `random` from COCOTB_RANDOM_SEED.""" model = await start(dut) await cycle(dut, model, rst=1) for _ in range(2000): await cycle(dut, model, rst=int(random.random() < 0.01), clr=int(random.random() < 0.05), en=int(random.random() < 0.7), din=random.randrange(256)) dut._log.info("2000 random cycles checked")