| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| """ |
| Cocotb is a coroutine, cosimulation framework for writing testbenches in Python. |
| |
| See https://docs.cocotb.org for full documentation |
| """ |
| import logging |
| import os |
| import random |
| import sys |
| import threading |
| import time |
| import warnings |
| from collections.abc import Coroutine |
| from types import SimpleNamespace |
| from typing import Dict, List, Optional, Union |
|
|
| import cocotb.handle |
| from cocotb.log import default_config |
| from cocotb.regression import RegressionManager |
| from cocotb.scheduler import Scheduler |
| from cocotb.task import Task |
|
|
| from ._version import __version__ |
|
|
| |
| from cocotb.decorators import ( |
| external, |
| function, |
| test, |
| parameterize, |
| ) |
| from cocotb.log import _filter_from_c, _log_from_c |
|
|
|
|
| def _setup_logging() -> None: |
| default_config() |
| global log |
| log = logging.getLogger(__name__) |
|
|
|
|
| |
| |
| |
| |
|
|
| scheduler: Optional[Scheduler] = None |
| """The global scheduler instance. |
| |
| This is guaranteed to hold a value at test time. |
| """ |
|
|
| regression_manager: Optional[RegressionManager] = None |
| """The global regression manager instance. |
| |
| This is guaranteed to hold a value at test time. |
| """ |
|
|
| argv: Optional[List[str]] = None |
| """The argument list as seen by the simulator. |
| |
| This is guaranteed to hold a value at test time. |
| """ |
|
|
| argc: Optional[int] = None |
| """The length of :data:`cocotb.argv`. |
| |
| This is guaranteed to hold a value at test time. |
| """ |
|
|
| plusargs: Optional[Dict[str, Union[bool, str]]] = None |
| """A dictionary of "plusargs" handed to the simulation. |
| |
| See :make:var:`PLUSARGS` for details. |
| This is guaranteed to hold a value at test time. |
| """ |
|
|
| packages: Optional[SimpleNamespace] = None |
| """A :class:`python:types.SimpleNamespace` of package handles. |
| |
| This will be populated with handles at test time if packages can be discovered |
| via the GPI. |
| |
| .. versionadded:: 2.0 |
| """ |
|
|
| LANGUAGE: Optional[str] = os.getenv("TOPLEVEL_LANG") |
| """The value of :make:var:`TOPLEVEL_LANG`. |
| |
| This is guaranteed to hold a value at test time. |
| """ |
|
|
| SIM_NAME: Optional[str] = None |
| """The running simulator product information. |
| |
| ``None`` if :mod:`cocotb` was not loaded from a simulator. |
| """ |
|
|
| SIM_VERSION: Optional[str] = None |
| """The version of the running simulator. |
| |
| ``None`` if :mod:`cocotb` was not loaded from a simulator.""" |
|
|
| RANDOM_SEED: Optional[int] = None |
| """ |
| The value passed to the Python default random number generator. |
| |
| See :envvar:`RANDOM_SEED` for details on how the value is computed. |
| This is guaranteed to hold a value at test time. |
| """ |
|
|
| _library_coverage = None |
| """ used for cocotb library coverage """ |
|
|
| _user_coverage = None |
| """ used for user code coverage """ |
|
|
| top: Optional[cocotb.handle.SimHandleBase] = None |
| r""" |
| A handle to the :envvar:`TOPLEVEL` entity/module. |
| |
| This is equivalent to the :term:`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 :term:`DUT` in module-level class and function definitions; |
| and in parameters to :class:`.TestFactory`\ s. |
| ``None`` if :mod:`cocotb` was not loaded from a simulator. |
| """ |
|
|
|
|
| def start_soon(coro: Union[Task, Coroutine]) -> Task: |
| """ |
| Schedule a coroutine to be run concurrently. |
| |
| Note that this is not an async function, |
| and the new task will not execute until the calling task yields control. |
| |
| .. versionadded:: 1.6.0 |
| """ |
| return scheduler.start_soon(coro) |
|
|
|
|
| async def start(coro: Union[Task, Coroutine]) -> Task: |
| """ |
| Schedule a coroutine to be run concurrently, then yield control to allow pending tasks to execute. |
| |
| The calling task will resume execution before control is returned to the simulator. |
| |
| .. versionadded:: 1.6.0 |
| """ |
| task = scheduler.start_soon(coro) |
| await cocotb.triggers.NullTrigger() |
| return task |
|
|
|
|
| def create_task(coro: Union[Task, Coroutine]) -> Task: |
| """ |
| Construct a coroutine into a Task without scheduling the Task. |
| |
| The Task can later be scheduled with :func:`cocotb.start` or :func:`cocotb.start_soon`. |
| |
| .. versionadded:: 1.6.0 |
| """ |
| return cocotb.scheduler.create_task(coro) |
|
|
|
|
| |
| _rlock = threading.RLock() |
|
|
|
|
| def _initialise_testbench(argv_): |
| """Initialize testbench. |
| |
| This function is called after the simulator has elaborated all |
| entities and is ready to run the test. |
| |
| The test must be defined by the environment variables |
| :envvar:`MODULE` and :envvar:`TESTCASE`. |
| """ |
| with _rlock: |
| try: |
| _start_library_coverage() |
| _initialise_testbench_(argv_) |
| except BaseException: |
| log.exception("cocotb testbench initialization failed. Exiting.") |
| from cocotb import simulator |
|
|
| simulator.stop_simulator() |
| _stop_library_coverage() |
|
|
|
|
| def _initialise_testbench_(argv_): |
| |
| |
| |
|
|
| global argc, argv |
| argv = argv_ |
| argc = len(argv) |
|
|
| root_name = os.getenv("TOPLEVEL") |
| if root_name is not None: |
| root_name = root_name.strip() |
| if root_name == "": |
| root_name = None |
| elif "." in root_name: |
| |
| root_name = root_name.split(".", 1)[1] |
|
|
| |
| |
| |
| sys.path.insert(0, "") |
|
|
| _setup_logging() |
|
|
| |
| |
| |
| if not sys.warnoptions: |
| warnings.simplefilter("default") |
|
|
| from cocotb import simulator |
|
|
| global SIM_NAME, SIM_VERSION |
| SIM_NAME = simulator.get_simulator_product().strip() |
| SIM_VERSION = simulator.get_simulator_version().strip() |
|
|
| cocotb.log.info(f"Running on {SIM_NAME} version {SIM_VERSION}") |
|
|
| log.info( |
| f"Running tests with cocotb v{__version__} from {os.path.dirname(__file__)}" |
| ) |
|
|
| |
|
|
| _process_plusargs() |
| _process_packages() |
|
|
| |
| global RANDOM_SEED |
| RANDOM_SEED = os.getenv("RANDOM_SEED") |
|
|
| if RANDOM_SEED is None: |
| if "ntb_random_seed" in plusargs: |
| RANDOM_SEED = eval(plusargs["ntb_random_seed"]) |
| elif "seed" in plusargs: |
| RANDOM_SEED = eval(plusargs["seed"]) |
| else: |
| RANDOM_SEED = int(time.time()) |
| log.info("Seeding Python random module with %d" % (RANDOM_SEED)) |
| else: |
| RANDOM_SEED = int(RANDOM_SEED) |
| log.info("Seeding Python random module with supplied seed %d" % (RANDOM_SEED)) |
| random.seed(RANDOM_SEED) |
|
|
| |
| handle = simulator.get_root_handle(root_name) |
| if not handle: |
| raise RuntimeError(f"Can not find root handle ({root_name})") |
|
|
| global top |
| top = cocotb.handle.SimHandle(handle) |
|
|
| _start_user_coverage() |
|
|
| global regression_manager |
| regression_manager = RegressionManager() |
|
|
| |
| module_str = os.getenv("MODULE").strip() |
| if module_str is None or len(module_str) == 0: |
| raise RuntimeError( |
| "Environment variable MODULE, which defines the module(s) to execute, is not defined or empty." |
| ) |
| modules = [s.strip() for s in module_str.split(",") if s.strip()] |
| test_str = os.getenv("TESTCASE", "") |
| filters = [s.strip() for s in test_str.split(",") if s.strip()] |
| regression_manager.setup_pytest_assertion_rewriting(modules) |
| regression_manager.discover_tests(modules=modules, filters=filters) |
|
|
| global scheduler |
| scheduler = Scheduler(handle_result=regression_manager._handle_result) |
|
|
| |
| regression_manager.start_regression() |
|
|
|
|
| def _start_library_coverage() -> None: |
| if "COCOTB_LIBRARY_COVERAGE" in os.environ: |
| try: |
| import coverage |
| except ImportError: |
| log.error( |
| "cocotb library coverage collection requested but coverage package not available. Install it using `pip install coverage`." |
| ) |
| else: |
| global _library_coverage |
| _library_coverage = coverage.coverage( |
| data_file=".coverage.cocotb", |
| config_file=False, |
| branch=True, |
| include=[f"{os.path.dirname(__file__)}/*"], |
| ) |
| _library_coverage.start() |
|
|
|
|
| def _stop_library_coverage() -> None: |
| if _library_coverage is not None: |
| |
| _library_coverage.stop() |
| _library_coverage.save() |
|
|
|
|
| def _sim_event(message): |
| """Function that can be called externally to signal an event.""" |
| from cocotb.result import SimFailure |
|
|
| |
| |
| msg = f"Failing test at simulator request before test run completion: {message}" |
| if scheduler is not None: |
| scheduler.log.error(msg) |
| scheduler._finish_scheduler(SimFailure(msg)) |
| else: |
| log.error(msg) |
| _stop_user_coverage() |
| _stop_library_coverage() |
|
|
|
|
| def _process_plusargs() -> None: |
| global plusargs |
|
|
| plusargs = {} |
|
|
| for option in cocotb.argv: |
| if option.startswith("+"): |
| if option.find("=") != -1: |
| (name, value) = option[1:].split("=", 1) |
| plusargs[name] = value |
| else: |
| plusargs[option[1:]] = True |
|
|
|
|
| def _process_packages() -> None: |
| global packages |
|
|
| pkg_dict = {} |
|
|
| from cocotb import simulator |
|
|
| pkgs = simulator.package_iterate() |
| if pkgs is None: |
| packages = SimpleNamespace() |
| return |
|
|
| for pkg in pkgs: |
| handle = cocotb.handle.SimHandle(pkg) |
| name = handle._name |
|
|
| |
| |
| |
| if SIM_NAME == "Icarus Verilog": |
| handle._discover_all() |
| pkg_dict[name] = handle |
|
|
| packages = SimpleNamespace(**pkg_dict) |
|
|
|
|
| def _start_user_coverage() -> None: |
| if "COVERAGE" in os.environ: |
| try: |
| import coverage |
| except ImportError: |
| cocotb.log.error( |
| "Coverage collection requested but coverage module not available. Install it using `pip install coverage`." |
| ) |
| else: |
| global _user_coverage |
| config_filepath = os.getenv("COVERAGE_RCFILE") |
| if config_filepath is None: |
| |
| cocotb.log.info( |
| "Collecting coverage of user code. No coverage config file supplied via COVERAGE_RCFILE." |
| ) |
| cocotb_package_dir = os.path.dirname(__file__) |
| _user_coverage = coverage.coverage( |
| branch=True, omit=[f"{cocotb_package_dir}/*"] |
| ) |
| else: |
| cocotb.log.info( |
| "Collecting coverage of user code. Coverage config file supplied." |
| ) |
| |
| _user_coverage = coverage.coverage() |
| _user_coverage.start() |
|
|
|
|
| def _stop_user_coverage() -> None: |
| if _user_coverage is not None: |
| _user_coverage.stop() |
| cocotb.log.debug("Writing coverage data") |
| _user_coverage.save() |
|
|