Your First Cocotb Testbench

Let's verify a simple Design Under Test (DUT). We will create a Verilog Adder and verify it using Python.

The Plan

We need three files located in the same folder:

  1. adder.sv: The hardware design (Verilog).
  2. test_adder.py: The testbench (Python).
  3. Makefile: The instructions for the simulator.

1. The Design (adder.sv)

Create a simple module that adds inputs A and B to produce output X.

// adder.sv
module adder (
    input [3:0] A,
    input [3:0] B,
    output [4:0] X
);
    assign X = A + B;
endmodule

2. The Testbench (test_adder.py)

This is where the magic happens. We interpret the 'A' and 'B' ports as variables we can set, and 'X' as a variable we can read.

# test_adder.py
import cocotb
from cocotb.triggers import Timer
@cocotb.test()
async def adder_basic_test(dut):
    """Test for 5 + 10"""
    # 1. Drive Inputs
    dut.A.value = 5
    dut.B.value = 10
    # 2. Wait for signal propagation (2ns)
    await Timer(2, units="ns")
    # 3. Check Output
    assert dut.X.value == 15, f"Adder result is wrong: {dut.X.value}"
    # 4. Log Success
    dut._log.info("Test Passed: 5 + 10 = 15")
Note: The async keyword means this function can pause execution (wait for time) and let the simulator run. The await keyword actually performs the pause.

3. The Makefile

This tells Cocotb which simulator to use and which files to compile.

# Makefile
# defaults
SIM ?= icarus
TOPLEVEL_LANG ?= verilog
# source files
VERILOG_SOURCES += $(PWD)/adder.sv
# TOPLEVEL is the name of the toplevel module in your Verilog or VHDL file
TOPLEVEL = adder
# MODULE is the basename of the Python test file
MODULE = test_adder
# include cocotb's make rules to take care of the simulator setup
include $(shell cocotb-config --makefiles)/Makefile.sim

4. Run It!

Open your terminal in that folder and type:

make

You should see output ending with:

INFO     cocotb.regression                  test_adder.adder_basic_test passed
INFO     cocotb.regression                  **************************************************************************************
INFO     cocotb.regression                  ** TEST                          STATUS  SIM TIME (ns)  REAL TIME (s)  RATIO (ns/s) **
INFO     cocotb.regression                  **************************************************************************************
INFO     cocotb.regression                  ** test_adder.adder_basic_test    PASS           2.00           0.00       4553.42  **
INFO     cocotb.regression                  **************************************************************************************