Library Reference

Test Results

The exceptions in this module can be raised at any point by any code and will terminate the test.

cocotb.result.raise_error(obj, msg)[source]

Create a TestError exception and raise it after printing a traceback.

Deprecated since version 1.3: Raise a standard Python exception instead of calling this function. A stacktrace will be printed by cocotb automatically if the exception is unhandled.

Parameters
  • obj – Object with a log method.

  • msg (str) – The log message.

cocotb.result.create_error(obj, msg)[source]

Like raise_error(), but return the exception rather than raise it, simply to avoid too many levels of nested try/except blocks.

Deprecated since version 1.3: Raise a standard Python exception instead of calling this function.

Parameters
  • obj – Object with a log method.

  • msg (str) – The log message.

exception cocotb.result.ReturnValue(retval)[source]

Helper exception needed for Python versions prior to 3.3.

Deprecated since version 1.4: Use a return statement instead; this works in all supported versions of Python.

exception cocotb.result.TestComplete(*args, **kwargs)[source]

Exception showing that the test was completed. Sub-exceptions detail the exit status.

exception cocotb.result.ExternalException(exception)[source]

Exception thrown by cocotb.external functions.

exception cocotb.result.TestError(*args, **kwargs)[source]

Exception showing that the test was completed with severity Error.

Deprecated since version 1.5: Raise a standard Python exception instead. A stacktrace will be printed by cocotb automatically if the exception is unhandled.

exception cocotb.result.TestFailure(*args, **kwargs)[source]

Exception showing that the test was completed with severity Failure.

exception cocotb.result.TestSuccess(*args, **kwargs)[source]

Exception showing that the test was completed successfully.

exception cocotb.result.SimFailure(*args, **kwargs)[source]

Exception showing that the simulator exited unsuccessfully.

exception cocotb.result.SimTimeoutError[source]

Exception for when a timeout, in terms of simulation time, occurs.

Writing and Generating tests

class cocotb.test(*args, **kwargs)[source]

Decorator to mark a function as a test.

All tests are coroutines. The test decorator provides some common reporting etc., a test timeout and allows us to mark tests as expected failures.

Tests are evaluated in the order they are defined in a test module.

Used as @cocotb.test(...).

Parameters
  • timeout_time (numbers.Real or decimal.Decimal, optional) –

    Simulation time duration before timeout occurs.

    New in version 1.3.

    Note

    Test timeout is intended for protection against deadlock. Users should use with_timeout if they require a more general-purpose timeout mechanism.

  • timeout_unit (str, optional) –

    Units of timeout_time, accepts any units that Timer does.

    New in version 1.3.

    Deprecated since version 1.5: Using None as the the timeout_unit argument is deprecated, use 'step' instead.

  • expect_fail (bool, optional) – Don’t mark the result as a failure if the test fails.

  • expect_error (exception type or tuple of exception types, optional) –

    Mark the result as a pass only if one of the exception types is raised in the test. This is primarily for cocotb internal regression use for when a simulator error is expected.

    Users are encouraged to use the following idiom instead:

    @cocotb.test()
    async def my_test(dut):
        try:
            await thing_that_should_fail()
        except ExceptionIExpect:
            pass
        else:
            assert False, "Exception did not occur"
    

    Changed in version 1.3: Specific exception types can be expected

    Deprecated since version 1.5: Passing a bool value is now deprecated. Pass a specific Exception or a tuple of Exceptions instead.

  • skip (bool, optional) – Don’t execute this test as part of the regression. Test can still be run manually by setting TESTCASE.

  • stage (int, optional) – Order tests logically into stages, where multiple tests can share a stage.

class cocotb.coroutine(func)[source]

Decorator class that allows us to provide common coroutine mechanisms:

log methods will log to cocotb.coroutine.name.

join() method returns an event which will fire when the coroutine exits.

Used as @cocotb.coroutine.

class cocotb.external(func)[source]

Decorator to apply to an external function to enable calling from cocotb.

This turns a normal function that isn’t a coroutine into a blocking coroutine. Currently, this creates a new execution thread for each function that is called. Scope for this to be streamlined to a queue in future.

class cocotb.function(func)[source]

Decorator class that allows a function to block.

This allows a coroutine that consumes simulation time to be called by a thread started with cocotb.external; in other words, to internally block while externally appear to yield.

class cocotb.hook(*args, **kwargs)[source]

Decorator to mark a function as a hook for cocotb.

Used as @cocotb.hook().

All hooks are run at the beginning of a cocotb test suite, prior to any test code being run.

Deprecated since version 1.5: Hooks are deprecated. Their functionality can be replaced with module-level Python code, higher-priority tests using the stage argument to cocotb.test()s, or custom decorators which perform work before and after the tests they decorate.

class cocotb.regression.TestFactory(test_function, *args, **kwargs)[source]

Factory to automatically generate tests.

Parameters
  • test_function – The function that executes a test. Must take dut as the first argument.

  • *args – Remaining arguments are passed directly to the test function. Note that these arguments are not varied. An argument that varies with each test must be a keyword argument to the test function.

  • **kwargs – Remaining keyword arguments are passed directly to the test function. Note that these arguments are not varied. An argument that varies with each test must be a keyword argument to the test function.

Assuming we have a common test function that will run a test. This test function will take keyword arguments (for example generators for each of the input interfaces) and generate tests that call the supplied function.

This Factory allows us to generate sets of tests based on the different permutations of the possible arguments to the test function.

For example, if we have a module that takes backpressure, has two configurable features where enabling feature_b requires feature_a to be active, and need to test against data generation routines gen_a and gen_b:

>>> tf = TestFactory(test_function=run_test)
>>> tf.add_option(name='data_in', optionlist=[gen_a, gen_b])
>>> tf.add_option('backpressure', [None, random_backpressure])
>>> tf.add_option(('feature_a', 'feature_b'), [(False, False), (True, False), (True, True)])
>>> tf.generate_tests()

We would get the following tests:

  • gen_a with no backpressure and both features disabled

  • gen_a with no backpressure and only feature_a enabled

  • gen_a with no backpressure and both features enabled

  • gen_a with random_backpressure and both features disabled

  • gen_a with random_backpressure and only feature_a enabled

  • gen_a with random_backpressure and both features enabled

  • gen_b with no backpressure and both features disabled

  • gen_b with no backpressure and only feature_a enabled

  • gen_b with no backpressure and both features enabled

  • gen_b with random_backpressure and both features disabled

  • gen_b with random_backpressure and only feature_a enabled

  • gen_b with random_backpressure and both features enabled

The tests are appended to the calling module for auto-discovery.

Tests are simply named test_function_N. The docstring for the test (hence the test description) includes the name and description of each generator.

Changed in version 1.5: Groups of options are now supported

add_option(name, optionlist)[source]

Add a named option to the test.

Parameters
  • name (str or iterable of str) – An option name, or an iterable of several option names. Passed to test as keyword arguments.

  • optionlist (list) – A list of possible options for this test knob. If N names were specified, this must be a list of N-tuples or lists, where each element specifies a value for its respective option.

Changed in version 1.5: Groups of options are now supported

generate_tests(prefix='', postfix='')[source]

Generate an exhaustive set of tests using the cartesian product of the possible keyword arguments.

The generated tests are appended to the namespace of the calling module.

Parameters
  • prefix (str) – Text string to append to start of test_function name when naming generated test cases. This allows reuse of a single test_function with multiple TestFactories without name clashes.

  • postfix (str) – Text string to append to end of test_function name when naming generated test cases. This allows reuse of a single test_function with multiple TestFactories without name clashes.

Interacting with the Simulator

class cocotb.binary.BinaryRepresentation[source]
UNSIGNED = 0

Unsigned format

SIGNED_MAGNITUDE = 1

Sign and magnitude format

TWOS_COMPLEMENT = 2

Two’s complement format

class cocotb.binary.BinaryValue(value=None, n_bits=None, bigEndian=True, binaryRepresentation=0, bits=None)[source]

Representation of values in binary format.

The underlying value can be set or accessed using these aliasing attributes:

For example:

>>> vec = BinaryValue()
>>> vec.integer = 42
>>> print(vec.binstr)
101010
>>> print(vec.buff)
b'*'
Parameters
  • value (str or int or long, optional) – Value to assign to the bus.

  • n_bits (int, optional) – Number of bits to use for the underlying binary representation.

  • bigEndian (bool, optional) – Interpret the binary as big-endian when converting to/from a string buffer.

  • binaryRepresentation (BinaryRepresentation) – The representation of the binary value (one of UNSIGNED, SIGNED_MAGNITUDE, TWOS_COMPLEMENT). Defaults to unsigned representation.

  • bits (int, optional) – Deprecated: Compatibility wrapper for n_bits.

assign(value)[source]

Decides how best to assign the value to the vector.

Picks from the type of its argument whether to set integer, binstr, or buff.

Parameters

value (str or int or bytes) – The value to assign.

Changed in version 1.4: This no longer falls back to setting buff if a str containing any characters that aren’t 0, 1, X or Z is used, since buff now accepts only bytes. Instead, an error is raised.

property integer

The integer representation of the underlying vector.

property value

Integer access to the value. deprecated

property signed_integer

The signed integer representation of the underlying vector.

property is_resolvable

Return whether the value contains only resolvable (i.e. no “unknown”) bits.

By default the values X, Z, U and W are considered unresolvable. This can be configured with COCOTB_RESOLVE_X.

This is similar to the SystemVerilog Assertion $isunknown system function or the VHDL function is_x (with an inverted meaning).

property buff

The value as a binary string buffer.

>>> BinaryValue("01000001" + "00101111").buff == b"\x41\x2F"
True

Changed in version 1.4: This changed from str to bytes. Note that for older versions used with Python 2 these types were indistinguishable.

property binstr

The binary representation stored as a string of 0, 1, and possibly x, z, and other states.

property n_bits

The number of bits of the binary value.

cocotb.fork(coro: Union[cocotb.decorators.RunningTask, collections.abc.Coroutine])cocotb.decorators.RunningTask[source]

Schedule a coroutine to be run concurrently. See Coroutines for details on its use.

cocotb.decorators.RunningTask.join(self)

Return a trigger that will fire when the wrapped coroutine exits.

cocotb.decorators.RunningTask.kill(self)

Kill a coroutine.

Triggers

See Simulator Triggers for a list of sub-classes. Below are the internal classes used within cocotb.

class cocotb.triggers.Trigger[source]

Base class to derive from.

abstract prime(callback)[source]

Set a callback to be invoked when the trigger fires.

The callback will be invoked with a single argument, self.

Sub-classes must override this, but should end by calling the base class method.

Do not call this directly within coroutines, it is intended to be used only by the scheduler.

unprime()[source]

Remove the callback, and perform cleanup if necessary.

After being un-primed, a Trigger may be re-primed again in the future. Calling unprime multiple times is allowed, subsequent calls should be a no-op.

Sub-classes may override this, but should end by calling the base class method.

Do not call this directly within coroutines, it is intended to be used only by the scheduler.

class cocotb.triggers.GPITrigger[source]

Base Trigger class for GPI triggers.

Consumes simulation time.

unprime()[source]

Disable a primed trigger, can be re-primed.

class cocotb.triggers.Waitable[source]

Base class for trigger-like objects implemented using coroutines.

This converts a _wait abstract method into a suitable __await__.

async _wait()[source]

Should be implemented by the sub-class. Called by await self to convert the waitable object into a coroutine.

Testbench Structure

These are provided by the cocotb-bus package.

Bus

class cocotb_bus.bus.Bus(entity, name, signals, optional_signals=[], bus_separator='_', array_idx=None)[source]

Wraps up a collection of signals.

Assumes we have a set of signals/nets named entity.<bus_name><separator><signal>.

For example a bus stream_in with signals valid and data is assumed to be named dut.stream_in_valid and dut.stream_in_data (with the default separator ‘_’).

Parameters
  • entity (SimHandle) – SimHandle instance to the entity containing the bus.

  • name (str) – Name of the bus. None for a nameless bus, e.g. bus-signals in an interface or a modport (untested on struct/record, but could work here as well).

  • signals (list or dict) – In the case of an object (passed to drive()/capture()) that has the same attribute names as the signal names of the bus, the signals argument can be a list of those names. When the object has different attribute names, the signals argument should be a dict that maps bus attribute names to object signal names.

  • optional_signals (list or dict, optional) – Signals that don’t have to be present on the interface. See the signals argument above for details.

  • bus_separator (str, optional) – Character(s) to use as separator between bus name and signal name. Defaults to ‘_’.

  • array_idx (int or None, optional) – Optional index when signal is an array.

drive(obj, strict=False)[source]

Drives values onto the bus.

Parameters
  • obj – Object with attribute names that match the bus signals.

  • strict (bool, optional) – Check that all signals are being assigned.

Raises

AttributeError – If not all signals have been assigned when strict=True.

capture()[source]

Capture the values from the bus, returning an object representing the capture.

Returns

A dictionary that supports access by attribute, where each attribute corresponds to each signal’s value.

Return type

dict

Raises

RuntimeError – If signal not present in bus, or attempt to modify a bus capture.

sample(obj, strict=False)[source]

Sample the values from the bus, assigning them to obj.

Parameters
  • obj – Object with attribute names that match the bus signals.

  • strict (bool, optional) – Check that all signals being sampled are present in obj.

Raises

AttributeError – If attribute is missing in obj when strict=True.

Driver

class cocotb_bus.drivers.Driver[source]

Class defining the standard interface for a driver within a testbench.

The driver is responsible for serializing transactions onto the physical pins of the interface. This may consume simulation time.

Constructor for a driver instance.

kill()[source]

Kill the coroutine sending stuff.

append(transaction: Any, callback: Optional[Callable[[Any], Any]] = None, event: Optional[cocotb.triggers.Event] = None, **kwargs: Any)None[source]

Queue up a transaction to be sent over the bus.

Mechanisms are provided to permit the caller to know when the transaction is processed.

Parameters
  • transaction – The transaction to be sent.

  • callback – Optional function to be called when the transaction has been sent.

  • eventEvent to be set when the transaction has been sent.

  • **kwargs – Any additional arguments used in child class’ _driver_send method.

clear()[source]

Clear any queued transactions without sending them onto the bus.

send(transaction: Any, sync: bool = True, **kwargs: Any)None[source]

Blocking send call (hence must be “awaited” rather than called).

Sends the transaction over the bus.

Parameters
  • transaction – The transaction to be sent.

  • sync – Synchronize the transfer by waiting for a rising edge.

  • **kwargs – Additional arguments used in child class’ _driver_send method.

async _driver_send(transaction: Any, sync: bool = True, **kwargs: Any)None[source]

Actual implementation of the send.

Sub-classes should override this method to implement the actual send() routine.

Parameters
  • transaction – The transaction to be sent.

  • sync – Synchronize the transfer by waiting for a rising edge.

  • **kwargs – Additional arguments if required for protocol implemented in a sub-class.

async _send(transaction: Any, callback: Callable[[Any], Any], event: cocotb.triggers.Event, sync: bool = True, **kwargs)None[source]

Send coroutine.

Parameters
  • transaction – The transaction to be sent.

  • callback – Optional function to be called when the transaction has been sent.

  • event – event to be set when the transaction has been sent.

  • sync – Synchronize the transfer by waiting for a rising edge.

  • **kwargs – Any additional arguments used in child class’ _driver_send method.

class cocotb_bus.drivers.BitDriver(signal, clk, generator=None)[source]

Bases: object

Drives a signal onto a single bit.

Useful for exercising ready/valid flags.

start(generator: Optional[Iterable[Tuple[int, int]]] = None)None[source]

Start generating data.

Parameters

generator

Generator yielding data. The generator should yield tuples (on, off) with the number of cycles to be on, followed by the number of cycles to be off. Typically the generator should go on forever.

Example:

bit_driver.start((1, i % 5) for i in itertools.count())

stop()[source]

Stop generating data.

class cocotb_bus.drivers.BusDriver(entity: cocotb.handle.SimHandleBase, name: Optional[str], clock: cocotb.handle.SimHandleBase, **kwargs: Any)[source]

Bases: cocotb_bus.drivers.Driver

Wrapper around common functionality for buses which have:

  • a list of _signals (class attribute)

  • a list of _optional_signals (class attribute)

  • a clock

  • a name

  • an entity

Parameters
  • entity – A handle to the simulator entity.

  • name – Name of this bus. None for a nameless bus, e.g. bus-signals in an interface or a modport. (untested on struct/record, but could work here as well).

  • clock – A handle to the clock associated with this bus.

  • **kwargs – Keyword arguments forwarded to cocotb.Bus, see docs for that class for more information.

Constructor for a driver instance.

async _driver_send(transaction, sync: bool = True)None[source]

Implementation for BusDriver.

Parameters
  • transaction – The transaction to send.

  • sync – Synchronize the transfer by waiting for a rising edge.

_wait_for_signal(signal)[source]

This method will return when the specified signal has hit logic 1. The state will be in the ReadOnly phase so sim will need to move to NextTimeStep before registering more callbacks can occur.

_wait_for_nsignal(signal)[source]

This method will return when the specified signal has hit logic 0. The state will be in the ReadOnly phase so sim will need to move to NextTimeStep before registering more callbacks can occur.

class cocotb_bus.drivers.ValidatedBusDriver(entity: cocotb.handle.SimHandleBase, name: str, clock: cocotb.handle.SimHandleBase, *, valid_generator: Optional[Iterable[Tuple[int, int]]] = None, **kwargs: Any)[source]

Bases: cocotb_bus.drivers.BusDriver

Same as a BusDriver except we support an optional generator to control which cycles are valid.

Parameters
  • entity (SimHandle) – A handle to the simulator entity.

  • name (str) – Name of this bus.

  • clock (SimHandle) – A handle to the clock associated with this bus.

  • valid_generator (generator, optional) – a generator that yields tuples of (valid, invalid) cycles to insert.

Constructor for a driver instance.

_next_valids()[source]

Optionally insert invalid cycles every N cycles.

The generator should yield tuples with the number of cycles to be on followed by the number of cycles to be off. The on cycles should be non-zero, we skip invalid generator entries.

set_valid_generator(valid_generator=None)[source]

Set a new valid generator for this bus.

Monitor

class cocotb_bus.monitors.Monitor(callback=None, event=None)[source]

Base class for Monitor objects.

Monitors are passive ‘listening’ objects that monitor pins going in or out of a DUT. This class should not be used directly, but should be sub-classed and the internal _monitor_recv() method should be overridden. This _monitor_recv() method should capture some behavior of the pins, form a transaction, and pass this transaction to the internal _recv() method. The _monitor_recv() method is added to the cocotb scheduler during the __init__ phase, so it should not be awaited anywhere.

The primary use of a Monitor is as an interface for a Scoreboard.

Parameters
  • callback (callable) – Callback to be called with each recovered transaction as the argument. If the callback isn’t used, received transactions will be placed on a queue and the event used to notify any consumers.

  • event (cocotb.triggers.Event) – Event that will be called when a transaction is received through the internal _recv() method. Event.data is set to the received transaction.

kill()[source]

Kill the monitor coroutine.

add_callback(callback)[source]

Add function as a callback.

Parameters

callback (callable) – The function to call back.

wait_for_recv(timeout=None)[source]

With timeout, wait() for transaction to arrive on monitor and return its data.

Parameters

timeout – The timeout value for Timer. Defaults to None.

Returns

Data of received transaction.

_monitor_recv()[source]

Actual implementation of the receiver.

Sub-classes should override this method to implement the actual receive routine and call _recv() with the recovered transaction.

_recv(transaction)[source]

Common handling of a received transaction.

class cocotb_bus.monitors.BusMonitor(entity, name, clock, reset=None, reset_n=None, callback=None, event=None, bus_separator='_', array_idx=None)[source]

Bases: cocotb_bus.monitors.Monitor

Wrapper providing common functionality for monitoring buses.

property in_reset

Boolean flag showing whether the bus is in reset state or not.

Scoreboard

Common scoreboarding capability.

class cocotb_bus.scoreboard.Scoreboard(dut, reorder_depth=0, fail_immediately=True)[source]

Bases: object

Generic scoreboarding class.

We can add interfaces by providing a monitor and an expected output queue.

The expected output can either be a function which provides a transaction or a simple list containing the expected output.

Parameters
  • dut (SimHandle) – Handle to the DUT.

  • reorder_depth (int, optional) – Consider up to reorder_depth elements of the expected result list as passing matches. Default is 0, meaning only the first element in the expected result list is considered for a passing match.

  • fail_immediately (bool, optional) – Raise TestFailure immediately when something is wrong instead of just recording an error. Default is True.

property result

Determine the test result, do we have any pending data remaining?

Returns

If not all expected output was received or error were recorded during the test.

Return type

TestFailure

compare(got, exp, log, strict_type=True)[source]

Common function for comparing two transactions.

Can be re-implemented by a sub-class.

Parameters
  • got – The received transaction.

  • exp – The expected transaction.

  • log – The logger for reporting messages.

  • strict_type (bool, optional) – Require transaction type to match exactly if True, otherwise compare its string representation.

Raises

TestFailure – If received transaction differed from expected transaction when fail_immediately is True. If strict_type is True, also the transaction type must match.

add_interface(monitor, expected_output, compare_fn=None, reorder_depth=0, strict_type=True)[source]

Add an interface to be scoreboarded.

Provides a function which the monitor will callback with received transactions.

Simply check against the expected output.

Parameters
  • monitor – The monitor object.

  • expected_output – Queue of expected outputs.

  • compare_fn (callable, optional) – Function doing the actual comparison.

  • reorder_depth (int, optional) – Consider up to reorder_depth elements of the expected result list as passing matches. Default is 0, meaning only the first element in the expected result list is considered for a passing match.

  • strict_type (bool, optional) – Require transaction type to match exactly if True, otherwise compare its string representation.

Raises

TypeError – If no monitor is on the interface or compare_fn is not a callable function.

Generators

Set of general generic generators

cocotb.generators.repeat(obj, nrepeat=None)[source]

Generator to repeatedly yield the same object

Parameters
  • obj (any) – The object to yield

  • nrepeat (int, optional) – The number of times to repeatedly yield obj

Deprecated since version 1.4.1.

cocotb.generators.combine(generators)[source]

Generator for serially combining multiple generators together

Parameters

generators (iterable) – Generators to combine together

Deprecated since version 1.4.1.

cocotb.generators.gaussian(mean, sigma)[source]

Generate a Gaussian distribution indefinitely

Parameters
  • mean (int/float) – mean value

  • sigma (int/float) – Standard deviation

Deprecated since version 1.4.1.

cocotb.generators.sine_wave(amplitude, w, offset=0)[source]

Generates a sine wave that repeats forever

Parameters
  • amplitude (int/float) – peak deviation of the function from zero

  • w (int/float) – is the rate of change of the function argument

Yields

floats that form a sine wave

Deprecated since version 1.4.1.

Bit

Collection of generators for creating bit signals.

Typically we use a single bit to control backpressure or insert IDLE cycles onto a bus.

These yield a tuple which is intended to be interpreted as a number of cycles (ON,OFF)

cocotb.generators.bit.intermittent_single_cycles(mean=10, sigma=None)[source]

Generator to intermittently insert a single cycle pulse

Parameters
  • mean (int, optional) – Average number of cycles in between single cycle gaps

  • sigma (int, optional) – Standard deviation of gaps. mean/4 if sigma is None

Deprecated since version 1.4.1.

cocotb.generators.bit.random_50_percent(mean=10, sigma=None)[source]

50% duty cycle with random width

Parameters
  • mean (int, optional) – Average number of cycles on/off

  • sigma (int, optional) – Standard deviation of gaps. mean/4 if sigma is None

Deprecated since version 1.4.1.

cocotb.generators.bit.wave(on_ampl=30, on_freq=200, off_ampl=10, off_freq=100)[source]

Drive a repeating sine_wave pattern

Deprecated since version 1.4.1.

Byte

Collection of generators for creating byte streams.

Note that on Python 3, individual bytes are represented with integers.

cocotb.generators.byte.get_bytes(nbytes: int, generator: Iterator[int])bytes[source]

Get nbytes bytes from generator

Changed in version 1.4.0: This now returns bytes, not str.

Deprecated since version 1.4.1.

cocotb.generators.byte.random_data()Iterator[int][source]

Random bytes

Changed in version 1.4.0: This now returns integers, not single-character strs.

Deprecated since version 1.4.1.

cocotb.generators.byte.incrementing_data(increment=1)Iterator[int][source]

Incrementing bytes

Changed in version 1.4.0: This now returns integers, not single-character strs.

Deprecated since version 1.4.1.

cocotb.generators.byte.repeating_bytes(pattern: bytes = b'\x00')Iterator[int][source]

Repeat a pattern of bytes

Deprecated since version 1.4.1.

Clock

class cocotb.clock.Clock(signal, period, units='step')[source]

Simple 50:50 duty cycle clock driver.

Instances of this class should call its start() method and fork() the result. This will create a clocking thread that drives the signal at the desired period/frequency.

Example:

c = Clock(dut.clk, 10, 'ns')
cocotb.fork(c.start())
Parameters
  • signal – The clock pin/signal to be driven.

  • period (int) – The clock period. Must convert to an even number of timesteps.

  • units (str, optional) – One of 'step', 'fs', 'ps', 'ns', 'us', 'ms', 'sec'. When units is 'step', the timestep is determined by the simulator (see COCOTB_HDL_TIMEPRECISION).

If you need more features like a phase shift and an asymmetric duty cycle, it is simple to create your own clock generator (that you then fork()):

async def custom_clock():
    # pre-construct triggers for performance
    high_time = Timer(high_delay, units="ns")
    low_time = Timer(low_delay, units="ns")
    await Timer(initial_delay, units="ns")
    while True:
        dut.clk <= 1
        await high_time
        dut.clk <= 0
        await low_time

If you also want to change the timing during simulation, use this slightly more inefficient example instead where the Timers inside the while loop are created with current delay values:

async def custom_clock():
    while True:
        dut.clk <= 1
        await Timer(high_delay, units="ns")
        dut.clk <= 0
        await Timer(low_delay, units="ns")

high_delay = low_delay = 100
cocotb.fork(custom_clock())
await Timer(1000, units="ns")
high_delay = low_delay = 10  # change the clock speed
await Timer(1000, units="ns")

Changed in version 1.5: Support 'step' as the the units argument to mean “simulator time step”.

Deprecated since version 1.5: Using None as the the units argument is deprecated, use 'step' instead.

async start(cycles=None, start_high=True)[source]

Clocking coroutine. Start driving your clock by fork()ing a call to this.

Parameters
  • cycles (int, optional) – Cycle the clock cycles number of times, or if None then cycle the clock forever. Note: 0 is not the same as None, as 0 will cycle no times.

  • start_high (bool, optional) –

    Whether to start the clock with a 1 for the first half of the period. Default is True.

    New in version 1.3.

Utilities

Collection of handy functions.

cocotb.utils.get_sim_time(units=None)[source]

Retrieves the simulation time from the simulator.

Parameters

units (str or None, optional) – String specifying the units of the result (one of None, 'fs', 'ps', 'ns', 'us', 'ms', 'sec'). None will return the raw simulation time.

Returns

The simulation time in the specified units.

cocotb.utils.get_time_from_sim_steps(steps, units)[source]

Calculates simulation time in the specified units from the steps based on the simulator precision.

Parameters
  • steps (int) – Number of simulation steps.

  • units (str) – String specifying the units of the result (one of 'fs', 'ps', 'ns', 'us', 'ms', 'sec').

Returns

The simulation time in the specified units.

cocotb.utils.get_sim_steps(time, units='step')[source]

Calculates the number of simulation time steps for a given amount of time.

Parameters
  • time (numbers.Real or decimal.Decimal) – The value to convert to simulation time steps.

  • units (str, optional) – String specifying the units of the result (one of 'step', 'fs', 'ps', 'ns', 'us', 'ms', 'sec'). 'step' means time is already in simulation time steps.

Returns

The number of simulation time steps.

Return type

int

Raises

ValueError – If given time cannot be represented by simulator precision.

Changed in version 1.5: Support 'step' as the the units argument to mean “simulator time step”.

cocotb.utils.pack(ctypes_obj)[source]

Convert a ctypes structure into a Python string.

Parameters

ctypes_obj (ctypes.Structure) – The ctypes structure to convert to a string.

Returns

New Python string containing the bytes from memory holding ctypes_obj.

Deprecated since version 1.5: This function is deprecated, use bytes(ctypes_obj) instead.

cocotb.utils.unpack(ctypes_obj, string, bytes=None)[source]

Unpack a Python string into a ctypes structure.

If the length of string is not the correct size for the memory footprint of the ctypes structure then the bytes keyword argument must be used.

Parameters
  • ctypes_obj (ctypes.Structure) – The ctypes structure to pack into.

  • string (str) – String to copy over the ctypes_obj memory space.

  • bytes (int, optional) – Number of bytes to copy. Defaults to None, meaning the length of string is used.

Raises
  • ValueError – If length of string and size of ctypes_obj are not equal.

  • MemoryError – If bytes is longer than size of ctypes_obj.

Deprecated since version 1.5: Converting bytes to a ctypes object should be done with from_buffer_copy(). If you need to assign bytes into an existing ctypes object, use memoryview(ctypes_obj).cast('B')[:bytes] = string, see memoryview for details.

cocotb.utils.hexdump(x: bytes)str[source]

Hexdump a buffer.

Parameters

x – Object that supports conversion to bytes.

Returns

A string containing the hexdump.

Deprecated since version 1.4: Passing a str to this function is deprecated, as it is not an appropriate type for binary data. Doing so anyway will encode the string to latin1.

Example

>>> print(hexdump(b'this somewhat long string'))
0000   74 68 69 73 20 73 6F 6D 65 77 68 61 74 20 6C 6F   this somewhat lo
0010   6E 67 20 73 74 72 69 6E 67                        ng string
cocotb.utils.hexdiffs(x: bytes, y: bytes)str[source]

Return a diff string showing differences between two binary strings.

Parameters
  • x – Object that supports conversion to bytes.

  • y – Object that supports conversion to bytes.

Deprecated since version 1.4: Passing strs to this function is deprecated, as it is not an appropriate type for binary data. Doing so anyway will encode the string to latin1.

Example

>>> print(hexdiffs(b'a', b'b'))
0000      61                                               a
     0000 62                                               b

>>> print(hexdiffs(b'this short thing', b'this also short'))
0000      746869732073686F 7274207468696E67 this short thing
     0000 7468697320616C73 6F  2073686F7274 this also  short
class cocotb.utils.ParametrizedSingleton(*args, **kwargs)[source]

A metaclass that allows class construction to reuse an existing instance.

We use this so that RisingEdge(sig) and Join(coroutine) always return the same instance, rather than creating new copies.

cocotb.utils.reject_remaining_kwargs(name, kwargs)[source]

Helper function to emulate Python 3 keyword-only arguments.

Use as:

def func(x1, **kwargs):
    a = kwargs.pop('a', 1)
    b = kwargs.pop('b', 2)
    reject_remaining_kwargs('func', kwargs)
    ...

To emulate the Python 3 syntax:

def func(x1, *, a=1, b=2):
    ...

Deprecated since version 1.4: Since the minimum supported Python version is now 3.5, this function is not needed.

class cocotb.utils.lazy_property(fget)[source]

A property that is executed the first time, then cached forever.

It does this by replacing itself on the instance, which works because unlike @property it does not define __set__.

This should be used for expensive members of objects that are not always used.

cocotb.utils.want_color_output()[source]

Return True if colored output is possible/requested and not running in GUI.

Colored output can be explicitly requested by setting COCOTB_ANSI_OUTPUT to 1.

cocotb.utils.remove_traceback_frames(tb_or_exc, frame_names)[source]

Strip leading frames from a traceback

Parameters
  • tb_or_exc (Union[traceback, BaseException, exc_info]) – Object to strip frames from. If an exception is passed, creates a copy of the exception with a new shorter traceback. If a tuple from sys.exc_info is passed, returns the same tuple with the traceback shortened

  • frame_names (List[str]) – Names of the frames to strip, which must be present.

cocotb.utils.walk_coro_stack(coro)[source]

Walk down the coroutine stack, starting at coro.

Supports coroutines and generators.

cocotb.utils.extract_coro_stack(coro, limit=None)[source]

Create a list of pre-processed entries from the coroutine stack.

This is based on traceback.extract_tb().

If limit is omitted or None, all entries are extracted. The list is a traceback.StackSummary object, and each entry in the list is a traceback.FrameSummary object containing attributes filename, lineno, name, and line representing the information that is usually printed for a stack trace. The line is a string with leading and trailing whitespace stripped; if the source is not available it is None.

Logging

cocotb.log.default_config()[source]

Apply the default cocotb log formatting to the root logger.

This hooks up the logger to write to stdout, using either SimColourLogFormatter or SimLogFormatter depending on whether colored output is requested. It also adds a SimTimeContextFilter filter so that created_sim_time is available to the formatter.

The logging level for cocotb logs is set based on the COCOTB_LOG_LEVEL environment variable, which defaults to INFO.

If desired, this logging configuration can be overwritten by calling logging.basicConfig(..., force=True) (in Python 3.8 onwards), or by manually resetting the root logger instance. An example of this can be found in the section on Rotating Log Files.

New in version 1.4.

class cocotb.log.SimLogFormatter[source]

Bases: logging.Formatter

Log formatter to provide consistent log message handling.

This will only add simulator timestamps if the handler object this formatter is attached to has a SimTimeContextFilter filter attached, which cocotb ensures by default.

Takes no arguments.

class cocotb.log.SimColourLogFormatter[source]

Bases: cocotb.log.SimLogFormatter

Log formatter to provide consistent log message handling.

Takes no arguments.

class cocotb.log.SimTimeContextFilter[source]

Bases: logging.Filter

A filter to inject simulator times into the log records.

This uses the approach described in the Python logging cookbook.

This adds the created_sim_time attribute.

New in version 1.4.

logging.LogRecord.created_sim_time

The result of get_sim_time() at the point the log was created (in simulator units). The formatter is responsible for converting this to something like nanoseconds via get_time_from_sim_steps().

This is added by cocotb.log.SimTimeContextFilter.

Simulation Object Handles

Inheritance diagram of cocotb.handle

class cocotb.handle.SimHandleBase(handle, path)[source]

Bases: object

Base class for all simulation objects.

We maintain a handle which we can use for GPI calls.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

_name: str

The name of an object.

_type: str

The type of an object as a string.

_path: str

The path to this handle, or its name if this is the root handle.

_def_name: str

The name of a GPI object’s definition.

This is the value of vpiDefName for VPI, vhpiNameP for VHPI, and mti_GetPrimaryName for FLI. Support for this depends on the specific object type and simulator used.

_def_file: str

The name of the file that sources the object’s definition.

This is the value of vpiDefFile for VPI, vhpiFileNameP for VHPI, and mti_GetRegionSourceName for FLI. Support for this depends on the specific object type and simulator used.

class cocotb.handle.RegionObject(handle, path)[source]

Bases: cocotb.handle.SimHandleBase

A region object, such as a scope or namespace.

Region objects don’t have values, they are effectively scopes or namespaces.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

class cocotb.handle.HierarchyObject(handle, path)[source]

Bases: cocotb.handle.RegionObject

Hierarchy objects are namespace/scope objects.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

_id(name, extended: bool = True)[source]

Query the simulator for an object with the specified name, and cache the result to build a tree of objects.

If extended is True, run the query only for VHDL extended identifiers. For Verilog, only extended=False is supported.

class cocotb.handle.HierarchyArrayObject(handle, path)[source]

Bases: cocotb.handle.RegionObject

Hierarchy Arrays are containers of Hierarchy Objects.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

class cocotb.handle.NonHierarchyObject(handle, path)[source]

Bases: cocotb.handle.SimHandleBase

Common base class for all non-hierarchy objects.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

property value

The value of this simulation object.

Note

When setting this property, the value is stored by the Scheduler and all stored values are written at the same time at the end of the current simulator time step.

Use setimmediatevalue() to set the value immediately.

setimmediatevalue(value)[source]

Assign a value to this simulation object immediately.

class cocotb.handle.ConstantObject(handle, path, handle_type)[source]

Bases: cocotb.handle.NonHierarchyObject

An object which has a value that can be read, but not set.

The value is cached in the class since it is fixed at elaboration time and won’t change within a simulation.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

  • handle_type – The type of the handle (simulator.INTEGER, simulator.ENUM, simulator.REAL, simulator.STRING).

property value

The value of this simulation object.

class cocotb.handle.NonHierarchyIndexableObject(handle, path)[source]

Bases: cocotb.handle.NonHierarchyObject

A non-hierarchy indexable object.

Getting and setting the current value of an array is done by iterating through sub-handles in left-to-right order.

Given an HDL array arr:

Verilog

VHDL

arr.value is equivalent to

arr[4:7]

arr(4 to 7)

[arr[4].value, arr[5].value, arr[6].value, arr[7].value]

arr[7:4]

arr(7 downto 4)

[arr[7].value, arr[6].value, arr[5].value, arr[4].value]

When setting the signal as in arr.value = ..., the same index equivalence as noted in the table holds.

Warning

Assigning a value to a sub-handle:

  • Wrong: dut.some_array.value[0] = 1 (gets value as a list then updates index 0)

  • Correct: dut.some_array[0].value = 1

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

property value

The value of this simulation object.

Note

When setting this property, the value is stored by the Scheduler and all stored values are written at the same time at the end of the current simulator time step.

Use setimmediatevalue() to set the value immediately.

class cocotb.handle.NonConstantObject(handle, path)[source]

Bases: cocotb.handle.NonHierarchyIndexableObject

A non-constant object

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

drivers()[source]

An iterator for gathering all drivers for a signal.

This is currently only available for VPI. Also, only a few simulators implement this.

loads()[source]

An iterator for gathering all loads on a signal.

This is currently only available for VPI. Also, only a few simulators implement this.

class cocotb.handle.ModifiableObject(handle, path)[source]

Bases: cocotb.handle.NonConstantObject

Base class for simulator objects whose values can be modified.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

property value

The value of this simulation object.

Note

When setting this property, the value is stored by the Scheduler and all stored values are written at the same time at the end of the current simulator time step.

Use setimmediatevalue() to set the value immediately.

class cocotb.handle.RealObject(handle, path)[source]

Bases: cocotb.handle.ModifiableObject

Specific object handle for Real signals and variables.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

property value

The value of this simulation object.

Note

When setting this property, the value is stored by the Scheduler and all stored values are written at the same time at the end of the current simulator time step.

Use setimmediatevalue() to set the value immediately.

class cocotb.handle.EnumObject(handle, path)[source]

Bases: cocotb.handle.ModifiableObject

Specific object handle for enumeration signals and variables.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

property value

The value of this simulation object.

Note

When setting this property, the value is stored by the Scheduler and all stored values are written at the same time at the end of the current simulator time step.

Use setimmediatevalue() to set the value immediately.

class cocotb.handle.IntegerObject(handle, path)[source]

Bases: cocotb.handle.ModifiableObject

Specific object handle for integer and enumeration signals and variables.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

property value

The value of this simulation object.

Note

When setting this property, the value is stored by the Scheduler and all stored values are written at the same time at the end of the current simulator time step.

Use setimmediatevalue() to set the value immediately.

class cocotb.handle.StringObject(handle, path)[source]

Bases: cocotb.handle.ModifiableObject

Specific object handle for String variables.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

property value

The value of this simulation object.

Note

When setting this property, the value is stored by the Scheduler and all stored values are written at the same time at the end of the current simulator time step.

Use setimmediatevalue() to set the value immediately.

cocotb.handle.SimHandle(handle, path=None)[source]

Factory function to create the correct type of SimHandle object.

Parameters
  • handle (int) – The GPI handle to the simulator object.

  • path (str) – Path to this handle, None if root.

Returns

The SimHandle object.

Raises

NotImplementedError – If no matching object for GPI type could be found.

Assignment Methods

class cocotb.handle.Deposit(value)[source]

Action used for placing a value into a given handle.

class cocotb.handle.Force(value)[source]

Action used to force a handle to a given value until a release is applied.

class cocotb.handle.Freeze[source]

Action used to make a handle keep its current value until a release is used.

class cocotb.handle.Release[source]

Action used to stop the effects of a previously applied force/freeze action.

Implemented Testbench Structures

Drivers

AMBA

Advanced Microcontroller Bus Architecture.

class cocotb_bus.drivers.amba.AXI4Master(entity: cocotb.handle.SimHandleBase, name: str, clock: cocotb.handle.SimHandleBase, **kwargs: Any)[source]

AXI4 Master

TODO: Kill all pending transactions if reset is asserted.

Constructor for a driver instance.

write(address: int, value: Union[int, Sequence[int]], *, size: Optional[int] = None, burst: cocotb_bus.drivers.amba.AXIBurst = <AXIBurst.INCR: 1>, byte_enable: Union[int, None, Sequence[Optional[int]]] = None, address_latency: int = 0, data_latency: int = 0, sync: bool = True)None[source]

Write a value to an address.

With unaligned writes (when address is not a multiple of size), only the low size - address % size Bytes are written for: * the last element of value for INCR or WRAP bursts, or * every element of value for FIXED bursts.

Parameters
  • address – The address to write to.

  • value – The data value(s) to write.

  • size – The size (in bytes) of each beat. Defaults to None (width of the data bus).

  • burst – The burst type, either FIXED, INCR or WRAP. Defaults to INCR.

  • byte_enable – Which bytes in value to actually write. Defaults to None (write all bytes).

  • address_latency – Delay before setting the address (in clock cycles). Default is no delay.

  • data_latency – Delay before setting the data value (in clock cycles). Default is no delay.

  • sync – Wait for rising edge on clock initially. Defaults to True.

Raises
  • ValueError – If any of the input parameters is invalid.

  • AXIProtocolError – If write response from AXI is not OKAY.

read(address: int, length: int = 1, *, size: Optional[int] = None, burst: cocotb_bus.drivers.amba.AXIBurst = <AXIBurst.INCR: 1>, return_rresp: bool = False, sync: bool = True)Union[List[cocotb.binary.BinaryValue], List[Tuple[cocotb.binary.BinaryValue, cocotb_bus.drivers.amba.AXIxRESP]]][source]

Read from an address.

With unaligned reads (when address is not a multiple of size) with INCR or WRAP bursts, the last element of the returned read data will be only the low-order size - address % size Bytes of the last word. With unaligned reads with FIXED bursts, every element of the returned read data will be only the low-order size - address % size Bytes.

Parameters
  • address – The address to read from.

  • length – Number of words to transfer. Defaults to 1.

  • size – The size (in bytes) of each beat. Defaults to None (width of the data bus).

  • burst – The burst type, either FIXED, INCR or WRAP. Defaults to INCR.

  • return_rresp – Return the list of RRESP values, instead of raising an AXIProtocolError in case of not OKAY. Defaults to False.

  • sync – Wait for rising edge on clock initially. Defaults to True.

Returns

The read data values or, if return_rresp is True, a list of pairs each containing the data and RRESP values.-

Raises
  • ValueError – If any of the input parameters is invalid.

  • AXIProtocolError – If read response from AXI is not OKAY and return_rresp is False

  • AXIReadBurstLengthMismatch – If the received number of words does not match the requested one.

class cocotb_bus.drivers.amba.AXI4LiteMaster(entity: cocotb.handle.SimHandleBase, name: str, clock: cocotb.handle.SimHandleBase, **kwargs: Any)[source]

AXI4-Lite Master

Constructor for a driver instance.

write(address: int, value: int, byte_enable: Optional[int] = None, address_latency: int = 0, data_latency: int = 0, sync: bool = True)cocotb.binary.BinaryValue[source]

Write a value to an address.

Parameters
  • address – The address to write to.

  • value – The data value to write.

  • byte_enable – Which bytes in value to actually write. Defaults to None (write all bytes).

  • address_latency – Delay before setting the address (in clock cycles). Default is no delay.

  • data_latency – Delay before setting the data value (in clock cycles). Default is no delay.

  • sync – Wait for rising edge on clock initially. Defaults to True.

  • Returns – The write response value.

  • Raises – ValueError: If any of the input parameters is invalid. AXIProtocolError: If write response from AXI is not OKAY.

read(address: int, sync: bool = True)cocotb.binary.BinaryValue[source]

Read from an address.

Parameters
  • address – The address to read from.

  • length – Number of words to transfer

  • sync – Wait for rising edge on clock initially. Defaults to True.

Returns

The read data value.

Raises

AXIProtocolError – If read response from AXI is not OKAY.

class cocotb_bus.drivers.amba.AXI4Slave(entity, name, clock, memory, callback=None, event=None, big_endian=False, **kwargs)[source]

AXI4 Slave

Monitors an internal memory and handles read and write requests.

Constructor for a driver instance.

Avalon

class cocotb_bus.drivers.avalon.AvalonMM(entity, name, clock, **kwargs)[source]

Bases: cocotb_bus.drivers.BusDriver

Avalon Memory Mapped Interface (Avalon-MM) Driver.

Currently we only support the mode required to communicate with SF avalon_mapper which is a limited subset of all the signals.

Blocking operation is all that is supported at the moment, and for the near future as well. Posted responses from a slave are not supported.

Constructor for a driver instance.

class cocotb_bus.drivers.avalon.AvalonMaster(entity, name, clock, **kwargs)[source]

Bases: cocotb_bus.drivers.avalon.AvalonMM

Avalon Memory Mapped Interface (Avalon-MM) Master.

Constructor for a driver instance.

read(address: int, sync: bool = True)cocotb.binary.BinaryValue[source]

Issue a request to the bus and block until this comes back.

Simulation time still progresses but syntactically it blocks.

Parameters
  • address – The address to read from.

  • sync – Wait for rising edge on clock initially. Defaults to True.

Returns

The read data value.

Raises

TestError – If master is write-only.

write(address: int, value: int)None[source]

Issue a write to the given address with the specified value.

Parameters
  • address – The address to write to.

  • value – The data value to write.

Raises

TestError – If master is read-only.

class cocotb_bus.drivers.avalon.AvalonMemory(entity, name, clock, readlatency_min=1, readlatency_max=1, memory=None, avl_properties={}, **kwargs)[source]

Bases: cocotb_bus.drivers.BusDriver

Emulate a memory, with back-door access.

Constructor for a driver instance.

class cocotb_bus.drivers.avalon.AvalonST(entity, name, clock, *, config={}, **kwargs)[source]

Bases: cocotb_bus.drivers.ValidatedBusDriver

Avalon Streaming Interface (Avalon-ST) Driver

Constructor for a driver instance.

class cocotb_bus.drivers.avalon.AvalonSTPkts(entity, name, clock, *, config={}, **kwargs)[source]

Bases: cocotb_bus.drivers.ValidatedBusDriver

Avalon Streaming Interface (Avalon-ST) Driver, packetized.

Constructor for a driver instance.

OPB

class cocotb_bus.drivers.opb.OPBMaster(entity, name, clock, **kwargs)[source]

Bases: cocotb_bus.drivers.BusDriver

On-chip peripheral bus master.

Constructor for a driver instance.

read(address: int, sync: bool = True)cocotb.binary.BinaryValue[source]

Issue a request to the bus and block until this comes back.

Simulation time still progresses but syntactically it blocks.

Parameters
  • address – The address to read from.

  • sync – Wait for rising edge on clock initially. Defaults to True.

Returns

The read data value.

Raises

OPBException – If read took longer than 16 cycles.

write(address: int, value: int, sync: bool = True)None[source]

Issue a write to the given address with the specified value.

Parameters
  • address – The address to read from.

  • value – The data value to write.

  • sync – Wait for rising edge on clock initially. Defaults to True.

Raises

OPBException – If write took longer than 16 cycles.

XGMII

class cocotb_bus.drivers.xgmii.XGMII(signal: cocotb.handle.SimHandleBase, clock: cocotb.handle.SimHandleBase, interleaved: bool = True)[source]

Bases: cocotb_bus.drivers.Driver

XGMII (10 Gigabit Media Independent Interface) driver.

Parameters
  • signal – The XGMII data bus.

  • clock – The associated clock (assumed to be driven by another coroutine).

  • interleaved – Whether control bits are interleaved with the data bytes or not.

If interleaved the bus is

byte0, byte0_control, byte1, byte1_control, …

Otherwise expect

byte0, byte1, …, byte0_control, byte1_control, …

static layer1(packet: bytes)bytes[source]

Take an Ethernet packet (as a string) and format as a layer 1 packet.

Pad to 64 bytes, prepend preamble and append 4-byte CRC on the end.

Parameters

packet – The Ethernet packet to format.

Returns

The formatted layer 1 packet.

idle()[source]

Helper function to set bus to IDLE state.

terminate(index: int)None[source]

Helper function to terminate from a provided lane index.

Parameters

index – The index to terminate.

Monitors

Avalon

class cocotb_bus.monitors.avalon.AvalonST(entity, name, clock, *, config={}, **kwargs)[source]

Bases: cocotb_bus.monitors.BusMonitor

Avalon-ST bus.

Non-packetized so each valid word is a separate transaction.

class cocotb_bus.monitors.avalon.AvalonSTPkts(entity, name, clock, *, config={}, report_channel=False, **kwargs)[source]

Bases: cocotb_bus.monitors.BusMonitor

Packetized Avalon-ST bus.

Parameters
  • entity – see BusMonitor

  • name – see BusMonitor

  • clock – see BusMonitor

  • config (dict) – bus configuration options

  • report_channel (bool) – report channel with data, default is False Setting to True on bus without channel signal will give an error

XGMII

class cocotb_bus.monitors.xgmii.XGMII(signal, clock, interleaved=True, callback=None, event=None)[source]

Bases: cocotb_bus.monitors.Monitor

XGMII (10 Gigabit Media Independent Interface) Monitor.

Assumes a single vector, either 4 or 8 bytes plus control bit for each byte.

If interleaved is True then the control bits are adjacent to the bytes.

Changed in version 1.4.0: This now emits packets of type bytes rather than str, which matches the behavior of cocotb.drivers.xgmii.XGMII.

Parameters
  • signal (SimHandle) – The XGMII data bus.

  • clock (SimHandle) – The associated clock (assumed to be driven by another coroutine).

  • interleaved (bool, optional) – Whether control bits are interleaved with the data bytes or not.

If interleaved the bus is

byte0, byte0_control, byte1, byte1_control, …

Otherwise expect

byte0, byte1, …, byte0_control, byte1_control, …

Miscellaneous

Asynchronous Queues

class cocotb.queue.Queue(maxsize: int = 0)[source]

A queue, useful for coordinating producer and consumer coroutines.

If maxsize is less than or equal to 0, the queue size is infinite. If it is an integer greater than 0, then put() will block when the queue reaches maxsize, until an item is removed by get().

qsize()int[source]

Number of items in the queue.

property maxsize

Number of items allowed in the queue.

empty()bool[source]

Return True if the queue is empty, False otherwise.

full()bool[source]

Return True if there are maxsize() items in the queue.

Note

If the Queue was initialized with maxsize=0 (the default), then full() is never True.

async put(item: T)None[source]

Put an item into the queue.

If the queue is full, wait until a free slot is available before adding the item.

put_nowait(item: T)None[source]

Put an item into the queue without blocking.

If no free slot is immediately available, raise asyncio.QueueFull.

async get()T[source]

Remove and return an item from the queue.

If the queue is empty, wait until an item is available.

get_nowait()T[source]

Remove and return an item from the queue.

Return an item if one is immediately available, else raise asyncio.QueueEmpty.

class cocotb.queue.PriorityQueue(maxsize: int = 0)[source]

A subclass of Queue; retrieves entries in priority order (smallest item first).

Entries are typically tuples of the form (priority number, data).

class cocotb.queue.LifoQueue(maxsize: int = 0)[source]

A subclass of Queue; retrieves most recently added entries first.

Other Runtime Information

cocotb.argv = None

The argument list as seen by the simulator

cocotb.SIM_NAME = None

The running simulator product information. None if cocotb was not loaded from a simulator

cocotb.SIM_VERSION = None

The version of the running simulator. None if cocotb was not loaded from a simulator

cocotb.RANDOM_SEED = None

The value passed to the Python default random number generator. See RANDOM_SEED for details on how the value is computed.

cocotb.plusargs = None

A dictionary of “plusargs” handed to the simulation. See PLUSARGS for details.

cocotb.LANGUAGE = None

The value of TOPLEVEL_LANG

cocotb.top = None

A handle to the TOPLEVEL entity/module.

This is equivalent to the DUT parameter given to cocotb tests, so it can be used wherever that variable can be used. It is particularly useful for extracting information about the DUT in module-level class and function definitions; and in parameters to TestFactorys. None if cocotb was not loaded from a simulator.

Signal Tracer for WaveDrom

class cocotb.wavedrom.Wavedrom(obj, name='')[source]

Base class for a WaveDrom compatible tracer.

sample()[source]

Record a sample of the signal value at this point in time.

clear()[source]

Delete all sampled data.

get(add_clock=True)[source]

Return the samples as a list suitable for use with WaveDrom.

class cocotb.wavedrom.trace(*args, clk=None)[source]

Context manager to enable tracing of signals.

Arguments are an arbitrary number of signals or buses to trace. We also require a clock to sample on, passed in as a keyword argument.

Usage:

with trace(sig1, sig2, a_bus, clk=clk) as waves:
    # Stuff happens, we trace it

    # Dump to JSON format compatible with WaveDrom
    j = waves.dumpj()

Implementation Details

Note

In general, nothing in this section should be interacted with directly - these components work mostly behind the scenes.

The Scheduler

cocotb.scheduler = None

The global scheduler instance.

class cocotb.scheduler.Scheduler[source]

The main scheduler.

Here we accept callbacks from the simulator and schedule the appropriate coroutines.

A callback fires, causing the react method to be called, with the trigger that caused the callback as the first argument.

We look up a list of coroutines to schedule (indexed by the trigger) and schedule them in turn.

Attention

Implementors should not depend on the scheduling order!

Some additional management is required since coroutines can return a list of triggers, to be scheduled when any one of the triggers fires. To ensure we don’t receive spurious callbacks, we have to un-prime all the other triggers when any one fires.

Due to the simulator nuances and fun with delta delays we have the following modes:

Normal mode
  • Callbacks cause coroutines to be scheduled

  • Any pending writes are cached and do not happen immediately

ReadOnly mode
  • Corresponds to cbReadOnlySynch (VPI) or vhpiCbRepEndOfTimeStep (VHPI). In this state we are not allowed to perform writes.

Write mode
  • Corresponds to cbReadWriteSynch (VPI) or vhpiCbRepLastKnownDeltaCycle (VHPI) In this mode we play back all the cached write updates.

We can legally transition from Normal to Write by registering a ReadWrite callback, however usually once a simulator has entered the ReadOnly phase of a given timestep then we must move to a new timestep before performing any writes. The mechanism for moving to a new timestep may not be consistent across simulators and therefore we provide an abstraction to assist with compatibility.

Unless a coroutine has explicitly requested to be scheduled in ReadOnly mode (for example wanting to sample the finally settled value after all delta delays) then it can reasonably be expected to be scheduled during “normal mode” i.e. where writes are permitted.

react(trigger)[source]

Deprecated since version 1.5: This function is now private.

unschedule(coro)[source]

Deprecated since version 1.5: This function is now private.

queue(coroutine)[source]

Deprecated since version 1.5: This function is now private.

queue_function(coro)[source]

Deprecated since version 1.5: This function is now private.

run_in_executor(func, *args, **kwargs)[source]

Deprecated since version 1.5: This function is now private.

static create_task(coroutine: Any)cocotb.decorators.RunningTask[source]

Checks to see if the given object is a schedulable coroutine object and if so, returns it

add(coroutine: Union[cocotb.decorators.RunningTask, collections.abc.Coroutine])cocotb.decorators.RunningTask[source]

Add a new coroutine.

Just a wrapper around self.schedule which provides some debug and useful error messages in the event of common gotchas.

start_soon(coro: Union[collections.abc.Coroutine, cocotb.decorators.RunningTask])cocotb.decorators.RunningTask[source]

Schedule a coroutine to be run concurrently, starting after the current coroutine yields control.

In contrast to fork() which starts the given coroutine immediately, this function starts the given coroutine only after the current coroutine yields control. This is useful when the coroutine to be forked has logic before the first await that may not be safe to execute immediately.

add_test(test_coro)[source]

Deprecated since version 1.5: This function is now private.

schedule(coroutine, trigger=None)[source]

Deprecated since version 1.5: This function is now private.

finish_test(exc)[source]

Deprecated since version 1.5: This function is now private.

finish_scheduler(exc)[source]

Deprecated since version 1.5: This function is now private.

cleanup()[source]

Deprecated since version 1.5: This function is now private.

The Regression Manager

cocotb.regression_manager = None

The global regression manager instance.

class cocotb.regression.RegressionManager(dut: cocotb.handle.SimHandle, tests: Iterable[cocotb.decorators.test], hooks: Iterable[cocotb.decorators.hook])[source]

Encapsulates all regression capability into a single place

Parameters
  • dut (SimHandle) – The root handle to pass into test functions.

  • tests (Iterable[Test]) – tests to run

  • hooks (Iterable[Hook]) – hooks to tun

classmethod from_discovery(dut: cocotb.handle.SimHandle)[source]

Obtains the test and hook lists by discovery.

See MODULE and TESTCASE for details on how tests are discovered.

Parameters

dut (SimHandle) – The root handle to pass into test functions.

next_test()Optional[cocotb.decorators.test][source]

Get the next test to run

handle_result(test: cocotb.decorators.RunningTask)None[source]

Handle a test completing.

Dump result to XML and schedule the next test (if any). Entered by the scheduler.

Parameters

test – The test that completed

The cocotb.simulator module

This module is a Python wrapper to libgpi. It should not be considered public API, but is documented here for developers of cocotb.

cocotb.simulator.get_precision()int

Get the precision of the simulator in powers of 10.

For example, if -12 is returned, the simulator’s time precision is 10**-12 or 1 ps.

cocotb.simulator.get_root_handle(name: str)cocotb.simulator.gpi_sim_hdl

Get the root handle.

cocotb.simulator.get_sim_time()Tuple[int, int]

Get the current simulation time.

Time is represented as a tuple of 32 bit integers ([low32, high32]) comprising a single 64 bit integer.

cocotb.simulator.get_simulator_product()str

Get the simulator’s product string.

cocotb.simulator.get_simulator_version()str

Get the simulator’s product version string.

class cocotb.simulator.gpi_cb_hdl

GPI callback handle

deregister()None

De-register this callback.

class cocotb.simulator.gpi_iterator_hdl

GPI iterator handle.

class cocotb.simulator.gpi_sim_hdl

GPI object handle

Contains methods for getting and setting the value of a GPI object, and introspection.

get_const()bool

Return True if the object is a constant.

get_definition_file()str

Get the file that sources the object’s definition.

get_definition_name()str

Get the name of a GPI object’s definition.

get_handle_by_index(index: int)cocotb.simulator.gpi_sim_hdl

Get a handle to a child object by index.

get_handle_by_name(name: str)cocotb.simulator.gpi_sim_hdl

Get a handle to a child object by name.

get_name_string()str

Get the name of an object as a string.

get_num_elems()int

Get the number of elements contained in the handle.

get_range()Tuple[int, int]

Get the range of elements (tuple) contained in the handle, return None if not indexable.

get_signal_val_binstr()str

Get the value of a logic vector signal as a string of (0, 1, X, etc.), one element per character.

get_signal_val_long()int

Get the value of a signal as an integer.

get_signal_val_real()float

Get the value of a signal as a float.

get_signal_val_str()bytes

Get the value of a signal as a byte string.

get_type()int

Get the GPI type of an object as an enum.

get_type_string()str

Get the GPI type of an object as a string.

iterate(mode: int)cocotb.simulator.gpi_iterator_hdl

Get an iterator handle to loop over all members in an object.

set_signal_val_binstr(action: int, value: str)None

Set the value of a logic vector signal using a string of (0, 1, X, etc.), one element per character.

set_signal_val_int(action, value, /)

Set the value of a signal using an int

set_signal_val_real(action: int, value: float)None

Set the value of a signal using a float.

set_signal_val_str(action: int, value: bytes)None

Set the value of a signal using a user-encoded string.

cocotb.simulator.is_running()bool

Returns True if the caller is running within a simulator.

New in version 1.4.

cocotb.simulator.log_level(level: int)None

Set the log level for GPI.

cocotb.simulator.log_msg(name: str, path: str, funcname: str, lineno: int, msg: str)None

Log a message.

cocotb.simulator.register_nextstep_callback(func: Callable[, None], *args: Any)cocotb.simulator.gpi_cb_hdl

Register a callback for the cbNextSimTime callback.

cocotb.simulator.register_readonly_callback(func: Callable[, None], *args: Any)cocotb.simulator.gpi_cb_hdl

Register a callback for the read-only section.

cocotb.simulator.register_rwsynch_callback(func: Callable[, None], *args: Any)cocotb.simulator.gpi_cb_hdl

Register a callback for the read-write section.

cocotb.simulator.register_timed_callback(time: int, func: Callable[, None], *args: Any)cocotb.simulator.gpi_cb_hdl

Register a timed callback.

cocotb.simulator.register_value_change_callback(signal: cocotb.simulator.gpi_sim_hdl, func: Callable[, None], edge: int, *args: Any)cocotb.simulator.gpi_cb_hdl

Register a signal change callback.

cocotb.simulator.stop_simulator()None

Instruct the attached simulator to stop. Users should not call this function.

The cocotb-config script

usage: cocotb-config [-h] [--prefix] [--share] [--makefiles] [--python-bin]
                     [--help-vars] [--libpython] [--lib-dir]
                     [--lib-name INTERFACE SIMULATOR]
                     [--lib-name-path INTERFACE SIMULATOR] [-v]

Named Arguments

--prefix

echo the package-prefix of cocotb

--share

echo the package-share of cocotb

--makefiles

echo the package-makefiles of cocotb

--python-bin

echo the path to the Python binary cocotb is installed for

--help-vars

show help about supported variables

--libpython

Print the absolute path to the libpython associated with the current Python installation

--lib-dir

Print the absolute path to the interface libraries location

--lib-name

Print the name of interface library for given interface (VPI/VHPI/FLI) and simulator

--lib-name-path

Print the absolute path of interface library for given interface (VPI/VHPI/FLI) and simulator

-v, --version

echo the version of cocotb