or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

binary-types.mdclock-generation.mdindex.mdlogging-utilities.mdsignal-handling.mdtask-management.mdtest-framework.mdtriggers-timing.md
tile.json

tessl/pypi-cocotb

Cocotb is a coroutine-based cosimulation library for writing VHDL and Verilog testbenches in Python.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/cocotb@1.9.x

To install, run

npx @tessl/cli install tessl/pypi-cocotb@1.9.0

index.mddocs/

Cocotb

A coroutine-based cosimulation library for writing VHDL and Verilog testbenches in Python. Cocotb enables hardware verification engineers to create comprehensive test suites using Python's rich ecosystem, providing seamless integration with various HDL simulators including Icarus Verilog, Verilator, GHDL, Questa, and others.

Package Information

  • Package Name: cocotb
  • Language: Python
  • Installation: pip install cocotb

Core Imports

import cocotb

Common imports for testbench development:

import cocotb
from cocotb.decorators import test, coroutine
from cocotb.triggers import Timer, RisingEdge, FallingEdge, Edge
from cocotb.clock import Clock

Basic Usage

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

@cocotb.test()
async def basic_test(dut):
    """Basic testbench demonstrating clock generation and signal monitoring."""
    
    # Start a clock
    clock = Clock(dut.clk, 10, units="ns")
    cocotb.start_soon(clock.start())
    
    # Reset sequence
    dut.reset.value = 1
    await Timer(100, units="ns")
    dut.reset.value = 0
    
    # Wait for clock edge and test functionality
    await RisingEdge(dut.clk)
    dut.input_signal.value = 0xAB
    
    # Wait a few clock cycles and check output
    for _ in range(5):
        await RisingEdge(dut.clk)
    
    assert dut.output_signal.value == 0xAB, f"Expected 0xAB, got {dut.output_signal.value}"
    
    # Test completion
    await Timer(50, units="ns")

@cocotb.test()
async def concurrent_test(dut):
    """Example showing concurrent task execution."""
    
    # Start multiple concurrent tasks
    task1 = cocotb.start_soon(stimulus_generator(dut))
    task2 = cocotb.start_soon(response_monitor(dut))
    
    # Wait for completion
    await task1
    await task2

async def stimulus_generator(dut):
    """Generate stimulus signals."""
    for i in range(10):
        dut.data_in.value = i
        await Timer(20, units="ns")

async def response_monitor(dut):
    """Monitor response signals."""
    for i in range(10):
        await RisingEdge(dut.clk)
        cocotb.log.info(f"Output: {dut.data_out.value}")

Architecture

Cocotb's architecture centers around coroutines and event-driven simulation:

  • Test Framework: Python decorators mark test functions, with automatic discovery and execution
  • Coroutine System: Async/await syntax for simulation time management and concurrency
  • Trigger System: Event-based synchronization with simulator (time, edges, custom events)
  • Handle System: Hierarchical access to HDL design objects with type-appropriate interfaces
  • Task Management: Concurrent execution of multiple coroutines with join/kill capabilities
  • Simulator Interface: GPI (Generic Programming Interface) provides simulator abstraction

This design enables Python-native testbench development while maintaining tight integration with HDL simulators, allowing engineers to leverage Python's extensive libraries for test data generation, analysis, and reporting.

Capabilities

Test Framework

Core decorators and functions for defining and running tests, including test discovery, execution control, timeout handling, and result management.

@test(timeout_time=None, timeout_unit="step", expect_fail=False, expect_error=(), skip=False, stage=0)
def test_decorator(func): ...

@coroutine
def coroutine_decorator(func): ...

@external
def external_decorator(func): ...

Test Framework

Task Management

Functions for creating, scheduling, and managing concurrent coroutines including immediate scheduling, yielding execution, task creation, and the deprecated fork function.

def start_soon(coro: Union[Task, Coroutine]) -> Task: ...
async def start(coro: Union[Task, Coroutine]) -> Task: ...
def create_task(coro: Union[Task, Coroutine]) -> Task: ...
def fork(coro: Union[Task, Coroutine]) -> Task: ...  # DEPRECATED

Task Management

Triggers and Timing

Comprehensive trigger system for time-based and event-based synchronization including timers, signal edges, composite triggers, and synchronization primitives.

class Timer(time, units="step", round_mode=None): ...
class RisingEdge(signal): ...
class FallingEdge(signal): ...
class Edge(signal): ...
class Event(): ...
class Lock(): ...

Triggers and Timing

Signal Handling

Design object access through hierarchical handles supporting reads, writes, forcing, and comprehensive signal manipulation across different HDL types.

class SimHandleBase: ...
class HierarchyObject(SimHandleBase): ...
class ModifiableObject(NonConstantObject): ...
def SimHandle(handle, path=None): ...

Signal Handling

Clock Generation

Clock generation utilities for creating periodic signals with configurable periods, duty cycles, and phase relationships.

class Clock(signal, period, units="step"): ...
class BaseClock: ...

Clock Generation

Binary and Type System

Binary value representation and HDL-compatible types including logic values, arrays, ranges, and conversion utilities.

class BinaryValue(value=None, n_bits=None, bigEndian=True, binaryRepresentation=BinaryRepresentation.UNSIGNED): ...
class Logic: ...
Bit = Logic  # Type alias
class LogicArray: ...
class Array[T]: ...
class Range(left, direction, right): ...

Binary and Type System

Logging and Utilities

Simulation-aware logging, time utilities, queue implementations, and debugging support with simulation time context and hierarchical naming.

class SimLog: ...
def get_sim_time(units="step"): ...
def get_sim_steps(time, units, round_mode=None): ...
class Queue[T](maxsize=0): ...

Logging and Utilities

Global Variables

scheduler: Optional[Scheduler]  # Global scheduler instance
regression_manager: Optional[RegressionManager]  # Global regression manager
top: Optional[SimHandleBase]  # Handle to toplevel entity/module (DUT)
argv: Optional[List[str]]  # Simulator argument list
argc: Optional[int]  # Length of argv
plusargs: Optional[Dict[str, Union[bool, str]]]  # Simulator plusargs
LANGUAGE: Optional[str]  # TOPLEVEL_LANG environment variable
SIM_NAME: Optional[str]  # Running simulator product name
SIM_VERSION: Optional[str]  # Running simulator version
RANDOM_SEED: Optional[int]  # Random number generator seed
__version__: str  # Cocotb version string

Types

from typing import Union, Optional, List, Dict, Any, Coroutine
from collections.abc import Coroutine

# Core types
Task = cocotb.task.Task
SimHandleBase = cocotb.handle.SimHandleBase

# Union type for coroutine parameters
CoroutineType = Union[Task, Coroutine]