Skip to content
systemcoding.dev
Hardware

Test HDL Designs in Python With cocotb

Write cocotb 1.9 tests in Python for a Verilog counter: drive a Clock, await RisingEdge and ReadOnly, assert outputs and run on Icarus Verilog from a Makefile.

7 min read
Summarize in AI
Flat illustration of logic gates wired into a small circuit, with the Python, Haskell and SparkFun logos.

Writing a testbench in Verilog means writing it in a language built to describe hardware, with almost no data structures and weak facilities for checking. cocotb takes the opposite approach: the design stays in Verilog or VHDL, and the testbench is ordinary Python that drives the simulator through a standard interface. You get lists, dictionaries, classes, random, files, pytest-style assertions and every library on PyPI. This post sets up cocotb 1.9 with Icarus Verilog 12.0 on Python 3.12, writes tests for a four-bit counter and explains the coroutine model that makes the waiting work. It assumes you can already write and run a Verilog testbench in Icarus Verilog.

How cocotb works

The simulator runs your design. cocotb loads a shared library into the simulator (through VPI for Icarus, or VHPI and FLI for others) and starts a Python interpreter inside the simulator process. Your tests are async functions. Each await hands control back to the simulator until the condition you are waiting for becomes true, such as a rising clock edge or a delay. While your coroutine waits, the simulator keeps advancing time, so Python never blocks the hardware.

The consequence for how you write tests: nothing happens in simulated time unless you await something. Setting dut.rst.value = 1 and then reading an output on the next line reads the old value, because no simulation step ran between them.

The design

Use the same counter module:

counter.vverilog
module counter (
    input  wire       clk,
    input  wire       rst,
    output reg  [3:0] count
);
    always @(posedge clk) begin
        if (rst)
            count <= 4'd0;
        else
            count <= count + 4'd1;
    end
endmodule

There is no testbench module. cocotb uses counter as the top level and reaches its ports through a handle named dut.

A first test

Create test_counter.py:

test_counter.pypython
import cocotb
from cocotb.clock import Clock
from cocotb.triggers import ReadOnly, RisingEdge


async def reset(dut):
    dut.rst.value = 1
    for _ in range(2):
        await RisingEdge(dut.clk)
    dut.rst.value = 0


@cocotb.test()
async def counts_up_and_wraps(dut):
    cocotb.start_soon(Clock(dut.clk, 10, units="ns").start())
    await reset(dut)

    for expected in range(1, 20):
        await RisingEdge(dut.clk)
        await ReadOnly()
        assert int(dut.count.value) == expected % 16, (
            f"count was {int(dut.count.value)}, expected {expected % 16}"
        )

The ReadOnly() trigger waits until the simulator has finished every update in the current time step, so the value you read is the settled one. Leave it out and await RisingEdge(dut.clk) returns while the counter's nonblocking assignment has not yet taken effect, so dut.count.value still holds the value from before the edge and every comparison is off by one. That off-by-one is the most common first failure in a cocotb test, and it is a scheduling effect, not a bug in the design.

Read the pieces. @cocotb.test() registers the function. Clock(dut.clk, 10, units="ns") builds a 10 ns clock; .start() is a coroutine that toggles the pin forever, and cocotb.start_soon runs it in the background. The reset helper is an ordinary coroutine, and calling it with await runs it to completion. dut.rst.value = 1 schedules a write that takes effect at the next opportunity, not instantly. int(dut.count.value) converts the resolved logic value to a Python integer; if any bit is x or z, that conversion raises ValueError, which is helpful: unknown output fails loudly.

The Makefile

cocotb ships its own makefile fragments. A short Makefile selects the simulator and the files:

Makefilemakefile
SIM ?= icarus
TOPLEVEL_LANG ?= verilog

VERILOG_SOURCES += $(PWD)/counter.v

TOPLEVEL = counter
MODULE = test_counter

include $(shell cocotb-config --makefiles)/Makefile.sim

TOPLEVEL is the Verilog module to simulate, and MODULE is the Python module that holds the tests. cocotb 2.0 renamed these to COCOTB_TOPLEVEL and COCOTB_TEST_MODULES and changed the units argument of Clock to unit, so if you install a newer cocotb than the one named here, adjust those three names. Install with pip install cocotb==1.9.2 in a virtual environment, and run:

Shell
make
Text
     0.00ns INFO     cocotb.regression                  running counts_up_and_wraps (1/1)
   200.00ns INFO     cocotb.regression                  counts_up_and_wraps passed
   200.00ns INFO     cocotb.regression                  *************************************************************************************
                                                         ** TEST                          STATUS  SIM TIME (ns)  REAL TIME (s)  RATIO (ns/s) **
                                                         *************************************************************************************
                                                         ** test_counter.counts_up_and_wraps  PASS         200.00           0.01      19000.00  **
                                                         *************************************************************************************
                                                         ** TESTS=1 PASS=1 FAIL=0 SKIP=0                  200.00           0.02      9500.00  **
                                                         *************************************************************************************

The wall-clock columns are an illustrative example and will differ on your machine; the simulated time of about 200 ns does follow from the code: two reset edges plus nineteen checking edges at 10 ns each.

What a failure looks like

Change expected % 16 to expected % 15 to make the test fail on purpose. The assertion message prints the two values and cocotb reports the Python traceback with the line:

Text
    assert int(dut.count.value) == expected % 15, (
AssertionError: count was 15, expected 0

The test fails at expected value 15 because the hardware reached 15 while the wrong reference wrapped it to 0. This is a point in cocotb's favour: the failure message is a Python assertion with a message you wrote, not a bare $display.

Randomised and parameterised tests

Python's strengths show up when the input space is large. Replace the fixed loop with a randomised reset test:

test_counter_random.pypython
import random

import cocotb
from cocotb.clock import Clock
from cocotb.triggers import ReadOnly, RisingEdge


@cocotb.test()
async def reset_always_wins(dut):
    cocotb.start_soon(Clock(dut.clk, 10, units="ns").start())
    random.seed(1234)

    dut.rst.value = 0
    for _ in range(100):
        dut.rst.value = random.choice([0, 0, 0, 1])
        await RisingEdge(dut.clk)
        await ReadOnly()
        if dut.rst.value == 1:
            assert int(dut.count.value) == 0

Seeding makes a failure reproducible, and the weighted choice produces a reset about a quarter of the time. cocotb 1.9 also supports TestFactory to generate many tests from a list of parameters. Note that after ReadOnly() the simulator forbids writes in the same time step, so the next write waits for the next await RisingEdge.

Split large checks into scoreboard classes. A scoreboard is a Python class that holds the expected-value queue and an append method the monitor coroutine calls; a few lines of code replace what takes a whole SystemVerilog UVM library.

Waiting on more than clock edges

RisingEdge is one of several triggers, and tests that go beyond a counter use all of them:

TriggerResumes the coroutine when
RisingEdge(sig) / FallingEdge(sig)the signal goes 0 to 1 or 1 to 0
Edge(sig)the signal changes in either direction
Timer(20, units="ns")the given simulated time has passed
ClockCycles(clk, n)n clock edges have passed
ReadOnly()the current time step has settled

A test that waits for a design to raise a done flag should never loop forever if the flag never comes. Wrap the wait in a timeout so a hang becomes a failure:

test_timeout.pypython
import cocotb
from cocotb.clock import Clock
from cocotb.triggers import RisingEdge, with_timeout


@cocotb.test()
async def counter_reaches_15(dut):
    cocotb.start_soon(Clock(dut.clk, 10, units="ns").start())
    dut.rst.value = 1
    await RisingEdge(dut.clk)
    dut.rst.value = 0

    async def wait_for_15():
        while int(dut.count.value) != 15:
            await RisingEdge(dut.clk)

    await with_timeout(wait_for_15(), 500, "ns")

If count never reaches 15 inside 500 ns, with_timeout raises SimTimeoutError and the test fails with the message instead of hanging the regression. The loop reads dut.count.value straight after the edge, which is acceptable here because the loop re-checks on the next edge and the final value is what matters.

A scoreboard in twelve lines

When a design has an output stream, keep the expected values in a Python list and compare as results arrive. This is the pattern that replaces UVM scoreboards:

scoreboard.pypython
class Scoreboard:
    def __init__(self):
        self.expected = []
        self.errors = 0

    def expect(self, value):
        self.expected.append(value)

    def check(self, actual):
        want = self.expected.pop(0)
        if actual != want:
            self.errors += 1
            raise AssertionError(f"got {actual}, expected {want}")

A monitor coroutine calls check each time the output is valid, and the test's stimulus coroutine calls expect with the value its reference model computes. Because both are plain Python, the reference model can be NumPy, a CRC library or a parser for a real protocol capture.

Waveforms from a cocotb run

cocotb does not dump waveforms by itself, and the simulator does. For Icarus Verilog 12.0 the simplest route is a tiny Verilog module that calls $dumpfile and $dumpvars, added to VERILOG_SOURCES and named as the top level, which instantiates counter inside it. Then dut in Python refers to that wrapper and signals of the counter sit one level down, such as dut.u_counter.count. Verilator-based runs accept WAVES=1 on the command line instead.

Where cocotb is the wrong tool

cocotb crosses the boundary between Python and the simulator on every await and every signal access. For a design that needs millions of cycles per second, a Verilator C++ harness is faster. cocotb also runs on Verilator 5, which narrows the gap, but the fastest runs still belong to compiled testbenches. Choose cocotb when test readability, data handling or reuse of Python code matters more than raw cycle rate.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.