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: Use
raise TestError(msg)
instead of 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: Use
TestError(msg)
directly instead of 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.
-
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.
-
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.
Writing and Generating tests¶
-
class
cocotb.
test
(f, timeout_time=None, timeout_unit=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_time (int, optional) –
Value representing simulation timeout.
New in version 1.3.
timeout_unit (str, optional) –
Unit of timeout value, see
Timer
for more info.New in version 1.3.
expect_fail (bool, optional) – Don’t mark the result as a failure if the test fails.
expect_error (bool or exception type or tuple of exception types, optional) –
If
True
, consider this test passing if it raises anyException
, and failing if it does not. If given an exception type or tuple of exception types, catching only a listed exception type is considered passing. 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() def my_test(dut): try: yield 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
skip (bool, optional) – Don’t execute this test as part of the regression.
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 tococotb.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
(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]¶ 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 and idles and have some packet generation routines
gen_a
andgen_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('idles', [None, random_idles]) >>> tf.generate_tests()
We would get the following tests:
gen_a
with no backpressure and no idlesgen_a
with no backpressure andrandom_idles
gen_a
withrandom_backpressure
and no idlesgen_a
withrandom_backpressure
andrandom_idles
gen_b
with no backpressure and no idlesgen_b
with no backpressure andrandom_idles
gen_b
withrandom_backpressure
and no idlesgen_b
withrandom_backpressure
andrandom_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.-
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 singletest_function
with multipleTestFactories
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 singletest_function
with multipleTestFactories
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:
BinaryValue.integer
is an integerBinaryValue.signed_integer
is a signed integerBinaryValue.binstr
is a string of01xXzZ
BinaryValue.buff
is a binary buffer of bytesBinaryValue.value
is an integer deprecated
For example:
>>> vec = BinaryValue() >>> vec.integer = 42 >>> print(vec.binstr) 101010 >>> print(repr(vec.buff)) '*'
- 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.
We possibly try to be a bit too clever here by first of all trying to assign the raw string as a
BinaryValue.binstr
, however if the string contains any characters that aren’t0
,1
,X
orZ
then we interpret the string as a binary buffer.
-
property
is_resolvable
¶ Does the value contain any
X
’s? Inquiring minds want to know.
-
property
value
¶ Integer access to the value. deprecated
-
property
integer
¶ The integer representation of the underlying vector.
-
property
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
-
property
buff
¶ Access to the value as a buffer.
-
property
binstr
¶ Access to the binary string.
-
property
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 signalsvalid
anddata
is assumed to be nameddut.stream_in_valid
anddut.stream_in_data
(with the default separator ‘_’).Todo
Support for
struct
/record
ports where signals are member names.- 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 amodport
(untested onstruct
/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
- 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
.
-
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 andfork()
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
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()
):@cocotb.coroutine def custom_clock(): # pre-construct triggers for performance high_time = Timer(high_delay, units="ns") low_time = Timer(low_delay, units="ns") yield Timer(initial_delay, units="ns") while True: dut.clk <= 1 yield high_time dut.clk <= 0 yield low_time
If you also want to change the timing during simulation, use this slightly more inefficient example instead where the
Timer
s inside the while loop are created with current delay values:@cocotb.coroutine def custom_clock(): while True: dut.clk <= 1 yield Timer(high_delay, units="ns") dut.clk <= 0 yield Timer(low_delay, units="ns") high_delay = low_delay = 100 cocotb.fork(custom_clock()) yield Timer(1000, units="ns") high_delay = low_delay = 10 # change the clock speed yield Timer(1000, units="ns")
-
cocotb.
fork
(coroutine)¶ Add a new coroutine.
Just a wrapper around self.schedule which provides some debug and useful error messages in the event of common gotchas.
-
cocotb.decorators.RunningCoroutine.
join
(self)¶ Return a trigger that will fire when the wrapped coroutine exits.
-
cocotb.decorators.RunningCoroutine.
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.
-
abstract
-
class
cocotb.triggers.
GPITrigger
[source]¶ Base Trigger class for GPI triggers.
Consumes simulation time.
Testbench Structure¶
Driver¶
-
class
cocotb.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.
-
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 (any) – The transaction to be sent.
callback (callable, optional) – Optional function to be called when the transaction has been sent.
event (optional) –
Event
to be set when the transaction has been sent.**kwargs – Any additional arguments used in child class’
_driver_send
method.
-
send
[source]¶ Blocking send call (hence must be “yielded” rather than called).
Sends the transaction over the bus.
- Parameters
transaction (any) – The transaction to be sent.
sync (bool, optional) – Synchronize the transfer by waiting for a rising edge.
**kwargs (dict) – Additional arguments used in child class’
_driver_send
method.
-
_driver_send
(transaction, sync=True, **kwargs)[source]¶ Actual implementation of the send.
Sub-classes should override this method to implement the actual
send()
routine.- Parameters
transaction (any) – The transaction to be sent.
sync (bool, optional) – Synchronize the transfer by waiting for a rising edge.
**kwargs – Additional arguments if required for protocol implemented in a sub-class.
-
_send
[source]¶ Send coroutine.
- Parameters
transaction (any) – The transaction to be sent.
callback (callable, optional) – Optional function to be called when the transaction has been sent.
event (optional) – event to be set when the transaction has been sent.
sync (bool, optional) – Synchronize the transfer by waiting for a rising edge.
**kwargs – Any additional arguments used in child class’
_driver_send
method.
-
-
class
cocotb.drivers.
BitDriver
(signal, clk, generator=None)[source]¶ Bases:
object
Drives a signal onto a single bit.
Useful for exercising ready/valid flags.
-
start
(generator=None)[source]¶ Start generating data.
- Parameters
generator (generator, optional) –
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())
-
-
class
cocotb.drivers.
BusDriver
(entity, name, clock, **kwargs)[source]¶ Bases:
cocotb.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 (SimHandle) – A handle to the simulator entity.
name (str or None) – Name of this bus.
None
for a nameless bus, e.g. bus-signals in an interface or amodport
. (untested onstruct
/record
, but could work here as well).clock (SimHandle) – A handle to the clock associated with this bus.
**kwargs (dict) – Keyword arguments forwarded to
cocotb.Bus
, see docs for that class for more information.
Constructor for a driver instance.
-
_driver_send
[source]¶ Implementation for BusDriver.
- Parameters
transaction – The transaction to send.
sync (bool, optional) – Synchronize the transfer by waiting for a rising edge.
-
_wait_for_signal
[source]¶ This method will return when the specified signal has hit logic
1
. The state will be in theReadOnly
phase so sim will need to move toNextTimeStep
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 theReadOnly
phase so sim will need to move toNextTimeStep
before registering more callbacks can occur.
-
class
cocotb.drivers.
ValidatedBusDriver
(entity, name, clock, **kwargs)[source]¶ Bases:
cocotb.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.
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 sub-classed and the internal
_monitor_recv
method should be overridden and decorated as acoroutine
. 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 (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.
-
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 toNone
.- Returns
Data of 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 buses.
-
property
in_reset
¶ Boolean flag showing whether the bus is in reset state or not.
-
property
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 (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 isTrue
.
-
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
-
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
isTrue
. If strict_type isTrue
, 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.
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 andfork()
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
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()
):@cocotb.coroutine def custom_clock(): # pre-construct triggers for performance high_time = Timer(high_delay, units="ns") low_time = Timer(low_delay, units="ns") yield Timer(initial_delay, units="ns") while True: dut.clk <= 1 yield high_time dut.clk <= 0 yield low_time
If you also want to change the timing during simulation, use this slightly more inefficient example instead where the
Timer
s inside the while loop are created with current delay values:@cocotb.coroutine def custom_clock(): while True: dut.clk <= 1 yield Timer(high_delay, units="ns") dut.clk <= 0 yield Timer(low_delay, units="ns") high_delay = low_delay = 100 cocotb.fork(custom_clock()) yield Timer(1000, units="ns") high_delay = low_delay = 10 # change the clock speed yield Timer(1000, units="ns")
-
start
[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 asNone
, as0
will cycle no times.start_high (bool, optional) –
Whether to start the clock with a
1
for the first half of the period. Default isTrue
.New in version 1.3.
Utilities¶
-
cocotb.
plusargs
= {}¶ A dictionary of “plusargs” handed to the simulation.
-
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.
-
cocotb.utils.
get_sim_steps
(time, units=None)[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 or None, optional) – 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.
- Returns
The number of simulation time steps.
- Return type
- 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 (ctypes.Structure) – The
ctypes
structure to convert to a string.- 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 (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.
-
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(0, 1)) 0000 30 0 0000 31 1 >>> print(hexdiffs('a', 'b')) 0000 61 a 0000 62 b >>> print(hexdiffs('this short thing', '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)
andJoin(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): ...
-
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
to1
.
-
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.
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
A region object, such as a scope or namespace.
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.
NonHierarchyObject
(handle, path)[source]¶ Bases:
cocotb.handle.SimHandleBase
Common base class for all non-hierarchy objects.
- Parameters
-
property
value
¶ A reference to the value
-
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.
We can also cache the value since it is fixed at elaboration time and won’t change within a simulation.
-
class
cocotb.handle.
NonHierarchyIndexableObject
(handle, path)[source]¶ Bases:
cocotb.handle.NonHierarchyObject
A non-hierarchy indexable object.
-
class
cocotb.handle.
NonConstantObject
(handle, path)[source]¶ Bases:
cocotb.handle.NonHierarchyIndexableObject
A non-constant object
- Parameters
-
class
cocotb.handle.
ModifiableObject
(handle, path)[source]¶ Bases:
cocotb.handle.NonConstantObject
Base class for simulator objects whose values can be modified.
- Parameters
-
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 (ctypes.Structure, cocotb.binary.BinaryValue, int, double) – The value to drive onto the simulator object.
- 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.
- Parameters
-
class
cocotb.handle.
EnumObject
(handle, path)[source]¶ Bases:
cocotb.handle.ModifiableObject
Specific object handle for enumeration signals and variables.
- Parameters
-
class
cocotb.handle.
IntegerObject
(handle, path)[source]¶ Bases:
cocotb.handle.ModifiableObject
Specific object handle for Integer and Enum signals and variables.
- Parameters
-
class
cocotb.handle.
StringObject
(handle, path)[source]¶ Bases:
cocotb.handle.ModifiableObject
Specific object handle for String variables.
- Parameters
Implemented Testbench Structures¶
Drivers¶
AMBA¶
Advanced Microcontroller Bus Architecture.
-
class
cocotb.drivers.amba.
AXI4LiteMaster
(entity, name, clock, **kwargs)[source]¶ AXI4-Lite Master.
TODO: Kill all pending transactions if reset is asserted.
Constructor for a driver instance.
-
write
(address, value, byte_enable=0xf, address_latency=0, data_latency=0)[source]¶ Write a value to an address.
- Parameters
address (int) – The address to write to.
value (int) – The data value to write.
byte_enable (int, optional) – Which bytes in value to actually write. Default is to write all bytes.
address_latency (int, optional) – Delay before setting the address (in clock cycles). Default is no delay.
data_latency (int, optional) – Delay before setting the data value (in clock cycles). Default is no delay.
sync (bool, optional) – Wait for rising edge on clock initially. Defaults to True.
- Returns
The write response value.
- Return type
- Raises
AXIProtocolError – If write response from AXI is not
OKAY
.
-
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.
Constructor for a driver instance.
-
class
cocotb.drivers.avalon.
AvalonMaster
(entity, name, clock, **kwargs)[source]¶ Avalon Memory Mapped Interface (Avalon-MM) Master.
Constructor for a driver instance.
-
class
cocotb.drivers.avalon.
AvalonMemory
(entity, name, clock, readlatency_min=1, readlatency_max=1, memory=None, avl_properties={}, **kwargs)[source]¶ Bases:
cocotb.drivers.BusDriver
Emulate a memory, with back-door access.
Constructor for a driver instance.
-
class
cocotb.drivers.avalon.
AvalonST
(entity, name, clock, **kwargs)[source]¶ Bases:
cocotb.drivers.ValidatedBusDriver
Avalon Streaming Interface (Avalon-ST) Driver
Constructor for a driver instance.
-
class
cocotb.drivers.avalon.
AvalonSTPkts
(entity, name, clock, **kwargs)[source]¶ Bases:
cocotb.drivers.ValidatedBusDriver
Avalon Streaming Interface (Avalon-ST) Driver, packetized.
Constructor for a driver instance.
OPB¶
-
class
cocotb.drivers.opb.
OPBMaster
(entity, name, clock, **kwargs)[source]¶ On-chip peripheral bus master.
Constructor for a driver instance.
-
write
(address, value, sync=True)[source]¶ Issue a write to the given address with the specified value.
-
XGMII¶
-
class
cocotb.drivers.xgmii.
XGMII
(signal, clock, interleaved=True)[source]¶ Bases:
cocotb.drivers.Driver
XGMII (10 Gigabit Media Independent Interface) driver.
- 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, …
Monitors¶
Avalon¶
-
class
cocotb.monitors.avalon.
AvalonST
(entity, name, clock, **kwargs)[source]¶ Bases:
cocotb.monitors.BusMonitor
Avalon-ST bus.
Non-packetized so each valid word is a separate transaction.
-
class
cocotb.monitors.avalon.
AvalonSTPkts
(entity, name, clock, **kwargs)[source]¶ Bases:
cocotb.monitors.BusMonitor
Packetized 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.- 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¶
Signal Tracer for WaveDrom¶
-
class
cocotb.wavedrom.
trace
(*args, **kwargs)[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()
Developer-focused¶
The Scheduler¶
Note
The scheduler object should generally not be interacted with directly -
the only part of it that a user will need is encapsulated in fork()
,
everything else works behind the scenes.
-
cocotb.
scheduler
= <cocotb.scheduler.Scheduler object>¶ 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) orvhpiCbLastKnownDeltaCycle
(VHPI). In this state we are not allowed to perform writes.
- Write mode
Corresponds to
cbReadWriteSynch
(VPI) orvhpiCbEndOfProcesses
(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]¶ Called when a trigger fires.
We ensure that we only start the event loop once, rather than letting it recurse.
-
queue_function
(coro)[source]¶ Queue a coroutine for execution and move the containing thread so that it does not block execution of the main thread any longer.
-
run_in_executor
(func, *args, **kwargs)[source]¶ Run the coroutine in a separate execution thread and return a yieldable object for the caller.
-
add
(coroutine)[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.
-
schedule
(coroutine, trigger=None)[source]¶ Schedule a coroutine by calling the send method.
- Parameters
coroutine (cocotb.decorators.coroutine) – The coroutine to schedule.
trigger (cocotb.triggers.Trigger) – The trigger that caused this coroutine to be scheduled.