python
import cocotb
from cocotb.triggers import Timer
from adder_model import adder_model
from cocotb.clock import Clock
from cocotb.triggers import RisingEdge
import random
@cocotb.test()
async def adder_basic_test(dut):
"""Test for 5 + 10"""
cocotb.fork(Clock(dut.clk, 10, units='ns').start())
A = 5
B = 10
#dut.A <= A
#dut.B <= B # 和下边两行等价
dut.A.value =A
dut.B.value =B
await RisingEdge(dut.clk)
await RisingEdge(dut.clk)
assert dut.X.value == adder_model(A, B), "Adder result is incorrect: {} != 15".format(dut.X.value)
@cocotb.test()
async def adder_randomised_test(dut):
"""Test for adding 2 random numbers multiple times"""
cocotb.fork(Clock(dut.clk, 5, units='ns').start())
for i in range(10):
A = random.randint(0, 15)
B = random.randint(0, 15)
#dut.A <= A
#dut.B <= B
dut.A.value = A
dut.B.value = B
await RisingEdge(dut.clk)
await RisingEdge(dut.clk)
assert dut.X.value == adder_model(A, B), "Randomised test failed with: {A} + {B} = {X}".format(
A=dut.A.value, B=dut.B.value, X=dut.X.value)
#adder_model.py
def adder_model(a: int, b: int) -> int:
""" model of adder """
return a + b
Makefile
# Makefile
TOPLEVEL_LANG= verilog
PWD=$(shell pwd)
VERILOG_SOURCES=./adder.v
TOPLEVEL=adder
MODULE= test_adder
SIM=icarus
include $(shell cocotb-config --makefiles)/Makefile.sim
多文件tb, 多文件dut
# makefile template
VERILOG_SOURCES = $(PWD)/submodule.sv $(PWD)/my_design.sv
# TOPLEVEL is the name of the toplevel module in your Verilog or VHDL file:
TOPLEVEL=my_design
# MODULE is the name of the Python test file:
MODULE=test_my_design
include $(shell cocotb-config --makefiles)/Makefile.sim