"""Build an HDL design with Icarus Verilog and run a cocotb test module on it. Used by the test_cocotb_*.py pytest wrappers. Build output goes to a temporary directory, so nothing is written next to the sources. """ from __future__ import annotations import sys import tempfile from pathlib import Path from cocotb_tools.check_results import get_results from cocotb_tools.runner import get_runner HERE = Path(__file__).resolve().parent def run_cocotb(sources: list[str], toplevel: str, test_module: str, parameters: dict[str, object] | None = None, seed: int = 12345) -> tuple[int, int]: """Return (number of tests, number of failures) for one cocotb module.""" if str(HERE) not in sys.path: sys.path.insert(0, str(HERE)) # the runner exports sys.path as PYTHONPATH runner = get_runner("icarus") with tempfile.TemporaryDirectory() as tmp: build_dir = Path(tmp) runner.build( sources=[HERE / s for s in sources], hdl_toplevel=toplevel, parameters=parameters or {}, build_dir=build_dir, timescale=("1ns", "1ps"), # Icarus needs a time precision finer than 1 s ) results = runner.test( test_module=test_module, hdl_toplevel=toplevel, build_dir=build_dir, test_dir=build_dir, results_xml=str(build_dir / "results.xml"), seed=seed, ) return get_results(results)