CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cocotb

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

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

test-framework.mddocs/

Test Framework

The cocotb test framework provides decorators and infrastructure for defining, discovering, and executing HDL testbenches using Python's async/await syntax. Tests are automatically discovered and can be configured with timeouts, failure expectations, and execution stages.

Capabilities

Test Decorator

Marks async functions as tests with optional configuration for timeouts, failure expectations, and execution control.

@test(timeout_time=None, timeout_unit="step", expect_fail=False, expect_error=(), skip=False, stage=0)
def test_decorator(func):
    """
    Decorator to mark a Callable which returns a Coroutine as a test.

    Parameters:
    - timeout_time (numbers.Real or decimal.Decimal, optional): Simulation time duration before timeout
    - timeout_unit (str, optional): Units of timeout_time, accepts any units that Timer does
    - expect_fail (bool, optional): If True, test passes when it fails a functional check
    - expect_error (exception type or tuple, optional): Test passes only if specified exception types are raised
    - skip (bool, optional): Don't execute this test as part of regression
    - stage (int): Order tests logically into stages, defaults to 0

    Returns:
    Test coroutine decorator
    """

Usage Examples:

@cocotb.test()
async def basic_test(dut):
    """Simple test without configuration."""
    await Timer(100, units="ns")
    assert dut.output.value == 1

@cocotb.test(timeout_time=1000, timeout_unit="ns")
async def timed_test(dut):
    """Test with timeout protection."""
    # Long-running test operations
    await Timer(500, units="ns")

@cocotb.test(expect_fail=True)
async def failing_test(dut):
    """Test that expects to fail."""
    assert False, "This test is expected to fail"

@cocotb.test(expect_error=ValueError)
async def error_test(dut):
    """Test that expects specific exception."""
    raise ValueError("Expected error")

@cocotb.test(skip=True)
async def skipped_test(dut):
    """Test that will be skipped."""
    pass

@cocotb.test(stage=1)
async def staged_test(dut):
    """Test in execution stage 1."""
    await Timer(50, units="ns")

Coroutine Decorator

Transforms functions into coroutines with logging capabilities and join functionality for creating reusable testbench components.

@coroutine
def coroutine_decorator(func):
    """
    Decorator class that provides common coroutine mechanisms.

    Features:
    - log methods will log to cocotb.coroutine.name
    - join method returns event which fires when coroutine exits

    Returns:
    Coroutine with enhanced capabilities
    """

Usage Examples:

@cocotb.coroutine
async def stimulus_generator(dut, data_list):
    """Reusable stimulus generation coroutine."""
    for data in data_list:
        dut.input_data.value = data
        await RisingEdge(dut.clk)
        stimulus_generator.log.info(f"Applied stimulus: {data}")

@cocotb.coroutine  
async def response_checker(dut, expected_list):
    """Reusable response checking coroutine."""
    for expected in expected_list:
        await RisingEdge(dut.clk)
        actual = dut.output_data.value
        assert actual == expected, f"Expected {expected}, got {actual}"
        response_checker.log.info(f"Verified response: {actual}")

@cocotb.test()
async def coordinated_test(dut):
    """Test using coroutine components."""
    stim_task = cocotb.start_soon(stimulus_generator(dut, [1, 2, 3, 4]))
    check_task = cocotb.start_soon(response_checker(dut, [1, 2, 3, 4]))
    
    await stim_task.join()
    await check_task.join()

External Decorator

Wraps functions to run in separate threads, enabling blocking operations without stopping simulation time progression.

@external
def external_decorator(func):
    """
    Decorator to apply to an external function to enable calling from cocotb.

    Converts normal function into blocking coroutine that runs in separate thread.
    Currently creates new execution thread for each function call.

    Returns:
    Blocking coroutine that yields until thread completion
    """

Usage Examples:

@cocotb.external
def file_operation(filename):
    """External function for file I/O."""
    with open(filename, 'r') as f:
        data = f.read()
    time.sleep(1)  # Simulate slow operation
    return data.strip()

@cocotb.external  
def network_request(url):
    """External function for network operations."""
    import requests
    response = requests.get(url)
    return response.json()

@cocotb.test()
async def external_test(dut):
    """Test using external functions."""
    # These operations run in threads and don't block simulation
    config_data = await file_operation("config.txt")
    api_data = await network_request("http://api.example.com/data")
    
    # Use the data in simulation
    dut.config.value = int(config_data)
    dut.api_value.value = api_data['value']
    
    await Timer(100, units="ns")

Function Decorator

Creates functions that can block simulation time while being called from external threads, bridging threaded code back to simulation context.

@function
def function_decorator(func):
    """
    Decorator for functions that can block and consume simulation time.

    Allows coroutine that consumes simulation time to be called by thread
    started with @external. Function internally blocks while externally
    appears to yield.

    Returns:
    Function that can be called from external threads
    """

Usage Examples:

@cocotb.function
async def wait_for_condition(dut, signal, value, timeout_ns=1000):
    """Function that waits for signal condition."""
    start_time = get_sim_time("ns")
    
    while dut._id(signal, extended=False).value != value:
        await Timer(10, units="ns")
        current_time = get_sim_time("ns")
        
        if current_time - start_time > timeout_ns:
            raise TimeoutError(f"Signal {signal} never reached {value}")
    
    return current_time - start_time

@cocotb.external
def threaded_test_sequence(dut):
    """External function that calls back into simulation."""
    import threading
    
    # This external function can call @function decorated functions
    duration = wait_for_condition(dut, "ready", 1, 500)
    print(f"Ready signal asserted after {duration} ns")
    
    return "sequence_complete"

@cocotb.test()
async def hybrid_test(dut):
    """Test combining external and function decorators."""
    # Start external thread that will call back into simulation
    result = await threaded_test_sequence(dut)
    assert result == "sequence_complete"

Public Utility Function

Public Decorator

Utility decorator for marking functions as part of the public API.

def public(f):
    """
    Use decorator to avoid retyping function/class names.
    
    Adds function name to module's __all__ list to mark as public API.
    
    Parameters:
    - f: Function to mark as public
    
    Returns:
    The original function unchanged
    """

Test Execution Context

Global Test Variables

During test execution, cocotb provides access to test context through global variables:

# Available during test execution
cocotb.regression_manager  # Access to test execution manager
cocotb.scheduler  # Access to coroutine scheduler
cocotb.top  # Handle to top-level design entity (DUT)
cocotb.argv  # Command-line arguments from simulator
cocotb.plusargs  # Plus-args from simulator command line

Usage Examples:

@cocotb.test()
async def context_test(dut):
    """Test accessing execution context."""
    # Access top-level design directly
    assert cocotb.top is dut  # They reference the same object
    
    # Check simulator arguments
    if "debug" in cocotb.plusargs:
        cocotb.log.info("Debug mode enabled")
    
    # Access scheduler for advanced operations
    current_time = cocotb.scheduler.sim_time
    cocotb.log.info(f"Test started at {current_time}")

Install with Tessl CLI

npx tessl i tessl/pypi-cocotb

docs

binary-types.md

clock-generation.md

index.md

logging-utilities.md

signal-handling.md

task-management.md

test-framework.md

triggers-timing.md

tile.json