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]

Creates a TestError exception and raises it after printing a traceback.

Parameters
  • obj – Object with a log method.

  • msg – The log message.

Type msg

str

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.

Parameters
  • obj – Object with a log method.

  • msg – The log message.

Type msg

str

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

Helper exception needed for Python versions prior to 3.3.

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

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

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

Exception thrown by external functions.

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

Exception showing that test was completed with severity Error.

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

Exception showing that test was completed with severity Failure.

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

Exception showing that test was completed successfully.

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

Exception showing that simulator exited unsuccessfully.

Writing and Generating tests

class cocotb.test(f, timeout=None, expect_fail=False, expect_error=False, skip=False, stage=None)[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.

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

Parameters
  • timeout – value representing simulation timeout (not implemented).

  • expect_fail – Don’t mark the result as a failure if the test fails.

  • expect_error – Don’t mark the result as an error if an error is raised. This is for cocotb internal regression use when a simulator error is expected.

  • skip – Don’t execute this test as part of the regression.

  • stage – Order tests logically into stages, where multiple tests can share a stage.

Type timeout

int, optional

Type expect_fail

bool, optional

Type expect_error

bool, optional

Type skip

bool, optional

Type stage

int, optional

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 currently creates a new execution context 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 function to internally block while externally appear to yield.

class cocotb.hook(f)[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.

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

Used to automatically generate tests.

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 and idles and have some packet generation routines gen_a and gen_b:

>>> tf = TestFactory(run_test)
>>> tf.add_option('data_in', [gen_a, gen_b])
>>> tf.add_option('backpressure', [None, random_backpressure])
>>> tf.add_option('idles', [None, random_idles])
>>> tf.generate_tests()
We would get the following tests:
  • gen_a with no backpressure and no idles

  • gen_a with no backpressure and random_idles

  • gen_a with random_backpressure and no idles

  • gen_a with random_backpressure and random_idles

  • gen_b with no backpressure and no idles

  • gen_b with no backpressure and random_idles

  • gen_b with random_backpressure and no idles

  • gen_b with random_backpressure and random_idles

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.

add_option(name, optionlist)[source]

Add a named option to the test.

Parameters
  • name – Name of the option. Passed to test as a keyword argument.

  • optionlist – A list of possible options for this test knob.

Type name

str

Type optionlist

list

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

Generates 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 – 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 – 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.

Type prefix

str

Type postfix

str

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(repr(vec.buff))
'*'
assign(value)[source]

Decides how best to assign the value to the vector.

We possibly try to be a bit too clever here by first of all trying to assign the raw string as a binstring, however if the string contains any characters that aren’t 0, 1, X or Z then we interpret the string as a binary buffer.

Parameters

value – The value to assign.

Type value

str or int or long

get_value()[source]

Return the integer representation of the underlying vector.

get_value_signed()[source]

Return the signed integer representation of the underlying vector.

is_resolvable

Does the value contain any X’s? Inquiring minds want to know.

value

Integer access to the value. deprecated

integer

The integer representation of the underlying vector.

signed_integer

The signed integer representation of the underlying vector.

get_buff()[source]

Attribute buff represents the value as a binary string buffer.

>>> "0100000100101111".buff == "A/"
True
buff

Access to the value as a buffer.

get_binstr()[source]

Attribute binstr is the binary representation stored as a string of 1 and 0.

binstr

Access to the binary string.

n_bits

Access to the number of bits of the binary value.

class cocotb.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 ‘_’).

Todo

Support for struct/record ports where signals are member names.

drive(obj, strict=False)[source]

Drives values onto the bus.

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

  • strict – Check that all signals are being assigned.

Type strict

bool, optional

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.

Rtype

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 – Check that all signals being sampled are present in obj.

Type strict

bool, optional

Raises AttributeError

If attribute is missing in obj when strict=True.

class cocotb.clock.Clock(signal, period, units=None)[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 – The clock period. Must convert to an even number of timesteps.

  • units – One of None, 'fs', 'ps', 'ns', 'us', 'ms', 'sec'. When no units is given (None) the timestep is determined by the simulator.

Type period

int

Type units

str, optional

Triggers

Triggers are used to indicate when the scheduler should resume coroutine execution. Typically a coroutine will yield a trigger or a list of triggers.

class cocotb.triggers.Trigger[source]

Base class to derive from.

Simulation Timing

class cocotb.triggers.Timer(time_ps, units=None)[source]

Execution will resume when the specified time period expires.

Consumes simulation time.

class cocotb.triggers.ReadOnly[source]

Execution will resume when the readonly portion of the sim cycles is reached.

class cocotb.triggers.NextTimeStep[source]

Execution will resume when the next time step is started.

class cocotb.triggers.ClockCycles(signal, num_cycles, rising=True)[source]

Execution will resume after num_cycles rising edges or num_cycles falling edges.

Python Triggers

class cocotb.triggers.Combine(*args)[source]

Waits until all the passed triggers have fired.

Like most triggers, this simply returns itself.

class cocotb.triggers.Event(name='')[source]

Event to permit synchronisation between two coroutines.

prime(callback, trigger)[source]

FIXME: document

set(data=None)[source]

Wake up any coroutines blocked on this event.

wait()[source]

This can be yielded to block this coroutine until another wakes it.

If the event has already been fired, this returns NullTrigger. To reset the event (and enable the use of wait again), clear() should be called.

clear()[source]

Clear this event that has fired.

Subsequent calls to wait() will block until set() is called again.

class cocotb.triggers.Lock(name='')[source]

Lock primitive (not re-entrant).

prime(callback, trigger)[source]

FIXME: document

acquire()[source]

This can be yielded to block until the lock is acquired.

release()[source]

Release the lock.

class cocotb.triggers.Join(coroutine)[source]

Join a coroutine, firing when it exits.

retval

document

Type

FIXME

prime(callback)[source]

FIXME: document

Testbench Structure

Driver

class cocotb.drivers.Driver[source]

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

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

kill()[source]

Kill the coroutine sending stuff.

append(transaction, callback=None, event=None, **kwargs)[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.

Type transaction

any

Type callback

callable, optional

Type event

optional

clear()[source]

Clear any queued transactions without sending them onto the bus.

send[source]

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

Sends the transaction over the bus.

Parameters
  • transaction – The transaction to be sent.

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

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

Type transaction

any

Type sync

bool, optional

Type **kwargs

dict

_driver_send(transaction, sync=True, **kwargs)[source]

Actual implementation of the send.

Subclasses should override this method to implement the actual send() routine.

Parameters
  • transaction – The transaction to be sent.

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

  • **kwargs – Additional arguments if required for protocol implemented in subclass.

Type transaction

any

Type sync

boolean, optional

_send[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 – Synchronise the transfer by waiting for a rising edge.

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

Type transaction

any

Type callback

callable, optional

Type event

optional

Type sync

boolean, optional

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

Bases: object

Drives a signal onto a single bit.

Useful for exercising ready / valid.

start(generator=None)[source]

Start generating data.

Parameters

generator – Generator yielding data.

Type generator

optional

stop()[source]

Stop generating data.

class cocotb.drivers.BusDriver(entity, name, clock, **kwargs)[source]

Bases: cocotb.drivers.Driver

Wrapper around common functionality for busses 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 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.

  • array_idx – Optional index when signal is an array.

Type entity

SimHandle

Type name

str or None

Type clock

SimHandle

Type array_idx

int or None, optional

_driver_send[source]

Implementation for BusDriver.

Parameters
  • transaction – The transaction to send.

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

Type sync

bool, optional

_wait_for_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[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.

Monitor

class cocotb.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 subclassed and the internal _monitor_recv method should be overridden and decorated as a coroutine. 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 yielded anywhere.

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

Parameters
  • callback – 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 – Object that supports a set method that will be called when a transaction is received through the internal _recv method.

Type callback

callable

Type event

event

for ... in 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.

Type timeout

optional

Returns: Data of received transaction.

_monitor_recv[source]

Actual implementation of the receiver.

Subclasses 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.monitors.BusMonitor(entity, name, clock, reset=None, reset_n=None, callback=None, event=None, bus_separator='_', array_idx=None)[source]

Bases: cocotb.monitors.Monitor

Wrapper providing common functionality for monitoring busses.

in_reset

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

Scoreboard

Common scoreboarding capability.

class cocotb.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.

Todo

Statistics for end-of-test summary etc.

Parameters
  • dut – Handle to the DUT.

  • reorder_depth – 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 – Raise TestFailure immediately when something is wrong instead of just recording an error. Default is True.

Type dut

SimHandle

Type reorder_depth

int, optional

Type fail_immediately

bool, optional

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.

Rtype

TestFailure

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

Common function for comparing two transactions.

Can be re-implemented by a subclass.

Parameters
  • got – The received transaction.

  • exp – The expected transaction.

  • log – The logger for reporting messages.

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

Type strict_type

bool, optional

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 – Function doing the actual comparison.

  • reorder_depth – 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 – Require transaction type to match exactly if True, otherwise compare its string representation.

Type compare_fn

callable, optional

Type reorder_depth

int, optional

Type strict_type

bool, optional

Raises TypeError

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

Clock

class cocotb.clock.Clock(signal, period, units=None)[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 – The clock period. Must convert to an even number of timesteps.

  • units – One of None, 'fs', 'ps', 'ns', 'us', 'ms', 'sec'. When no units is given (None) the timestep is determined by the simulator.

Type period

int

Type units

str, optional

start[source]

Clocking coroutine. Start driving your clock by forking a call to this.

Parameters

cycles – 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.

Type cycles

int, optional

Utilities

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

Retrieves the simulation time from the simulator.

Parameters

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

Type units

str or None, optional

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 – Number of simulation steps.

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

Type steps

int

Type units

str

Returns

The simulation time in the specified units.

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

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

Parameters
  • time – The value to convert to simulation time steps.

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

Type time

int or float

Type units

str or None, optional

Returns

The number of simulation time steps.

Rtype

int

Raises ValueError

If given time cannot be represented by simulator precision.

cocotb.utils.pack(ctypes_obj)[source]

Convert a ctypes structure into a Python string.

Parameters

ctypes_obj – The ctypes structure to convert to a string.

Type ctypes_obj

ctypes.Structure

Returns

New Python string containing the bytes from memory holding ctypes_obj.

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 – The ctypes structure to pack into.

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

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

Type ctypes_obj

ctypes.Structure

Type string

str

Type bytes

int, optional

Raises ValueError

If length of string and size of ctypes_obj are not equal.

Raises MemoryError

If bytes is longer than size of ctypes_obj.

cocotb.utils.hexdump(x)[source]

Hexdump a buffer.

Parameters

x – Object that supports conversion via the str built-in.

Returns

A string containing the hexdump.

Example:

print(hexdump('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, y)[source]

Return a diff string showing differences between two binary strings.

Parameters
  • x – Object that supports conversion via the str built-in.

  • y – Object that supports conversion via the str built-in.

Example:

print(hexdiffs('this short thing', 'this also short'))
0000      746869732073686F 7274207468696E67 this short thing
     0000 7468697320616C73 6F  2073686F7274 this also  short
cocotb.utils.with_metaclass(meta, *bases)[source]

This provides:

class Foo(with_metaclass(Meta, Base1, Base2)): pass

which is a unifying syntax for:

# python 3
class Foo(Base1, Base2, metaclass=Meta): pass

# python 2
class Foo(Base1, Base2):
    __metaclass__ = Meta
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.

class cocotb.utils.nullcontext(enter_result=None)[source]

Context manager that does no additional processing. Used as a stand-in for a normal context manager, when a particular block of code is only sometimes used with a normal context manager:

>>> cm = optional_cm if condition else nullcontext()
>>> with cm:
>>>     # Perform operation, using optional_cm if condition is True
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):
    ...

Simulation Object Handles

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.

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

Bases: cocotb.handle.SimHandleBase

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

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

Bases: cocotb.handle.RegionObject

Hierarchy objects are namespace/scope objects.

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

Bases: cocotb.handle.RegionObject

Hierarchy Arrays are containers of Hierarchy Objects.

class cocotb.handle.AssignmentResult(signal, value)[source]

Bases: object

Object that exists solely to provide an error message if the caller is not aware of cocotb’s meaning of <=.

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

Bases: cocotb.handle.SimHandleBase

Common base class for all non-hierarchy objects.

value

A reference to the value

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

Bases: cocotb.handle.NonHierarchyObject

Constant objects have a value that can be read, but not set.

We can also cache the value since it is elaboration time fixed and won’t change within a simulation.

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

Bases: cocotb.handle.NonHierarchyObject

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

Bases: cocotb.handle.NonHierarchyIndexableObject

for ... in drivers()[source]

An iterator for gathering all drivers for a signal.

for ... in loads()[source]

An iterator for gathering all loads on a signal.

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

Bases: cocotb.handle.NonConstantObject

Base class for simulator objects whose values can be modified.

setimmediatevalue(value)[source]

Set the value of the underlying simulation object to value.

This operation will fail unless the handle refers to a modifiable object, e.g. net, signal or variable.

We determine the library call to make based on the type of the value because assigning integers less than 32 bits is faster.

Parameters

value – The value to drive onto the simulator object.

Type value

ctypes.Structure, cocotb.binary.BinaryValue, int, double

Raises TypeError

If target is not wide enough or has an unsupported type for value assignment.

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

Bases: cocotb.handle.ModifiableObject

Specific object handle for Real signals and variables.

setimmediatevalue(value)[source]

Set the value of the underlying simulation object to value.

This operation will fail unless the handle refers to a modifiable object, e.g. net, signal or variable.

Parameters

value – The value to drive onto the simulator object.

Type value

float

Raises TypeError

If target has an unsupported type for real value assignment.

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

Bases: cocotb.handle.ModifiableObject

Specific object handle for enumeration signals and variables.

setimmediatevalue(value)[source]

Set the value of the underlying simulation object to value.

This operation will fail unless the handle refers to a modifiable object, e.g. net, signal or variable.

Parameters

value – The value to drive onto the simulator object.

Type value

int

Raises TypeError

If target has an unsupported type for integer value assignment.

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

Bases: cocotb.handle.ModifiableObject

Specific object handle for Integer and Enum signals and variables.

setimmediatevalue(value)[source]

Set the value of the underlying simulation object to value.

This operation will fail unless the handle refers to a modifiable object, e.g. net, signal or variable.

Parameters

value – The value to drive onto the simulator object.

Type value

int

Raises TypeError

If target has an unsupported type for integer value assignment.

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

Bases: cocotb.handle.ModifiableObject

Specific object handle for String variables.

setimmediatevalue(value)[source]

Set the value of the underlying simulation object to value.

This operation will fail unless the handle refers to a modifiable object, e.g. net, signal or variable.

Parameters

value – The value to drive onto the simulator object.

Type value

str

Raises TypeError

If target has an unsupported type for string value assignment.

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

Factory function to create the correct type of SimHandle object.

Implemented Testbench Structures

Drivers

AD9361

Analog Devices AD9361 RF Transceiver.

class cocotb.drivers.ad9361.AD9361(dut, rx_channels=1, tx_channels=1, tx_clock_half_period=16276, rx_clock_half_period=16276, loopback_queue_maxlen=16)[source]

Driver for the AD9361 RF Transceiver.

send_data(i_data, q_data, i_data2=None, q_data2=None, binaryRepresentation=BinaryRepresentation.TWOS_COMPLEMENT)[source]

Forks the rx_data_to_ad9361 coroutine to send data.

Parameters
  • i_data – Data of the I0 channel.

  • q_data – Data of the Q0 channel.

  • i_data2 – Data of the I1 channel.

  • q_data2 – Data of the Q1 channel.

  • binaryRepresentation – The representation of the binary value. Default is TWOS_COMPLEMENT.

Type i_data

int

Type q_data

int

Type i_data2

int, optional

Type q_data2

int, optional

Type binaryRepresentation

BinaryRepresentation

for ... in rx_data_to_ad9361(i_data, q_data, i_data2=None, q_data2=None, binaryRepresentation=BinaryRepresentation.TWOS_COMPLEMENT)[source]

Receive data to AD9361.

This is a coroutine.

Parameters
  • i_data – Data of the I0 channel.

  • q_data – Data of the Q0 channel.

  • i_data2 – Data of the I1 channel.

  • q_data2 – Data of the Q1 channel.

  • binaryRepresentation – The representation of the binary value. Default is TWOS_COMPLEMENT.

Type i_data

int

Type q_data

int

Type i_data2

int, optional

Type q_data2

int, optional

Type binaryRepresentation

BinaryRepresentation

ad9361_tx_to_rx_loopback()[source]

Create loopback from tx to rx.

Forks a coroutine doing the actual task.

tx_data_from_ad9361()[source]

Transmit data from AD9361.

Forks a coroutine doing the actual task.

AMBA

Advanced Microcontroller Bus Architecture.

class cocotb.drivers.amba.AXI4LiteMaster(entity, name, clock)[source]

AXI4-Lite Master.

TODO: Kill all pending transactions if reset is asserted.

for ... in write(address, value, byte_enable=0xf, address_latency=0, data_latency=0)[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. Default is to 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.

Type address

int

Type value

int

Type byte_enable

int, optional

Type address_latency

int, optional

Type data_latency

int, optional

Type sync

bool, optional

Returns

The write response value.

Rtype

BinaryValue

Raises AXIProtocolError

If write response from AXI is not OKAY.

for ... in read(address, sync=True)[source]

Read from an address.

Parameters
  • address – The address to read from.

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

Type address

int

Type sync

bool, optional

Returns

The read data value.

Rtype

BinaryValue

Raises AXIProtocolError

If read response from AXI is not OKAY.

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

AXI4 Slave

Monitors an internal memory and handles read and write requests.

Avalon

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

Bases: cocotb.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.

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

Avalon Memory Mapped Interface (Avalon-MM) Master

for ... in write(address, value)[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.

Type address

int

Type value

int

Raises TestError

If master is read-only.

for ... in read(address, sync=True)[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.

Type address

int

Type sync

bool, optional

Returns

The read data value.

Rtype

BinaryValue

Raises TestError

If master is write-only.

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

Bases: cocotb.drivers.BusDriver

Emulate a memory, with back-door access.

class cocotb.drivers.avalon.AvalonST(*args, **kwargs)[source]

Bases: cocotb.drivers.ValidatedBusDriver

Avalon Streaming Interface (Avalon-ST) Driver

class cocotb.drivers.avalon.AvalonSTPkts(*args, **kwargs)[source]

Bases: cocotb.drivers.ValidatedBusDriver

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

OPB

class cocotb.drivers.opb.OPBMaster(entity, name, clock)[source]

On-chip peripheral bus master.

for ... in write(address, value, sync=True)[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.

Type address

int

Type value

int

Type sync

bool, optional

Raises OPBException

If write took longer than 16 cycles.

for ... in read(address, sync=True)[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.

Type address

int

Type sync

bool, optional

Returns

The read data value.

Rtype

BinaryValue

Raises OPBException

If read took longer than 16 cycles.

XGMII

class cocotb.drivers.xgmii.XGMII(signal, clock, interleaved=True)[source]

Bases: cocotb.drivers.Driver

XGMII (10 Gigabit Media Independent Interface) driver.

staticmethod layer1(packet)[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.

Type packet

str

Returns

The formatted layer 1 packet.

Rtype

str

idle()[source]

Helper function to set bus to IDLE state.

terminate(index)[source]

Helper function to terminate from a provided lane index.

Parameters

index – The index to terminate.

Type index

int

Monitors

Avalon

class cocotb.monitors.avalon.AvalonST(*args, **kwargs)[source]

Bases: cocotb.monitors.BusMonitor

Avalon-ST bus.

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

class cocotb.monitors.avalon.AvalonSTPkts(*args, **kwargs)[source]

Bases: cocotb.monitors.BusMonitor

Packetised Avalon-ST bus.

XGMII

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

Bases: cocotb.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.