index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
29,527
cocotb.regression
RegressionManager
Encapsulates all regression capability into a single place
class RegressionManager: """Encapsulates all regression capability into a single place""" def __init__(self, dut: SimHandle, tests: Iterable[Test]): """ Args: dut (SimHandle): The root handle to pass into test functions. tests (Iterable[Test]): tests to run """ self._dut = dut self._test = None self._test_task = None self._test_start_time = None self._test_start_sim_time = None self._cov = None self.log = _logger self.start_time = time.time() self.test_results = [] self.count = 0 self.passed = 0 self.skipped = 0 self.failures = 0 self._tearing_down = False # Setup XUnit ################### results_filename = os.getenv("COCOTB_RESULTS_FILE", "results.xml") suite_name = os.getenv("RESULT_TESTSUITE", "all") package_name = os.getenv("RESULT_TESTPACKAGE", "all") self.xunit = XUnitReporter(filename=results_filename) self.xunit.add_testsuite(name=suite_name, package=package_name) self.xunit.add_property(name="random_seed", value=str(cocotb.RANDOM_SEED)) # Setup Coverage #################### if coverage is not None: self.log.info("Enabling coverage collection of Python code") config_filepath = os.getenv("COVERAGE_RCFILE") if config_filepath is None: # Exclude cocotb itself from coverage collection. cocotb_package_dir = os.path.dirname(__file__) self._cov = coverage.coverage( branch=True, omit=[f"{cocotb_package_dir}/*"] ) else: # Allow the config file to handle all configuration self._cov = coverage.coverage() self._cov.start() # Test Discovery #################### self._queue = [] for test in tests: self.log.info(f"Found test {test.__module__}.{test.__qualname__}") self._queue.append(test) self.ntests = len(self._queue) if not self._queue: self.log.warning("No tests were discovered") self._queue.sort(key=lambda test: (test.stage, test._id)) @classmethod def from_discovery(cls, dut: SimHandle): """ Obtains the test list by discovery. See :envvar:`MODULE` and :envvar:`TESTCASE` for details on how tests are discovered. Args: dut (SimHandle): The root handle to pass into test functions. """ tests = cls._discover_tests() return cls(dut, tests) @classmethod def _discover_tests(cls) -> Iterable[Test]: """ Discovers tests in files automatically. See :envvar:`MODULE` and :envvar:`TESTCASE` for details on how tests are discovered. """ module_str = os.getenv("MODULE") test_str = os.getenv("TESTCASE") if module_str is None: raise ValueError( "Environment variable MODULE, which defines the module(s) to execute, is not defined." ) modules = [s.strip() for s in module_str.split(",") if s.strip()] cls._setup_pytest_assertion_rewriting(modules) tests = None if test_str: tests = [s.strip() for s in test_str.split(",") if s.strip()] for module_name in modules: try: _logger.debug("Python Path: " + ",".join(sys.path)) _logger.debug("PWD: " + os.getcwd()) module = _my_import(module_name) except Exception as E: _logger.critical("Failed to import module %s: %s", module_name, E) _logger.info('MODULE variable was "%s"', ".".join(modules)) _logger.info("Traceback: ") _logger.info(traceback.format_exc()) raise if tests is not None: not_found_tests = [] # Specific functions specified, don't auto-discover for test_name in tests: try: test = getattr(module, test_name) except AttributeError: not_found_tests.append(test_name) continue if not isinstance(test, Test): _logger.error( "Requested %s from module %s isn't a cocotb.test decorated coroutine", test_name, module_name, ) raise ImportError( "Failed to find requested test %s" % test_name ) # If we request a test manually, it should be run even if skip=True is set. test.skip = False yield test # Use the non-matching test names in the next module search tests = not_found_tests else: # auto-discover for thing in vars(module).values(): if isinstance(thing, Test): yield thing # If any test were not found in any module, raise an error if tests: _logger.error( "Requested test(s) %s wasn't found in module(s) %s", tests, modules ) raise AttributeError("Test(s) %s doesn't exist in %s" % (tests, modules)) @classmethod def _setup_pytest_assertion_rewriting(cls, test_modules: Iterable[str]) -> None: try: import pytest except ImportError: _logger.info( "pytest not found, install it to enable better AssertionError messages" ) return try: # Install the assertion rewriting hook, which must be done before we # import the test modules. from _pytest.assertion import install_importhook from _pytest.config import Config pytest_conf = Config.fromdictargs( {}, ["--capture=no", "-o", "python_files=*.py"] ) install_importhook(pytest_conf) except Exception: _logger.exception( "Configuring the assertion rewrite hook using pytest {} failed. " "Please file a bug report!".format(pytest.__version__) ) @deprecated("This method is now private.") def tear_down(self) -> None: self._tear_down() def _tear_down(self) -> None: # prevent re-entering the tear down procedure if not self._tearing_down: self._tearing_down = True else: return # fail remaining tests while True: test = self._next_test() if test is None: break self._record_result( test=test, outcome=Error(SimFailure), wall_time_s=0, sim_time_ns=0 ) # Write out final log messages self._log_test_summary() # Generate output reports self.xunit.write() if self._cov: self._cov.stop() self.log.info("Writing coverage data") self._cov.save() self._cov.html_report() if cocotb._library_coverage is not None: # TODO: move this once we have normal shutdown behavior to _sim_event cocotb._library_coverage.stop() cocotb._library_coverage.save() # Setup simulator finalization simulator.stop_simulator() @deprecated("This method is now private.") def next_test(self) -> Optional[Test]: return self._next_test() def _next_test(self) -> Optional[Test]: """Get the next test to run""" if not self._queue: return None self.count += 1 return self._queue.pop(0) @deprecated("This method is now private.") def handle_result(self, test: Task) -> None: self._handle_result(test) def _handle_result(self, test: Task) -> None: """Handle a test completing. Dump result to XML and schedule the next test (if any). Entered by the scheduler. Args: test: The test that completed """ assert test is self._test_task real_time = time.time() - self._test_start_time sim_time_ns = get_sim_time("ns") - self._test_start_sim_time self._record_result( test=self._test, outcome=self._test_task._outcome, wall_time_s=real_time, sim_time_ns=sim_time_ns, ) self._execute() def _init_test(self, test: Test) -> Optional[Task]: """Initialize a test. Record outcome if the initialization fails. Record skip if the test is skipped. Save the initialized test if it successfully initializes. """ if test.skip: hilight_start = ANSI.COLOR_SKIPPED if want_color_output() else "" hilight_end = ANSI.COLOR_DEFAULT if want_color_output() else "" # Want this to stand out a little bit self.log.info( "{start}skipping{end} {name} ({i}/{total})".format( start=hilight_start, i=self.count, total=self.ntests, end=hilight_end, name=test.__qualname__, ) ) self._record_result(test, None, 0, 0) return None test_init_outcome = cocotb.outcomes.capture(test, self._dut) if isinstance(test_init_outcome, cocotb.outcomes.Error): self.log.error( "Failed to initialize test %s" % test.__qualname__, exc_info=test_init_outcome.error, ) self._record_result(test, test_init_outcome, 0, 0) return None running_test = test_init_outcome.get() # seed random number generator based on test module, name, and RANDOM_SEED hasher = hashlib.sha1() hasher.update(test.__qualname__.encode()) hasher.update(test.__module__.encode()) seed = cocotb.RANDOM_SEED + int(hasher.hexdigest(), 16) random.seed(seed) return running_test def _score_test(self, test: Test, outcome: Outcome) -> Tuple[bool, bool]: """ Given a test and the test's outcome, determine if the test met expectations and log pertinent information """ # scoring outcomes result_pass = True sim_failed = False try: outcome.get() except (KeyboardInterrupt, SystemExit): raise except BaseException as e: result = remove_traceback_frames(e, ["_score_test", "get"]) else: result = TestSuccess() if ( isinstance(result, TestSuccess) and not test.expect_fail and not test.expect_error ): self._log_test_passed(test, None, None) elif isinstance(result, TestSuccess) and test.expect_error: self._log_test_failed(test, None, "passed but we expected an error") result_pass = False elif isinstance(result, TestSuccess): self._log_test_failed(test, None, "passed but we expected a failure") result_pass = False elif isinstance(result, SimFailure): if isinstance(result, test.expect_error): self._log_test_passed(test, result, "errored as expected") else: self.log.error("Test error has lead to simulator shutting us down") result_pass = False # whether we expected it or not, the simulation has failed unrecoverably sim_failed = True elif isinstance(result, (AssertionError, _Failed)) and test.expect_fail: self._log_test_passed(test, result, "failed as expected") elif test.expect_error: if isinstance(result, test.expect_error): self._log_test_passed(test, result, "errored as expected") else: self._log_test_failed(test, result, "errored with unexpected type ") result_pass = False else: self._log_test_failed(test, result, None) result_pass = False if _pdb_on_exception: pdb.post_mortem(result.__traceback__) return result_pass, sim_failed def _log_test_passed( self, test: Test, result: Optional[Exception] = None, msg: Optional[str] = None ) -> None: start_hilight = ANSI.COLOR_PASSED if want_color_output() else "" stop_hilight = ANSI.COLOR_DEFAULT if want_color_output() else "" if msg is None: rest = "" else: rest = f": {msg}" if result is None: result_was = "" else: result_was = f" (result was {type(result).__qualname__})" self.log.info( f"{test.__qualname__} {start_hilight}passed{stop_hilight}{rest}{result_was}" ) def _log_test_failed( self, test: Test, result: Optional[Exception] = None, msg: Optional[str] = None ) -> None: start_hilight = ANSI.COLOR_FAILED if want_color_output() else "" stop_hilight = ANSI.COLOR_DEFAULT if want_color_output() else "" if msg is None: rest = "" else: rest = f": {msg}" self.log.info( f"{test.__qualname__} {start_hilight}failed{stop_hilight}{rest}", exc_info=result, ) def _record_result( self, test: Test, outcome: Optional[Outcome], wall_time_s: float, sim_time_ns: float, ) -> None: ratio_time = self._safe_divide(sim_time_ns, wall_time_s) try: lineno = inspect.getsourcelines(test._func)[1] except OSError: lineno = 1 self.xunit.add_testcase( name=test.__qualname__, classname=test.__module__, file=inspect.getfile(test._func), lineno=repr(lineno), time=repr(wall_time_s), sim_time_ns=repr(sim_time_ns), ratio_time=repr(ratio_time), ) if outcome is None: # skipped test_pass, sim_failed = None, False self.xunit.add_skipped() self.skipped += 1 else: test_pass, sim_failed = self._score_test(test, outcome) if not test_pass: self.xunit.add_failure( message=f"Test failed with RANDOM_SEED={cocotb.RANDOM_SEED}" ) self.failures += 1 else: self.passed += 1 self.test_results.append( { "test": ".".join([test.__module__, test.__qualname__]), "pass": test_pass, "sim": sim_time_ns, "real": wall_time_s, "ratio": ratio_time, } ) if sim_failed: self._tear_down() return @deprecated("This method is now private.") def execute(self) -> None: self._execute() def _execute(self) -> None: while True: self._test = self._next_test() if self._test is None: return self._tear_down() self._test_task = self._init_test(self._test) if self._test_task is not None: return self._start_test() def _start_test(self) -> None: # Want this to stand out a little bit start = "" end = "" if want_color_output(): start = ANSI.COLOR_TEST end = ANSI.COLOR_DEFAULT self.log.info( "{start}running{end} {name} ({i}/{total}){description}".format( start=start, i=self.count, total=self.ntests, end=end, name=self._test.__qualname__, description=_trim(self._test.__doc__), ) ) self._test_start_time = time.time() self._test_start_sim_time = get_sim_time("ns") cocotb.scheduler._add_test(self._test_task) def _log_test_summary(self) -> None: real_time = time.time() - self.start_time sim_time_ns = get_sim_time("ns") ratio_time = self._safe_divide(sim_time_ns, real_time) if len(self.test_results) == 0: return TEST_FIELD = "TEST" RESULT_FIELD = "STATUS" SIM_FIELD = "SIM TIME (ns)" REAL_FIELD = "REAL TIME (s)" RATIO_FIELD = "RATIO (ns/s)" TOTAL_NAME = f"TESTS={self.ntests} PASS={self.passed} FAIL={self.failures} SKIP={self.skipped}" TEST_FIELD_LEN = max( len(TEST_FIELD), len(TOTAL_NAME), len(max([x["test"] for x in self.test_results], key=len)), ) RESULT_FIELD_LEN = len(RESULT_FIELD) SIM_FIELD_LEN = len(SIM_FIELD) REAL_FIELD_LEN = len(REAL_FIELD) RATIO_FIELD_LEN = len(RATIO_FIELD) header_dict = dict( a=TEST_FIELD, b=RESULT_FIELD, c=SIM_FIELD, d=REAL_FIELD, e=RATIO_FIELD, a_len=TEST_FIELD_LEN, b_len=RESULT_FIELD_LEN, c_len=SIM_FIELD_LEN, d_len=REAL_FIELD_LEN, e_len=RATIO_FIELD_LEN, ) LINE_LEN = ( 3 + TEST_FIELD_LEN + 2 + RESULT_FIELD_LEN + 2 + SIM_FIELD_LEN + 2 + REAL_FIELD_LEN + 2 + RATIO_FIELD_LEN + 3 ) LINE_SEP = "*" * LINE_LEN + "\n" summary = "" summary += LINE_SEP summary += "** {a:<{a_len}} {b:^{b_len}} {c:>{c_len}} {d:>{d_len}} {e:>{e_len}} **\n".format( **header_dict ) summary += LINE_SEP test_line = "** {a:<{a_len}} {start}{b:^{b_len}}{end} {c:>{c_len}.2f} {d:>{d_len}.2f} {e:>{e_len}} **\n" for result in self.test_results: hilite = "" lolite = "" if result["pass"] is None: ratio = "-.--" pass_fail_str = "SKIP" if want_color_output(): hilite = ANSI.COLOR_SKIPPED lolite = ANSI.COLOR_DEFAULT elif result["pass"]: ratio = format(result["ratio"], "0.2f") pass_fail_str = "PASS" if want_color_output(): hilite = ANSI.COLOR_PASSED lolite = ANSI.COLOR_DEFAULT else: ratio = format(result["ratio"], "0.2f") pass_fail_str = "FAIL" if want_color_output(): hilite = ANSI.COLOR_FAILED lolite = ANSI.COLOR_DEFAULT test_dict = dict( a=result["test"], b=pass_fail_str, c=result["sim"], d=result["real"], e=ratio, a_len=TEST_FIELD_LEN, b_len=RESULT_FIELD_LEN, c_len=SIM_FIELD_LEN - 1, d_len=REAL_FIELD_LEN - 1, e_len=RATIO_FIELD_LEN - 1, start=hilite, end=lolite, ) summary += test_line.format(**test_dict) summary += LINE_SEP summary += test_line.format( a=TOTAL_NAME, b="", c=sim_time_ns, d=real_time, e=format(ratio_time, "0.2f"), a_len=TEST_FIELD_LEN, b_len=RESULT_FIELD_LEN, c_len=SIM_FIELD_LEN - 1, d_len=REAL_FIELD_LEN - 1, e_len=RATIO_FIELD_LEN - 1, start="", end="", ) summary += LINE_SEP self.log.info(summary) @staticmethod def _safe_divide(a: float, b: float) -> float: try: return a / b except ZeroDivisionError: if a == 0: return float("nan") else: return float("inf")
(dut: <function SimHandle at 0x7ff996933d00>, tests: Iterable[cocotb.decorators.test])
29,528
cocotb.regression
__init__
Args: dut (SimHandle): The root handle to pass into test functions. tests (Iterable[Test]): tests to run
def __init__(self, dut: SimHandle, tests: Iterable[Test]): """ Args: dut (SimHandle): The root handle to pass into test functions. tests (Iterable[Test]): tests to run """ self._dut = dut self._test = None self._test_task = None self._test_start_time = None self._test_start_sim_time = None self._cov = None self.log = _logger self.start_time = time.time() self.test_results = [] self.count = 0 self.passed = 0 self.skipped = 0 self.failures = 0 self._tearing_down = False # Setup XUnit ################### results_filename = os.getenv("COCOTB_RESULTS_FILE", "results.xml") suite_name = os.getenv("RESULT_TESTSUITE", "all") package_name = os.getenv("RESULT_TESTPACKAGE", "all") self.xunit = XUnitReporter(filename=results_filename) self.xunit.add_testsuite(name=suite_name, package=package_name) self.xunit.add_property(name="random_seed", value=str(cocotb.RANDOM_SEED)) # Setup Coverage #################### if coverage is not None: self.log.info("Enabling coverage collection of Python code") config_filepath = os.getenv("COVERAGE_RCFILE") if config_filepath is None: # Exclude cocotb itself from coverage collection. cocotb_package_dir = os.path.dirname(__file__) self._cov = coverage.coverage( branch=True, omit=[f"{cocotb_package_dir}/*"] ) else: # Allow the config file to handle all configuration self._cov = coverage.coverage() self._cov.start() # Test Discovery #################### self._queue = [] for test in tests: self.log.info(f"Found test {test.__module__}.{test.__qualname__}") self._queue.append(test) self.ntests = len(self._queue) if not self._queue: self.log.warning("No tests were discovered") self._queue.sort(key=lambda test: (test.stage, test._id))
(self, dut: <function SimHandle at 0x7ff996933d00>, tests: Iterable[cocotb.decorators.test])
29,529
cocotb.regression
_execute
null
def _execute(self) -> None: while True: self._test = self._next_test() if self._test is None: return self._tear_down() self._test_task = self._init_test(self._test) if self._test_task is not None: return self._start_test()
(self) -> NoneType
29,530
cocotb.regression
_handle_result
Handle a test completing. Dump result to XML and schedule the next test (if any). Entered by the scheduler. Args: test: The test that completed
def _handle_result(self, test: Task) -> None: """Handle a test completing. Dump result to XML and schedule the next test (if any). Entered by the scheduler. Args: test: The test that completed """ assert test is self._test_task real_time = time.time() - self._test_start_time sim_time_ns = get_sim_time("ns") - self._test_start_sim_time self._record_result( test=self._test, outcome=self._test_task._outcome, wall_time_s=real_time, sim_time_ns=sim_time_ns, ) self._execute()
(self, test: cocotb.task.Task) -> NoneType
29,531
cocotb.regression
_init_test
Initialize a test. Record outcome if the initialization fails. Record skip if the test is skipped. Save the initialized test if it successfully initializes.
def _init_test(self, test: Test) -> Optional[Task]: """Initialize a test. Record outcome if the initialization fails. Record skip if the test is skipped. Save the initialized test if it successfully initializes. """ if test.skip: hilight_start = ANSI.COLOR_SKIPPED if want_color_output() else "" hilight_end = ANSI.COLOR_DEFAULT if want_color_output() else "" # Want this to stand out a little bit self.log.info( "{start}skipping{end} {name} ({i}/{total})".format( start=hilight_start, i=self.count, total=self.ntests, end=hilight_end, name=test.__qualname__, ) ) self._record_result(test, None, 0, 0) return None test_init_outcome = cocotb.outcomes.capture(test, self._dut) if isinstance(test_init_outcome, cocotb.outcomes.Error): self.log.error( "Failed to initialize test %s" % test.__qualname__, exc_info=test_init_outcome.error, ) self._record_result(test, test_init_outcome, 0, 0) return None running_test = test_init_outcome.get() # seed random number generator based on test module, name, and RANDOM_SEED hasher = hashlib.sha1() hasher.update(test.__qualname__.encode()) hasher.update(test.__module__.encode()) seed = cocotb.RANDOM_SEED + int(hasher.hexdigest(), 16) random.seed(seed) return running_test
(self, test: cocotb.decorators.test) -> Optional[cocotb.task.Task]
29,532
cocotb.regression
_log_test_failed
null
def _log_test_failed( self, test: Test, result: Optional[Exception] = None, msg: Optional[str] = None ) -> None: start_hilight = ANSI.COLOR_FAILED if want_color_output() else "" stop_hilight = ANSI.COLOR_DEFAULT if want_color_output() else "" if msg is None: rest = "" else: rest = f": {msg}" self.log.info( f"{test.__qualname__} {start_hilight}failed{stop_hilight}{rest}", exc_info=result, )
(self, test: cocotb.decorators.test, result: Optional[Exception] = None, msg: Optional[str] = None) -> NoneType
29,533
cocotb.regression
_log_test_passed
null
def _log_test_passed( self, test: Test, result: Optional[Exception] = None, msg: Optional[str] = None ) -> None: start_hilight = ANSI.COLOR_PASSED if want_color_output() else "" stop_hilight = ANSI.COLOR_DEFAULT if want_color_output() else "" if msg is None: rest = "" else: rest = f": {msg}" if result is None: result_was = "" else: result_was = f" (result was {type(result).__qualname__})" self.log.info( f"{test.__qualname__} {start_hilight}passed{stop_hilight}{rest}{result_was}" )
(self, test: cocotb.decorators.test, result: Optional[Exception] = None, msg: Optional[str] = None) -> NoneType
29,534
cocotb.regression
_log_test_summary
null
def _log_test_summary(self) -> None: real_time = time.time() - self.start_time sim_time_ns = get_sim_time("ns") ratio_time = self._safe_divide(sim_time_ns, real_time) if len(self.test_results) == 0: return TEST_FIELD = "TEST" RESULT_FIELD = "STATUS" SIM_FIELD = "SIM TIME (ns)" REAL_FIELD = "REAL TIME (s)" RATIO_FIELD = "RATIO (ns/s)" TOTAL_NAME = f"TESTS={self.ntests} PASS={self.passed} FAIL={self.failures} SKIP={self.skipped}" TEST_FIELD_LEN = max( len(TEST_FIELD), len(TOTAL_NAME), len(max([x["test"] for x in self.test_results], key=len)), ) RESULT_FIELD_LEN = len(RESULT_FIELD) SIM_FIELD_LEN = len(SIM_FIELD) REAL_FIELD_LEN = len(REAL_FIELD) RATIO_FIELD_LEN = len(RATIO_FIELD) header_dict = dict( a=TEST_FIELD, b=RESULT_FIELD, c=SIM_FIELD, d=REAL_FIELD, e=RATIO_FIELD, a_len=TEST_FIELD_LEN, b_len=RESULT_FIELD_LEN, c_len=SIM_FIELD_LEN, d_len=REAL_FIELD_LEN, e_len=RATIO_FIELD_LEN, ) LINE_LEN = ( 3 + TEST_FIELD_LEN + 2 + RESULT_FIELD_LEN + 2 + SIM_FIELD_LEN + 2 + REAL_FIELD_LEN + 2 + RATIO_FIELD_LEN + 3 ) LINE_SEP = "*" * LINE_LEN + "\n" summary = "" summary += LINE_SEP summary += "** {a:<{a_len}} {b:^{b_len}} {c:>{c_len}} {d:>{d_len}} {e:>{e_len}} **\n".format( **header_dict ) summary += LINE_SEP test_line = "** {a:<{a_len}} {start}{b:^{b_len}}{end} {c:>{c_len}.2f} {d:>{d_len}.2f} {e:>{e_len}} **\n" for result in self.test_results: hilite = "" lolite = "" if result["pass"] is None: ratio = "-.--" pass_fail_str = "SKIP" if want_color_output(): hilite = ANSI.COLOR_SKIPPED lolite = ANSI.COLOR_DEFAULT elif result["pass"]: ratio = format(result["ratio"], "0.2f") pass_fail_str = "PASS" if want_color_output(): hilite = ANSI.COLOR_PASSED lolite = ANSI.COLOR_DEFAULT else: ratio = format(result["ratio"], "0.2f") pass_fail_str = "FAIL" if want_color_output(): hilite = ANSI.COLOR_FAILED lolite = ANSI.COLOR_DEFAULT test_dict = dict( a=result["test"], b=pass_fail_str, c=result["sim"], d=result["real"], e=ratio, a_len=TEST_FIELD_LEN, b_len=RESULT_FIELD_LEN, c_len=SIM_FIELD_LEN - 1, d_len=REAL_FIELD_LEN - 1, e_len=RATIO_FIELD_LEN - 1, start=hilite, end=lolite, ) summary += test_line.format(**test_dict) summary += LINE_SEP summary += test_line.format( a=TOTAL_NAME, b="", c=sim_time_ns, d=real_time, e=format(ratio_time, "0.2f"), a_len=TEST_FIELD_LEN, b_len=RESULT_FIELD_LEN, c_len=SIM_FIELD_LEN - 1, d_len=REAL_FIELD_LEN - 1, e_len=RATIO_FIELD_LEN - 1, start="", end="", ) summary += LINE_SEP self.log.info(summary)
(self) -> NoneType
29,535
cocotb.regression
_next_test
Get the next test to run
def _next_test(self) -> Optional[Test]: """Get the next test to run""" if not self._queue: return None self.count += 1 return self._queue.pop(0)
(self) -> Optional[cocotb.decorators.test]
29,536
cocotb.regression
_record_result
null
def _record_result( self, test: Test, outcome: Optional[Outcome], wall_time_s: float, sim_time_ns: float, ) -> None: ratio_time = self._safe_divide(sim_time_ns, wall_time_s) try: lineno = inspect.getsourcelines(test._func)[1] except OSError: lineno = 1 self.xunit.add_testcase( name=test.__qualname__, classname=test.__module__, file=inspect.getfile(test._func), lineno=repr(lineno), time=repr(wall_time_s), sim_time_ns=repr(sim_time_ns), ratio_time=repr(ratio_time), ) if outcome is None: # skipped test_pass, sim_failed = None, False self.xunit.add_skipped() self.skipped += 1 else: test_pass, sim_failed = self._score_test(test, outcome) if not test_pass: self.xunit.add_failure( message=f"Test failed with RANDOM_SEED={cocotb.RANDOM_SEED}" ) self.failures += 1 else: self.passed += 1 self.test_results.append( { "test": ".".join([test.__module__, test.__qualname__]), "pass": test_pass, "sim": sim_time_ns, "real": wall_time_s, "ratio": ratio_time, } ) if sim_failed: self._tear_down() return
(self, test: cocotb.decorators.test, outcome: Optional[cocotb.outcomes.Outcome], wall_time_s: float, sim_time_ns: float) -> NoneType
29,537
cocotb.regression
_safe_divide
null
@staticmethod def _safe_divide(a: float, b: float) -> float: try: return a / b except ZeroDivisionError: if a == 0: return float("nan") else: return float("inf")
(a: float, b: float) -> float
29,538
cocotb.regression
_score_test
Given a test and the test's outcome, determine if the test met expectations and log pertinent information
def _score_test(self, test: Test, outcome: Outcome) -> Tuple[bool, bool]: """ Given a test and the test's outcome, determine if the test met expectations and log pertinent information """ # scoring outcomes result_pass = True sim_failed = False try: outcome.get() except (KeyboardInterrupt, SystemExit): raise except BaseException as e: result = remove_traceback_frames(e, ["_score_test", "get"]) else: result = TestSuccess() if ( isinstance(result, TestSuccess) and not test.expect_fail and not test.expect_error ): self._log_test_passed(test, None, None) elif isinstance(result, TestSuccess) and test.expect_error: self._log_test_failed(test, None, "passed but we expected an error") result_pass = False elif isinstance(result, TestSuccess): self._log_test_failed(test, None, "passed but we expected a failure") result_pass = False elif isinstance(result, SimFailure): if isinstance(result, test.expect_error): self._log_test_passed(test, result, "errored as expected") else: self.log.error("Test error has lead to simulator shutting us down") result_pass = False # whether we expected it or not, the simulation has failed unrecoverably sim_failed = True elif isinstance(result, (AssertionError, _Failed)) and test.expect_fail: self._log_test_passed(test, result, "failed as expected") elif test.expect_error: if isinstance(result, test.expect_error): self._log_test_passed(test, result, "errored as expected") else: self._log_test_failed(test, result, "errored with unexpected type ") result_pass = False else: self._log_test_failed(test, result, None) result_pass = False if _pdb_on_exception: pdb.post_mortem(result.__traceback__) return result_pass, sim_failed
(self, test: cocotb.decorators.test, outcome: cocotb.outcomes.Outcome) -> Tuple[bool, bool]
29,539
cocotb.regression
_start_test
null
def _start_test(self) -> None: # Want this to stand out a little bit start = "" end = "" if want_color_output(): start = ANSI.COLOR_TEST end = ANSI.COLOR_DEFAULT self.log.info( "{start}running{end} {name} ({i}/{total}){description}".format( start=start, i=self.count, total=self.ntests, end=end, name=self._test.__qualname__, description=_trim(self._test.__doc__), ) ) self._test_start_time = time.time() self._test_start_sim_time = get_sim_time("ns") cocotb.scheduler._add_test(self._test_task)
(self) -> NoneType
29,540
cocotb.regression
_tear_down
null
def _tear_down(self) -> None: # prevent re-entering the tear down procedure if not self._tearing_down: self._tearing_down = True else: return # fail remaining tests while True: test = self._next_test() if test is None: break self._record_result( test=test, outcome=Error(SimFailure), wall_time_s=0, sim_time_ns=0 ) # Write out final log messages self._log_test_summary() # Generate output reports self.xunit.write() if self._cov: self._cov.stop() self.log.info("Writing coverage data") self._cov.save() self._cov.html_report() if cocotb._library_coverage is not None: # TODO: move this once we have normal shutdown behavior to _sim_event cocotb._library_coverage.stop() cocotb._library_coverage.save() # Setup simulator finalization simulator.stop_simulator()
(self) -> NoneType
29,541
cocotb.regression
execute
null
# Copyright (c) 2013, 2018 Potential Ventures Ltd # Copyright (c) 2013 SolarFlare Communications Inc # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of Potential Ventures Ltd, # SolarFlare Communications Inc nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL POTENTIAL VENTURES LTD BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """All things relating to regression capabilities.""" import hashlib import inspect import math import os import pdb import random import sys import time import traceback from itertools import product from typing import Any, Iterable, Optional, Tuple, Type import cocotb import cocotb.ANSI as ANSI from cocotb import simulator from cocotb._deprecation import deprecated from cocotb.decorators import test as Test from cocotb.handle import SimHandle from cocotb.log import SimLog from cocotb.outcomes import Error, Outcome from cocotb.result import SimFailure, TestSuccess from cocotb.task import Task from cocotb.utils import get_sim_time, remove_traceback_frames, want_color_output from cocotb.xunit_reporter import XUnitReporter _pdb_on_exception = "COCOTB_PDB_ON_EXCEPTION" in os.environ # Optional support for coverage collection of testbench files coverage = None if "COVERAGE" in os.environ: try: import coverage except ImportError as e: msg = ( "Coverage collection requested but coverage module not available" "\n" "Import error was: %s\n" % repr(e) ) sys.stderr.write(msg) def _my_import(name: str) -> Any: mod = __import__(name) components = name.split(".") for comp in components[1:]: mod = getattr(mod, comp) return mod
(self) -> NoneType
29,545
cocotb.scheduler
Scheduler
The main scheduler. Here we accept callbacks from the simulator and schedule the appropriate coroutines. A callback fires, causing the :any:`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 :class:`~cocotb.triggers.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.
class Scheduler: """The main scheduler. Here we accept callbacks from the simulator and schedule the appropriate coroutines. A callback fires, causing the :any:`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 :class:`~cocotb.triggers.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. """ _MODE_NORMAL = 1 # noqa _MODE_READONLY = 2 # noqa _MODE_WRITE = 3 # noqa _MODE_TERM = 4 # noqa # Singleton events, recycled to avoid spurious object creation _next_time_step = NextTimeStep() _read_write = ReadWrite() _read_only = ReadOnly() _timer1 = Timer(1) def __init__(self, handle_result: Callable[[Task], None]) -> None: self._handle_result = handle_result self.log = SimLog("cocotb.scheduler") if _debug: self.log.setLevel(logging.DEBUG) # Use OrderedDict here for deterministic behavior (gh-934) # A dictionary of pending coroutines for each trigger, # indexed by trigger self._trigger2coros = _py_compat.insertion_ordered_dict() # Our main state self._mode = Scheduler._MODE_NORMAL # A dictionary of pending (write_func, args), keyed by handle. # Writes are applied oldest to newest (least recently used). # Only the last scheduled write to a particular handle in a timestep is performed. self._write_calls = OrderedDict() self._pending_coros = [] self._pending_triggers = [] self._pending_threads = [] self._pending_events = [] # Events we need to call set on once we've unwound self._scheduling = [] self._terminate = False self._test = None self._main_thread = threading.current_thread() self._current_task = None self._is_reacting = False self._write_coro_inst = None self._writes_pending = Event() async def _do_writes(self): """An internal coroutine that performs pending writes""" while True: await self._writes_pending.wait() if self._mode != Scheduler._MODE_NORMAL: await self._next_time_step await self._read_write while self._write_calls: handle, (func, args) = self._write_calls.popitem(last=False) func(*args) self._writes_pending.clear() def _check_termination(self): """ Handle a termination that causes us to move onto the next test. """ if self._terminate: if _debug: self.log.debug("Test terminating, scheduling Timer") if self._write_coro_inst is not None: self._write_coro_inst.kill() self._write_coro_inst = None for t in self._trigger2coros: t.unprime() if self._timer1.primed: self._timer1.unprime() self._timer1.prime(self._test_completed) self._trigger2coros = _py_compat.insertion_ordered_dict() self._terminate = False self._write_calls = OrderedDict() self._writes_pending.clear() self._mode = Scheduler._MODE_TERM def _test_completed(self, trigger=None): """Called after a test and its cleanup have completed""" if _debug: self.log.debug("_test_completed called with trigger: %s" % (str(trigger))) if _profiling: ps = pstats.Stats(_profile).sort_stats("cumulative") ps.dump_stats("test_profile.pstat") ctx = profiling_context() else: ctx = _py_compat.nullcontext() with ctx: self._mode = Scheduler._MODE_NORMAL if trigger is not None: trigger.unprime() # extract the current test, and clear it test = self._test self._test = None if test is None: raise InternalError("_test_completed called with no active test") if test._outcome is None: raise InternalError("_test_completed called with an incomplete test") # Issue previous test result if _debug: self.log.debug("Issue test result to regression object") # this may schedule another test self._handle_result(test) # if it did, make sure we handle the test completing self._check_termination() def react(self, trigger): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._react(trigger) def _react(self, trigger): """ Called when a trigger fires. We ensure that we only start the event loop once, rather than letting it recurse. """ if self._is_reacting: # queue up the trigger, the event loop will get to it self._pending_triggers.append(trigger) return if self._pending_triggers: raise InternalError( "Expected all triggers to be handled but found {}".format( self._pending_triggers ) ) # start the event loop self._is_reacting = True try: self._event_loop(trigger) finally: self._is_reacting = False def _event_loop(self, trigger): """ Run an event loop triggered by the given trigger. The loop will keep running until no further triggers fire. This should be triggered by only: * The beginning of a test, when there is no trigger to react to * A GPI trigger """ if _profiling: ctx = profiling_context() else: ctx = _py_compat.nullcontext() with ctx: # When a trigger fires it is unprimed internally if _debug: self.log.debug("Trigger fired: %s" % str(trigger)) # trigger.unprime() if self._mode == Scheduler._MODE_TERM: if _debug: self.log.debug( "Ignoring trigger %s since we're terminating" % str(trigger) ) return if trigger is self._read_only: self._mode = Scheduler._MODE_READONLY # Only GPI triggers affect the simulator scheduling mode elif isinstance(trigger, GPITrigger): self._mode = Scheduler._MODE_NORMAL # work through triggers one by one is_first = True self._pending_triggers.append(trigger) while self._pending_triggers: trigger = self._pending_triggers.pop(0) if not is_first and isinstance(trigger, GPITrigger): self.log.warning( "A GPI trigger occurred after entering react - this " "should not happen." ) assert False # this only exists to enable the warning above is_first = False # Scheduled coroutines may append to our waiting list so the first # thing to do is pop all entries waiting on this trigger. try: self._scheduling = self._trigger2coros.pop(trigger) except KeyError: # GPI triggers should only be ever pending if there is an # associated coroutine waiting on that trigger, otherwise it would # have been unprimed already if isinstance(trigger, GPITrigger): self.log.critical( "No coroutines waiting on trigger that fired: %s" % str(trigger) ) trigger.log.info("I'm the culprit") # For Python triggers this isn't actually an error - we might do # event.set() without knowing whether any coroutines are actually # waiting on this event, for example elif _debug: self.log.debug( "No coroutines waiting on trigger that fired: %s" % str(trigger) ) del trigger continue if _debug: debugstr = "\n\t".join( [coro._coro.__qualname__ for coro in self._scheduling] ) if len(self._scheduling) > 0: debugstr = "\n\t" + debugstr self.log.debug( "%d pending coroutines for event %s%s" % (len(self._scheduling), str(trigger), debugstr) ) # This trigger isn't needed any more trigger.unprime() for coro in self._scheduling: if coro._outcome is not None: # coroutine was killed by another coroutine waiting on the same trigger continue if _debug: self.log.debug( "Scheduling coroutine %s" % (coro._coro.__qualname__) ) self._schedule(coro, trigger=trigger) if _debug: self.log.debug( "Scheduled coroutine %s" % (coro._coro.__qualname__) ) # remove our reference to the objects at the end of each loop, # to try and avoid them being destroyed at a weird time (as # happened in gh-957) del coro self._scheduling = [] # Handle any newly queued coroutines that need to be scheduled while self._pending_coros: task = self._pending_coros.pop(0) if _debug: self.log.debug( "Scheduling queued coroutine %s" % (task._coro.__qualname__) ) self._schedule(task) if _debug: self.log.debug( "Scheduled queued coroutine %s" % (task._coro.__qualname__) ) del task # Schedule may have queued up some events so we'll burn through those while self._pending_events: if _debug: self.log.debug( "Scheduling pending event %s" % (str(self._pending_events[0])) ) self._pending_events.pop(0).set() # remove our reference to the objects at the end of each loop, # to try and avoid them being destroyed at a weird time (as # happened in gh-957) del trigger # no more pending triggers self._check_termination() if _debug: self.log.debug( "All coroutines scheduled, handing control back" " to simulator" ) def unschedule(self, coro): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._unschedule(coro) def _unschedule(self, coro): """Unschedule a coroutine. Unprime any pending triggers""" if coro in self._pending_coros: assert not coro.has_started() self._pending_coros.remove(coro) # Close coroutine so there is no RuntimeWarning that it was never awaited coro.close() return # Unprime the trigger this coroutine is waiting on trigger = coro._trigger if trigger is not None: coro._trigger = None if coro in self._trigger2coros.setdefault(trigger, []): self._trigger2coros[trigger].remove(coro) if not self._trigger2coros[trigger]: trigger.unprime() del self._trigger2coros[trigger] assert self._test is not None if coro is self._test: if _debug: self.log.debug(f"Unscheduling test {coro}") if not self._terminate: self._terminate = True self._cleanup() elif Join(coro) in self._trigger2coros: self._react(Join(coro)) else: try: # throws an error if the background coroutine errored # and no one was monitoring it coro._outcome.get() except (TestComplete, AssertionError) as e: coro.log.info("Test stopped by this forked coroutine") e = remove_traceback_frames(e, ["_unschedule", "get"]) self._abort_test(e) except BaseException as e: coro.log.error("Exception raised by this forked coroutine") e = remove_traceback_frames(e, ["_unschedule", "get"]) warnings.warn( '"Unwatched" tasks that throw exceptions will not cause the test to fail. ' "See issue #2664 for more details.", FutureWarning, ) self._abort_test(e) def _schedule_write(self, handle, write_func, *args): """Queue `write_func` to be called on the next ReadWrite trigger.""" if self._mode == Scheduler._MODE_READONLY: raise Exception( f"Write to object {handle._name} was scheduled during a read-only sync phase." ) # TODO: we should be able to better keep track of when this needs to # be scheduled if self._write_coro_inst is None: self._write_coro_inst = self._add(self._do_writes()) if handle in self._write_calls: del self._write_calls[handle] self._write_calls[handle] = (write_func, args) self._writes_pending.set() def _resume_coro_upon(self, coro, trigger): """Schedule `coro` to be resumed when `trigger` fires.""" coro._trigger = trigger trigger_coros = self._trigger2coros.setdefault(trigger, []) if coro is self._write_coro_inst: # Our internal write coroutine always runs before any user coroutines. # This preserves the behavior prior to the refactoring of writes to # this coroutine. trigger_coros.insert(0, coro) else: # Everything else joins the back of the queue trigger_coros.append(coro) if not trigger.primed: if trigger_coros != [coro]: # should never happen raise InternalError( "More than one coroutine waiting on an unprimed trigger" ) try: trigger.prime(self._react) except Exception as e: # discard the trigger we associated, it will never fire self._trigger2coros.pop(trigger) # replace it with a new trigger that throws back the exception self._resume_coro_upon( coro, NullTrigger( name="Trigger.prime() Error", outcome=outcomes.Error(e) ), ) def queue(self, coroutine): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._queue(coroutine) def _queue(self, coroutine): """Queue a coroutine for execution""" # Don't queue the same coroutine more than once (gh-2503) if coroutine not in self._pending_coros: self._pending_coros.append(coroutine) def queue_function(self, coro): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._queue_function(coro) def _queue_function(self, coro): """Queue a coroutine for execution and move the containing thread so that it does not block execution of the main thread any longer. """ # We should be able to find ourselves inside the _pending_threads list matching_threads = [ t for t in self._pending_threads if t.thread == threading.current_thread() ] if len(matching_threads) == 0: raise RuntimeError("queue_function called from unrecognized thread") # Raises if there is more than one match. This can never happen, since # each entry always has a unique thread. (t,) = matching_threads async def wrapper(): # This function runs in the scheduler thread try: _outcome = outcomes.Value(await coro) except BaseException as e: _outcome = outcomes.Error(e) event.outcome = _outcome # Notify the current (scheduler) thread that we are about to wake # up the background (`@external`) thread, making sure to do so # before the background thread gets a chance to go back to sleep by # calling thread_suspend. # We need to do this here in the scheduler thread so that no more # coroutines run until the background thread goes back to sleep. t.thread_resume() event.set() event = threading.Event() self._pending_coros.append(Task(wrapper())) # The scheduler thread blocks in `thread_wait`, and is woken when we # call `thread_suspend` - so we need to make sure the coroutine is # queued before that. t.thread_suspend() # This blocks the calling `@external` thread until the coroutine finishes event.wait() return event.outcome.get() def run_in_executor(self, func, *args, **kwargs): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._run_in_executor(func, *args, **kwargs) def _run_in_executor(self, func, *args, **kwargs): """Run the coroutine in a separate execution thread and return an awaitable object for the caller. """ # Create a thread # Create a trigger that is called as a result of the thread finishing # Create an Event object that the caller can await on # Event object set when the thread finishes execution, this blocks the # calling coroutine (but not the thread) until the external completes def execute_external(func, _waiter): _waiter._outcome = outcomes.capture(func, *args, **kwargs) if _debug: self.log.debug( "Execution of external routine done %s" % threading.current_thread() ) _waiter.thread_done() async def wrapper(): waiter = external_waiter() thread = threading.Thread( group=None, target=execute_external, name=func.__qualname__ + "_thread", args=([func, waiter]), kwargs={}, ) waiter.thread = thread self._pending_threads.append(waiter) await waiter.event.wait() return waiter.result # raises if there was an exception return wrapper() @staticmethod def create_task(coroutine: Any) -> Task: """Check to see if the given object is a schedulable coroutine object and if so, return it.""" if isinstance(coroutine, Task): return coroutine if isinstance(coroutine, Coroutine): return Task(coroutine) if inspect.iscoroutinefunction(coroutine): raise TypeError( "Coroutine function {} should be called prior to being " "scheduled.".format(coroutine) ) if isinstance(coroutine, cocotb.decorators.coroutine): raise TypeError( "Attempt to schedule a coroutine that hasn't started: {}.\n" "Did you forget to add parentheses to the @cocotb.test() " "decorator?".format(coroutine) ) if inspect.isasyncgen(coroutine): raise TypeError( "{} is an async generator, not a coroutine. " "You likely used the yield keyword instead of await.".format( coroutine.__qualname__ ) ) raise TypeError( "Attempt to add an object of type {} to the scheduler, which " "isn't a coroutine: {!r}\n" "Did you forget to use the @cocotb.coroutine decorator?".format( type(coroutine), coroutine ) ) @deprecated("This method is now private.") def add(self, coroutine: Union[Task, Coroutine]) -> Task: return self._add(coroutine) def _add(self, coroutine: Union[Task, Coroutine]) -> Task: """Add a new coroutine. Just a wrapper around self.schedule which provides some debug and useful error messages in the event of common gotchas. """ task = self.create_task(coroutine) if _debug: self.log.debug("Adding new coroutine %s" % task._coro.__qualname__) self._schedule(task) self._check_termination() return task def start_soon(self, coro: Union[Coroutine, Task]) -> Task: """ Schedule a coroutine to be run concurrently, starting after the current coroutine yields control. In contrast to :func:`~cocotb.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 :keyword:`await` that may not be safe to execute immediately. .. versionadded:: 1.5 """ task = self.create_task(coro) if _debug: self.log.debug("Queueing a new coroutine %s" % task._coro.__qualname__) self._queue(task) return task def add_test(self, test_coro): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._add_test(test_coro) def _add_test(self, test_coro): """Called by the regression manager to queue the next test""" if self._test is not None: raise InternalError("Test was added while another was in progress") self._test = test_coro self._resume_coro_upon( test_coro, NullTrigger(name=f"Start {test_coro!s}", outcome=outcomes.Value(None)), ) # This collection of functions parses a trigger out of the object # that was yielded by a coroutine, converting `list` -> `Waitable`, # `Waitable` -> `Task`, `Task` -> `Trigger`. # Doing them as separate functions allows us to avoid repeating unnecessary # `isinstance` checks. def _trigger_from_started_coro(self, result: Task) -> Trigger: if _debug: self.log.debug( "Joining to already running coroutine: %s" % result._coro.__qualname__ ) return result.join() def _trigger_from_unstarted_coro(self, result: Task) -> Trigger: self._queue(result) if _debug: self.log.debug( "Scheduling nested coroutine: %s" % result._coro.__qualname__ ) return result.join() def _trigger_from_waitable(self, result: cocotb.triggers.Waitable) -> Trigger: return self._trigger_from_unstarted_coro(Task(result._wait())) def _trigger_from_list(self, result: list) -> Trigger: return self._trigger_from_waitable(cocotb.triggers.First(*result)) def _trigger_from_any(self, result) -> Trigger: """Convert a yielded object into a Trigger instance""" # note: the order of these can significantly impact performance if isinstance(result, Trigger): return result if isinstance(result, Task): if not result.has_started(): return self._trigger_from_unstarted_coro(result) else: return self._trigger_from_started_coro(result) if inspect.iscoroutine(result): return self._trigger_from_unstarted_coro(Task(result)) if isinstance(result, list): return self._trigger_from_list(result) if isinstance(result, cocotb.triggers.Waitable): return self._trigger_from_waitable(result) if inspect.isasyncgen(result): raise TypeError( "{} is an async generator, not a coroutine. " "You likely used the yield keyword instead of await.".format( result.__qualname__ ) ) raise TypeError( "Coroutine yielded an object of type {}, which the scheduler can't " "handle: {!r}\n" "Did you forget to decorate with @cocotb.coroutine?".format( type(result), result ) ) @contextmanager def _task_context(self, task): """Context manager for the currently running task.""" old_task = self._current_task self._current_task = task try: yield finally: self._current_task = old_task def schedule(self, coroutine, trigger=None): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._schedule(coroutine, trigger) def _schedule(self, coroutine, trigger=None): """Schedule a coroutine by calling the send method. Args: coroutine (cocotb.decorators.coroutine): The coroutine to schedule. trigger (cocotb.triggers.Trigger): The trigger that caused this coroutine to be scheduled. """ with self._task_context(coroutine): if trigger is None: send_outcome = outcomes.Value(None) else: send_outcome = trigger._outcome if _debug: self.log.debug(f"Scheduling with {send_outcome}") coroutine._trigger = None result = coroutine._advance(send_outcome) if coroutine.done(): if _debug: self.log.debug( "Coroutine {} completed with {}".format( coroutine, coroutine._outcome ) ) assert result is None self._unschedule(coroutine) # Don't handle the result if we're shutting down if self._terminate: return if not coroutine.done(): if _debug: self.log.debug( "Coroutine %s yielded %s (mode %d)" % (coroutine._coro.__qualname__, str(result), self._mode) ) try: result = self._trigger_from_any(result) except TypeError as exc: # restart this coroutine with an exception object telling it that # it wasn't allowed to yield that result = NullTrigger(outcome=outcomes.Error(exc)) self._resume_coro_upon(coroutine, result) # We do not return from here until pending threads have completed, but only # from the main thread, this seems like it could be problematic in cases # where a sim might change what this thread is. if self._main_thread is threading.current_thread(): for ext in self._pending_threads: ext.thread_start() if _debug: self.log.debug( "Blocking from {} on {}".format( threading.current_thread(), ext.thread ) ) state = ext.thread_wait() if _debug: self.log.debug( "Back from wait on self %s with newstate %d" % (threading.current_thread(), state) ) if state == external_state.EXITED: self._pending_threads.remove(ext) self._pending_events.append(ext.event) def finish_test(self, exc): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._finish_test(exc) def _finish_test(self, exc): self._abort_test(exc) self._check_termination() def _abort_test(self, exc): """Force this test to end early, without executing any cleanup. This happens when a background task fails, and is consistent with how the behavior has always been. In future, we may want to behave more gracefully to allow the test body to clean up. `exc` is the exception that the test should report as its reason for aborting. """ if self._test._outcome is not None: # pragma: no cover raise InternalError("Outcome already has a value, but is being set again.") outcome = outcomes.Error(exc) if _debug: self._test.log.debug(f"outcome forced to {outcome}") self._test._outcome = outcome self._unschedule(self._test) def finish_scheduler(self, exc): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._finish_scheduler(exc) def _finish_scheduler(self, exc): """Directly call into the regression manager and end test once we return the sim will close us so no cleanup is needed. """ # If there is an error during cocotb initialization, self._test may not # have been set yet. Don't cause another Python exception here. if not self._test.done(): self.log.debug("Issue sim closedown result to regression object") self._abort_test(exc) self._handle_result(self._test) def cleanup(self): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._cleanup() def _cleanup(self): """Clear up all our state. Unprime all pending triggers and kill off any coroutines, stop all externals. """ # copy since we modify this in kill items = list((k, list(v)) for k, v in self._trigger2coros.items()) # reversing seems to fix gh-928, although the order is still somewhat # arbitrary. for trigger, waiting in items[::-1]: for coro in waiting: if _debug: self.log.debug("Killing %s" % str(coro)) coro.kill() assert not self._trigger2coros # if there are coroutines being scheduled when the test ends, kill them (gh-1347) for coro in self._scheduling: if _debug: self.log.debug("Killing %s" % str(coro)) coro.kill() self._scheduling = [] # cancel outstanding triggers *before* queued coroutines (gh-3270) while self._pending_triggers: trigger = self._pending_triggers.pop(0) if _debug: self.log.debug("Unpriming %r", trigger) trigger.unprime() assert not self._pending_triggers # Kill any queued coroutines. # We use a while loop because task.kill() calls _unschedule(), which will remove the task from _pending_coros. # If that happens a for loop will stop early and then the assert will fail. while self._pending_coros: # Get first task but leave it in the list so that _unschedule() will correctly close the unstarted coroutine object. task = self._pending_coros[0] task.kill() if self._main_thread is not threading.current_thread(): raise Exception("Cleanup() called outside of the main thread") for ext in self._pending_threads: self.log.warning("Waiting for %s to exit", ext.thread)
(handle_result: Callable[[cocotb.task.Task], NoneType]) -> None
29,546
cocotb.scheduler
__init__
null
def __init__(self, handle_result: Callable[[Task], None]) -> None: self._handle_result = handle_result self.log = SimLog("cocotb.scheduler") if _debug: self.log.setLevel(logging.DEBUG) # Use OrderedDict here for deterministic behavior (gh-934) # A dictionary of pending coroutines for each trigger, # indexed by trigger self._trigger2coros = _py_compat.insertion_ordered_dict() # Our main state self._mode = Scheduler._MODE_NORMAL # A dictionary of pending (write_func, args), keyed by handle. # Writes are applied oldest to newest (least recently used). # Only the last scheduled write to a particular handle in a timestep is performed. self._write_calls = OrderedDict() self._pending_coros = [] self._pending_triggers = [] self._pending_threads = [] self._pending_events = [] # Events we need to call set on once we've unwound self._scheduling = [] self._terminate = False self._test = None self._main_thread = threading.current_thread() self._current_task = None self._is_reacting = False self._write_coro_inst = None self._writes_pending = Event()
(self, handle_result: Callable[[cocotb.task.Task], NoneType]) -> NoneType
29,547
cocotb.scheduler
_abort_test
Force this test to end early, without executing any cleanup. This happens when a background task fails, and is consistent with how the behavior has always been. In future, we may want to behave more gracefully to allow the test body to clean up. `exc` is the exception that the test should report as its reason for aborting.
def _abort_test(self, exc): """Force this test to end early, without executing any cleanup. This happens when a background task fails, and is consistent with how the behavior has always been. In future, we may want to behave more gracefully to allow the test body to clean up. `exc` is the exception that the test should report as its reason for aborting. """ if self._test._outcome is not None: # pragma: no cover raise InternalError("Outcome already has a value, but is being set again.") outcome = outcomes.Error(exc) if _debug: self._test.log.debug(f"outcome forced to {outcome}") self._test._outcome = outcome self._unschedule(self._test)
(self, exc)
29,548
cocotb.scheduler
_add
Add a new coroutine. Just a wrapper around self.schedule which provides some debug and useful error messages in the event of common gotchas.
def _add(self, coroutine: Union[Task, Coroutine]) -> Task: """Add a new coroutine. Just a wrapper around self.schedule which provides some debug and useful error messages in the event of common gotchas. """ task = self.create_task(coroutine) if _debug: self.log.debug("Adding new coroutine %s" % task._coro.__qualname__) self._schedule(task) self._check_termination() return task
(self, coroutine: Union[cocotb.task.Task, collections.abc.Coroutine]) -> cocotb.task.Task
29,549
cocotb.scheduler
_add_test
Called by the regression manager to queue the next test
def _add_test(self, test_coro): """Called by the regression manager to queue the next test""" if self._test is not None: raise InternalError("Test was added while another was in progress") self._test = test_coro self._resume_coro_upon( test_coro, NullTrigger(name=f"Start {test_coro!s}", outcome=outcomes.Value(None)), )
(self, test_coro)
29,550
cocotb.scheduler
_check_termination
Handle a termination that causes us to move onto the next test.
def _check_termination(self): """ Handle a termination that causes us to move onto the next test. """ if self._terminate: if _debug: self.log.debug("Test terminating, scheduling Timer") if self._write_coro_inst is not None: self._write_coro_inst.kill() self._write_coro_inst = None for t in self._trigger2coros: t.unprime() if self._timer1.primed: self._timer1.unprime() self._timer1.prime(self._test_completed) self._trigger2coros = _py_compat.insertion_ordered_dict() self._terminate = False self._write_calls = OrderedDict() self._writes_pending.clear() self._mode = Scheduler._MODE_TERM
(self)
29,551
cocotb.scheduler
_cleanup
Clear up all our state. Unprime all pending triggers and kill off any coroutines, stop all externals.
def _cleanup(self): """Clear up all our state. Unprime all pending triggers and kill off any coroutines, stop all externals. """ # copy since we modify this in kill items = list((k, list(v)) for k, v in self._trigger2coros.items()) # reversing seems to fix gh-928, although the order is still somewhat # arbitrary. for trigger, waiting in items[::-1]: for coro in waiting: if _debug: self.log.debug("Killing %s" % str(coro)) coro.kill() assert not self._trigger2coros # if there are coroutines being scheduled when the test ends, kill them (gh-1347) for coro in self._scheduling: if _debug: self.log.debug("Killing %s" % str(coro)) coro.kill() self._scheduling = [] # cancel outstanding triggers *before* queued coroutines (gh-3270) while self._pending_triggers: trigger = self._pending_triggers.pop(0) if _debug: self.log.debug("Unpriming %r", trigger) trigger.unprime() assert not self._pending_triggers # Kill any queued coroutines. # We use a while loop because task.kill() calls _unschedule(), which will remove the task from _pending_coros. # If that happens a for loop will stop early and then the assert will fail. while self._pending_coros: # Get first task but leave it in the list so that _unschedule() will correctly close the unstarted coroutine object. task = self._pending_coros[0] task.kill() if self._main_thread is not threading.current_thread(): raise Exception("Cleanup() called outside of the main thread") for ext in self._pending_threads: self.log.warning("Waiting for %s to exit", ext.thread)
(self)
29,552
cocotb.scheduler
_do_writes
An internal coroutine that performs pending writes
def __init__(self, handle_result: Callable[[Task], None]) -> None: self._handle_result = handle_result self.log = SimLog("cocotb.scheduler") if _debug: self.log.setLevel(logging.DEBUG) # Use OrderedDict here for deterministic behavior (gh-934) # A dictionary of pending coroutines for each trigger, # indexed by trigger self._trigger2coros = _py_compat.insertion_ordered_dict() # Our main state self._mode = Scheduler._MODE_NORMAL # A dictionary of pending (write_func, args), keyed by handle. # Writes are applied oldest to newest (least recently used). # Only the last scheduled write to a particular handle in a timestep is performed. self._write_calls = OrderedDict() self._pending_coros = [] self._pending_triggers = [] self._pending_threads = [] self._pending_events = [] # Events we need to call set on once we've unwound self._scheduling = [] self._terminate = False self._test = None self._main_thread = threading.current_thread() self._current_task = None self._is_reacting = False self._write_coro_inst = None self._writes_pending = Event()
(self)
29,553
cocotb.scheduler
_event_loop
Run an event loop triggered by the given trigger. The loop will keep running until no further triggers fire. This should be triggered by only: * The beginning of a test, when there is no trigger to react to * A GPI trigger
def _event_loop(self, trigger): """ Run an event loop triggered by the given trigger. The loop will keep running until no further triggers fire. This should be triggered by only: * The beginning of a test, when there is no trigger to react to * A GPI trigger """ if _profiling: ctx = profiling_context() else: ctx = _py_compat.nullcontext() with ctx: # When a trigger fires it is unprimed internally if _debug: self.log.debug("Trigger fired: %s" % str(trigger)) # trigger.unprime() if self._mode == Scheduler._MODE_TERM: if _debug: self.log.debug( "Ignoring trigger %s since we're terminating" % str(trigger) ) return if trigger is self._read_only: self._mode = Scheduler._MODE_READONLY # Only GPI triggers affect the simulator scheduling mode elif isinstance(trigger, GPITrigger): self._mode = Scheduler._MODE_NORMAL # work through triggers one by one is_first = True self._pending_triggers.append(trigger) while self._pending_triggers: trigger = self._pending_triggers.pop(0) if not is_first and isinstance(trigger, GPITrigger): self.log.warning( "A GPI trigger occurred after entering react - this " "should not happen." ) assert False # this only exists to enable the warning above is_first = False # Scheduled coroutines may append to our waiting list so the first # thing to do is pop all entries waiting on this trigger. try: self._scheduling = self._trigger2coros.pop(trigger) except KeyError: # GPI triggers should only be ever pending if there is an # associated coroutine waiting on that trigger, otherwise it would # have been unprimed already if isinstance(trigger, GPITrigger): self.log.critical( "No coroutines waiting on trigger that fired: %s" % str(trigger) ) trigger.log.info("I'm the culprit") # For Python triggers this isn't actually an error - we might do # event.set() without knowing whether any coroutines are actually # waiting on this event, for example elif _debug: self.log.debug( "No coroutines waiting on trigger that fired: %s" % str(trigger) ) del trigger continue if _debug: debugstr = "\n\t".join( [coro._coro.__qualname__ for coro in self._scheduling] ) if len(self._scheduling) > 0: debugstr = "\n\t" + debugstr self.log.debug( "%d pending coroutines for event %s%s" % (len(self._scheduling), str(trigger), debugstr) ) # This trigger isn't needed any more trigger.unprime() for coro in self._scheduling: if coro._outcome is not None: # coroutine was killed by another coroutine waiting on the same trigger continue if _debug: self.log.debug( "Scheduling coroutine %s" % (coro._coro.__qualname__) ) self._schedule(coro, trigger=trigger) if _debug: self.log.debug( "Scheduled coroutine %s" % (coro._coro.__qualname__) ) # remove our reference to the objects at the end of each loop, # to try and avoid them being destroyed at a weird time (as # happened in gh-957) del coro self._scheduling = [] # Handle any newly queued coroutines that need to be scheduled while self._pending_coros: task = self._pending_coros.pop(0) if _debug: self.log.debug( "Scheduling queued coroutine %s" % (task._coro.__qualname__) ) self._schedule(task) if _debug: self.log.debug( "Scheduled queued coroutine %s" % (task._coro.__qualname__) ) del task # Schedule may have queued up some events so we'll burn through those while self._pending_events: if _debug: self.log.debug( "Scheduling pending event %s" % (str(self._pending_events[0])) ) self._pending_events.pop(0).set() # remove our reference to the objects at the end of each loop, # to try and avoid them being destroyed at a weird time (as # happened in gh-957) del trigger # no more pending triggers self._check_termination() if _debug: self.log.debug( "All coroutines scheduled, handing control back" " to simulator" )
(self, trigger)
29,554
cocotb.scheduler
_finish_scheduler
Directly call into the regression manager and end test once we return the sim will close us so no cleanup is needed.
def _finish_scheduler(self, exc): """Directly call into the regression manager and end test once we return the sim will close us so no cleanup is needed. """ # If there is an error during cocotb initialization, self._test may not # have been set yet. Don't cause another Python exception here. if not self._test.done(): self.log.debug("Issue sim closedown result to regression object") self._abort_test(exc) self._handle_result(self._test)
(self, exc)
29,555
cocotb.scheduler
_finish_test
null
def _finish_test(self, exc): self._abort_test(exc) self._check_termination()
(self, exc)
29,556
cocotb.scheduler
_queue
Queue a coroutine for execution
def _queue(self, coroutine): """Queue a coroutine for execution""" # Don't queue the same coroutine more than once (gh-2503) if coroutine not in self._pending_coros: self._pending_coros.append(coroutine)
(self, coroutine)
29,557
cocotb.scheduler
_queue_function
Queue a coroutine for execution and move the containing thread so that it does not block execution of the main thread any longer.
def _queue_function(self, coro): """Queue a coroutine for execution and move the containing thread so that it does not block execution of the main thread any longer. """ # We should be able to find ourselves inside the _pending_threads list matching_threads = [ t for t in self._pending_threads if t.thread == threading.current_thread() ] if len(matching_threads) == 0: raise RuntimeError("queue_function called from unrecognized thread") # Raises if there is more than one match. This can never happen, since # each entry always has a unique thread. (t,) = matching_threads async def wrapper(): # This function runs in the scheduler thread try: _outcome = outcomes.Value(await coro) except BaseException as e: _outcome = outcomes.Error(e) event.outcome = _outcome # Notify the current (scheduler) thread that we are about to wake # up the background (`@external`) thread, making sure to do so # before the background thread gets a chance to go back to sleep by # calling thread_suspend. # We need to do this here in the scheduler thread so that no more # coroutines run until the background thread goes back to sleep. t.thread_resume() event.set() event = threading.Event() self._pending_coros.append(Task(wrapper())) # The scheduler thread blocks in `thread_wait`, and is woken when we # call `thread_suspend` - so we need to make sure the coroutine is # queued before that. t.thread_suspend() # This blocks the calling `@external` thread until the coroutine finishes event.wait() return event.outcome.get()
(self, coro)
29,558
cocotb.scheduler
_react
Called when a trigger fires. We ensure that we only start the event loop once, rather than letting it recurse.
def _react(self, trigger): """ Called when a trigger fires. We ensure that we only start the event loop once, rather than letting it recurse. """ if self._is_reacting: # queue up the trigger, the event loop will get to it self._pending_triggers.append(trigger) return if self._pending_triggers: raise InternalError( "Expected all triggers to be handled but found {}".format( self._pending_triggers ) ) # start the event loop self._is_reacting = True try: self._event_loop(trigger) finally: self._is_reacting = False
(self, trigger)
29,559
cocotb.scheduler
_resume_coro_upon
Schedule `coro` to be resumed when `trigger` fires.
def _resume_coro_upon(self, coro, trigger): """Schedule `coro` to be resumed when `trigger` fires.""" coro._trigger = trigger trigger_coros = self._trigger2coros.setdefault(trigger, []) if coro is self._write_coro_inst: # Our internal write coroutine always runs before any user coroutines. # This preserves the behavior prior to the refactoring of writes to # this coroutine. trigger_coros.insert(0, coro) else: # Everything else joins the back of the queue trigger_coros.append(coro) if not trigger.primed: if trigger_coros != [coro]: # should never happen raise InternalError( "More than one coroutine waiting on an unprimed trigger" ) try: trigger.prime(self._react) except Exception as e: # discard the trigger we associated, it will never fire self._trigger2coros.pop(trigger) # replace it with a new trigger that throws back the exception self._resume_coro_upon( coro, NullTrigger( name="Trigger.prime() Error", outcome=outcomes.Error(e) ), )
(self, coro, trigger)
29,560
cocotb.scheduler
_run_in_executor
Run the coroutine in a separate execution thread and return an awaitable object for the caller.
def _run_in_executor(self, func, *args, **kwargs): """Run the coroutine in a separate execution thread and return an awaitable object for the caller. """ # Create a thread # Create a trigger that is called as a result of the thread finishing # Create an Event object that the caller can await on # Event object set when the thread finishes execution, this blocks the # calling coroutine (but not the thread) until the external completes def execute_external(func, _waiter): _waiter._outcome = outcomes.capture(func, *args, **kwargs) if _debug: self.log.debug( "Execution of external routine done %s" % threading.current_thread() ) _waiter.thread_done() async def wrapper(): waiter = external_waiter() thread = threading.Thread( group=None, target=execute_external, name=func.__qualname__ + "_thread", args=([func, waiter]), kwargs={}, ) waiter.thread = thread self._pending_threads.append(waiter) await waiter.event.wait() return waiter.result # raises if there was an exception return wrapper()
(self, func, *args, **kwargs)
29,561
cocotb.scheduler
_schedule
Schedule a coroutine by calling the send method. Args: coroutine (cocotb.decorators.coroutine): The coroutine to schedule. trigger (cocotb.triggers.Trigger): The trigger that caused this coroutine to be scheduled.
def _schedule(self, coroutine, trigger=None): """Schedule a coroutine by calling the send method. Args: coroutine (cocotb.decorators.coroutine): The coroutine to schedule. trigger (cocotb.triggers.Trigger): The trigger that caused this coroutine to be scheduled. """ with self._task_context(coroutine): if trigger is None: send_outcome = outcomes.Value(None) else: send_outcome = trigger._outcome if _debug: self.log.debug(f"Scheduling with {send_outcome}") coroutine._trigger = None result = coroutine._advance(send_outcome) if coroutine.done(): if _debug: self.log.debug( "Coroutine {} completed with {}".format( coroutine, coroutine._outcome ) ) assert result is None self._unschedule(coroutine) # Don't handle the result if we're shutting down if self._terminate: return if not coroutine.done(): if _debug: self.log.debug( "Coroutine %s yielded %s (mode %d)" % (coroutine._coro.__qualname__, str(result), self._mode) ) try: result = self._trigger_from_any(result) except TypeError as exc: # restart this coroutine with an exception object telling it that # it wasn't allowed to yield that result = NullTrigger(outcome=outcomes.Error(exc)) self._resume_coro_upon(coroutine, result) # We do not return from here until pending threads have completed, but only # from the main thread, this seems like it could be problematic in cases # where a sim might change what this thread is. if self._main_thread is threading.current_thread(): for ext in self._pending_threads: ext.thread_start() if _debug: self.log.debug( "Blocking from {} on {}".format( threading.current_thread(), ext.thread ) ) state = ext.thread_wait() if _debug: self.log.debug( "Back from wait on self %s with newstate %d" % (threading.current_thread(), state) ) if state == external_state.EXITED: self._pending_threads.remove(ext) self._pending_events.append(ext.event)
(self, coroutine, trigger=None)
29,562
cocotb.scheduler
_schedule_write
Queue `write_func` to be called on the next ReadWrite trigger.
def _schedule_write(self, handle, write_func, *args): """Queue `write_func` to be called on the next ReadWrite trigger.""" if self._mode == Scheduler._MODE_READONLY: raise Exception( f"Write to object {handle._name} was scheduled during a read-only sync phase." ) # TODO: we should be able to better keep track of when this needs to # be scheduled if self._write_coro_inst is None: self._write_coro_inst = self._add(self._do_writes()) if handle in self._write_calls: del self._write_calls[handle] self._write_calls[handle] = (write_func, args) self._writes_pending.set()
(self, handle, write_func, *args)
29,563
cocotb.scheduler
_task_context
Context manager for the currently running task.
def __init__(self, handle_result: Callable[[Task], None]) -> None: self._handle_result = handle_result self.log = SimLog("cocotb.scheduler") if _debug: self.log.setLevel(logging.DEBUG) # Use OrderedDict here for deterministic behavior (gh-934) # A dictionary of pending coroutines for each trigger, # indexed by trigger self._trigger2coros = _py_compat.insertion_ordered_dict() # Our main state self._mode = Scheduler._MODE_NORMAL # A dictionary of pending (write_func, args), keyed by handle. # Writes are applied oldest to newest (least recently used). # Only the last scheduled write to a particular handle in a timestep is performed. self._write_calls = OrderedDict() self._pending_coros = [] self._pending_triggers = [] self._pending_threads = [] self._pending_events = [] # Events we need to call set on once we've unwound self._scheduling = [] self._terminate = False self._test = None self._main_thread = threading.current_thread() self._current_task = None self._is_reacting = False self._write_coro_inst = None self._writes_pending = Event()
(self, task)
29,564
cocotb.scheduler
_test_completed
Called after a test and its cleanup have completed
def _test_completed(self, trigger=None): """Called after a test and its cleanup have completed""" if _debug: self.log.debug("_test_completed called with trigger: %s" % (str(trigger))) if _profiling: ps = pstats.Stats(_profile).sort_stats("cumulative") ps.dump_stats("test_profile.pstat") ctx = profiling_context() else: ctx = _py_compat.nullcontext() with ctx: self._mode = Scheduler._MODE_NORMAL if trigger is not None: trigger.unprime() # extract the current test, and clear it test = self._test self._test = None if test is None: raise InternalError("_test_completed called with no active test") if test._outcome is None: raise InternalError("_test_completed called with an incomplete test") # Issue previous test result if _debug: self.log.debug("Issue test result to regression object") # this may schedule another test self._handle_result(test) # if it did, make sure we handle the test completing self._check_termination()
(self, trigger=None)
29,565
cocotb.scheduler
_trigger_from_any
Convert a yielded object into a Trigger instance
def _trigger_from_any(self, result) -> Trigger: """Convert a yielded object into a Trigger instance""" # note: the order of these can significantly impact performance if isinstance(result, Trigger): return result if isinstance(result, Task): if not result.has_started(): return self._trigger_from_unstarted_coro(result) else: return self._trigger_from_started_coro(result) if inspect.iscoroutine(result): return self._trigger_from_unstarted_coro(Task(result)) if isinstance(result, list): return self._trigger_from_list(result) if isinstance(result, cocotb.triggers.Waitable): return self._trigger_from_waitable(result) if inspect.isasyncgen(result): raise TypeError( "{} is an async generator, not a coroutine. " "You likely used the yield keyword instead of await.".format( result.__qualname__ ) ) raise TypeError( "Coroutine yielded an object of type {}, which the scheduler can't " "handle: {!r}\n" "Did you forget to decorate with @cocotb.coroutine?".format( type(result), result ) )
(self, result) -> cocotb.triggers.Trigger
29,566
cocotb.scheduler
_trigger_from_list
null
def _trigger_from_list(self, result: list) -> Trigger: return self._trigger_from_waitable(cocotb.triggers.First(*result))
(self, result: list) -> cocotb.triggers.Trigger
29,567
cocotb.scheduler
_trigger_from_started_coro
null
def _trigger_from_started_coro(self, result: Task) -> Trigger: if _debug: self.log.debug( "Joining to already running coroutine: %s" % result._coro.__qualname__ ) return result.join()
(self, result: cocotb.task.Task) -> cocotb.triggers.Trigger
29,568
cocotb.scheduler
_trigger_from_unstarted_coro
null
def _trigger_from_unstarted_coro(self, result: Task) -> Trigger: self._queue(result) if _debug: self.log.debug( "Scheduling nested coroutine: %s" % result._coro.__qualname__ ) return result.join()
(self, result: cocotb.task.Task) -> cocotb.triggers.Trigger
29,569
cocotb.scheduler
_trigger_from_waitable
null
def _trigger_from_waitable(self, result: cocotb.triggers.Waitable) -> Trigger: return self._trigger_from_unstarted_coro(Task(result._wait()))
(self, result: cocotb.triggers.Waitable) -> cocotb.triggers.Trigger
29,570
cocotb.scheduler
_unschedule
Unschedule a coroutine. Unprime any pending triggers
def _unschedule(self, coro): """Unschedule a coroutine. Unprime any pending triggers""" if coro in self._pending_coros: assert not coro.has_started() self._pending_coros.remove(coro) # Close coroutine so there is no RuntimeWarning that it was never awaited coro.close() return # Unprime the trigger this coroutine is waiting on trigger = coro._trigger if trigger is not None: coro._trigger = None if coro in self._trigger2coros.setdefault(trigger, []): self._trigger2coros[trigger].remove(coro) if not self._trigger2coros[trigger]: trigger.unprime() del self._trigger2coros[trigger] assert self._test is not None if coro is self._test: if _debug: self.log.debug(f"Unscheduling test {coro}") if not self._terminate: self._terminate = True self._cleanup() elif Join(coro) in self._trigger2coros: self._react(Join(coro)) else: try: # throws an error if the background coroutine errored # and no one was monitoring it coro._outcome.get() except (TestComplete, AssertionError) as e: coro.log.info("Test stopped by this forked coroutine") e = remove_traceback_frames(e, ["_unschedule", "get"]) self._abort_test(e) except BaseException as e: coro.log.error("Exception raised by this forked coroutine") e = remove_traceback_frames(e, ["_unschedule", "get"]) warnings.warn( '"Unwatched" tasks that throw exceptions will not cause the test to fail. ' "See issue #2664 for more details.", FutureWarning, ) self._abort_test(e)
(self, coro)
29,571
cocotb.scheduler
add
null
#!/usr/bin/env python # Copyright (c) 2013, 2018 Potential Ventures Ltd # Copyright (c) 2013 SolarFlare Communications Inc # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of Potential Ventures Ltd, # SolarFlare Communications Inc nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL POTENTIAL VENTURES LTD BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Coroutine scheduler. FIXME: We have a problem here. If a coroutine schedules a read-only but we also have pending writes we have to schedule the ReadWrite callback before the ReadOnly (and this is invalid, at least in Modelsim). """ import inspect import logging import os import threading import warnings from collections import OrderedDict from collections.abc import Coroutine from contextlib import contextmanager from typing import Any, Callable, Union import cocotb import cocotb.decorators from cocotb import _py_compat, outcomes from cocotb._deprecation import deprecated from cocotb.log import SimLog from cocotb.result import TestComplete from cocotb.task import Task from cocotb.triggers import ( Event, GPITrigger, Join, NextTimeStep, NullTrigger, ReadOnly, ReadWrite, Timer, Trigger, ) from cocotb.utils import remove_traceback_frames # Debug mode controlled by environment variables _profiling = "COCOTB_ENABLE_PROFILING" in os.environ if _profiling: import cProfile import pstats _profile = cProfile.Profile() # Sadly the Python standard logging module is very slow so it's better not to # make any calls by testing a boolean flag first _debug = "COCOTB_SCHEDULER_DEBUG" in os.environ class InternalError(BaseException): """An error internal to scheduler. If you see this, report a bug!""" pass
(self, coroutine: Union[cocotb.task.Task, collections.abc.Coroutine]) -> cocotb.task.Task
29,572
cocotb.scheduler
add_test
.. deprecated:: 1.5 This function is now private.
def add_test(self, test_coro): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._add_test(test_coro)
(self, test_coro)
29,573
cocotb.scheduler
cleanup
.. deprecated:: 1.5 This function is now private.
def cleanup(self): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._cleanup()
(self)
29,574
cocotb.scheduler
create_task
Check to see if the given object is a schedulable coroutine object and if so, return it.
@staticmethod def create_task(coroutine: Any) -> Task: """Check to see if the given object is a schedulable coroutine object and if so, return it.""" if isinstance(coroutine, Task): return coroutine if isinstance(coroutine, Coroutine): return Task(coroutine) if inspect.iscoroutinefunction(coroutine): raise TypeError( "Coroutine function {} should be called prior to being " "scheduled.".format(coroutine) ) if isinstance(coroutine, cocotb.decorators.coroutine): raise TypeError( "Attempt to schedule a coroutine that hasn't started: {}.\n" "Did you forget to add parentheses to the @cocotb.test() " "decorator?".format(coroutine) ) if inspect.isasyncgen(coroutine): raise TypeError( "{} is an async generator, not a coroutine. " "You likely used the yield keyword instead of await.".format( coroutine.__qualname__ ) ) raise TypeError( "Attempt to add an object of type {} to the scheduler, which " "isn't a coroutine: {!r}\n" "Did you forget to use the @cocotb.coroutine decorator?".format( type(coroutine), coroutine ) )
(coroutine: Any) -> cocotb.task.Task
29,575
cocotb.scheduler
finish_scheduler
.. deprecated:: 1.5 This function is now private.
def finish_scheduler(self, exc): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._finish_scheduler(exc)
(self, exc)
29,576
cocotb.scheduler
finish_test
.. deprecated:: 1.5 This function is now private.
def finish_test(self, exc): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._finish_test(exc)
(self, exc)
29,577
cocotb.scheduler
queue
.. deprecated:: 1.5 This function is now private.
def queue(self, coroutine): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._queue(coroutine)
(self, coroutine)
29,578
cocotb.scheduler
queue_function
.. deprecated:: 1.5 This function is now private.
def queue_function(self, coro): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._queue_function(coro)
(self, coro)
29,579
cocotb.scheduler
react
.. deprecated:: 1.5 This function is now private.
def react(self, trigger): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._react(trigger)
(self, trigger)
29,580
cocotb.scheduler
run_in_executor
.. deprecated:: 1.5 This function is now private.
def run_in_executor(self, func, *args, **kwargs): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._run_in_executor(func, *args, **kwargs)
(self, func, *args, **kwargs)
29,581
cocotb.scheduler
schedule
.. deprecated:: 1.5 This function is now private.
def schedule(self, coroutine, trigger=None): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._schedule(coroutine, trigger)
(self, coroutine, trigger=None)
29,582
cocotb.scheduler
start_soon
Schedule a coroutine to be run concurrently, starting after the current coroutine yields control. In contrast to :func:`~cocotb.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 :keyword:`await` that may not be safe to execute immediately. .. versionadded:: 1.5
def start_soon(self, coro: Union[Coroutine, Task]) -> Task: """ Schedule a coroutine to be run concurrently, starting after the current coroutine yields control. In contrast to :func:`~cocotb.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 :keyword:`await` that may not be safe to execute immediately. .. versionadded:: 1.5 """ task = self.create_task(coro) if _debug: self.log.debug("Queueing a new coroutine %s" % task._coro.__qualname__) self._queue(task) return task
(self, coro: Union[collections.abc.Coroutine, cocotb.task.Task]) -> cocotb.task.Task
29,583
cocotb.scheduler
unschedule
.. deprecated:: 1.5 This function is now private.
def unschedule(self, coro): """ .. deprecated:: 1.5 This function is now private. """ warnings.warn("This function is now private.", DeprecationWarning, stacklevel=2) return self._unschedule(coro)
(self, coro)
29,584
cocotb.task
Task
Concurrently executing task. This class is not intended for users to directly instantiate. Use :func:`cocotb.create_task` to create a Task object, or use :func:`cocotb.start_soon` or :func:`cocotb.start` to create a Task and schedule it to run. .. versionchanged:: 1.8.0 Moved to the ``cocotb.task`` module.
class Task(typing.Coroutine[typing.Any, typing.Any, T]): """Concurrently executing task. This class is not intended for users to directly instantiate. Use :func:`cocotb.create_task` to create a Task object, or use :func:`cocotb.start_soon` or :func:`cocotb.start` to create a Task and schedule it to run. .. versionchanged:: 1.8.0 Moved to the ``cocotb.task`` module. """ _name: str = "Task" # class name of schedulable task _id_count = 0 # used by the scheduler for debug def __init__(self, inst): if isinstance(inst, collections.abc.Coroutine): self._natively_awaitable = True elif inspect.isgenerator(inst): self._natively_awaitable = False elif inspect.iscoroutinefunction(inst): raise TypeError( "Coroutine function {} should be called prior to being " "scheduled.".format(inst) ) elif inspect.isasyncgen(inst): raise TypeError( "{} is an async generator, not a coroutine. " "You likely used the yield keyword instead of await.".format( inst.__qualname__ ) ) else: raise TypeError( f"{inst} isn't a valid coroutine! Did you forget to use the yield keyword?" ) self._coro = inst self._started = False self._outcome: outcomes.Outcome = None self._trigger: typing.Optional[cocotb.triggers.Trigger] = None self._cancelled: typing.Optional[CancelledError] = None self._task_id = self._id_count type(self)._id_count += 1 self.__name__ = f"{type(self)._name} {self._task_id}" self.__qualname__ = self.__name__ @lazy_property def log(self) -> SimLog: # Creating a logger is expensive, only do it if we actually plan to # log anything return SimLog(f"cocotb.{self.__qualname__}.{self._coro.__qualname__}") @property def retval(self) -> T: """Return the result of the Task. If the Task ran to completion, the result is returned. If the Task failed with an exception, the exception is re-raised. If the Task is not yet complete, a :exc:`RuntimeError` is raised. .. deprecated:: 1.7.0 """ warnings.warn( "Deprecated in favor of the result() method. " "Replace `task.retval` with `task.result()`.", DeprecationWarning, stacklevel=2, ) if self._outcome is None: raise RuntimeError("coroutine is not complete") return self._outcome.get() @property def _finished(self) -> bool: """``True`` if the Task is finished executing. .. deprecated:: 1.7.0 """ warnings.warn( "Deprecated in favor of the done() method. " "Replace `task._finished` with `task.done()`.", DeprecationWarning, stacklevel=2, ) return self._outcome is not None def __iter__(self: Self) -> Self: # for use in "yield from" statements return self def __str__(self) -> str: return f"<{self.__name__}>" def _get_coro_stack(self) -> typing.Any: """Get the coroutine callstack of this Task.""" coro_stack = extract_coro_stack(self._coro) # Remove Trigger.__await__() from the stack, as it's not really useful if self._natively_awaitable and len(coro_stack): if coro_stack[-1].name == "__await__": coro_stack.pop() return coro_stack def __repr__(self) -> str: coro_stack = self._get_coro_stack() if cocotb.scheduler._current_task is self: fmt = "<{name} running coro={coro}()>" elif self.done(): fmt = "<{name} finished coro={coro}() outcome={outcome}>" elif self._trigger is not None: fmt = "<{name} pending coro={coro}() trigger={trigger}>" elif not self._started: fmt = "<{name} created coro={coro}()>" else: fmt = "<{name} adding coro={coro}()>" try: coro_name = coro_stack[-1].name # coro_stack may be empty if: # - exhausted generator # - finished coroutine except IndexError: coro_name = self._coro.__name__ repr_string = fmt.format( name=self.__name__, coro=coro_name, trigger=self._trigger, outcome=self._outcome, ) return repr_string def _advance(self, outcome: outcomes.Outcome) -> typing.Any: """Advance to the next yield in this coroutine. Args: outcome: The :any:`outcomes.Outcome` object to resume with. Returns: The object yielded from the coroutine or None if coroutine finished """ try: self._started = True return outcome.send(self._coro) except ReturnValue as e: self._outcome = outcomes.Value(e.retval) except StopIteration as e: self._outcome = outcomes.Value(e.value) except BaseException as e: self._outcome = outcomes.Error( remove_traceback_frames(e, ["_advance", "send"]) ) def send(self, value: typing.Any) -> typing.Any: return self._coro.send(value) def throw(self, exc: BaseException) -> typing.Any: return self._coro.throw(exc) def close(self) -> None: return self._coro.close() def kill(self) -> None: """Kill a coroutine.""" if self._outcome is not None: # already finished, nothing to kill return if _debug: self.log.debug("kill() called on coroutine") # todo: probably better to throw an exception for anyone waiting on the coroutine self._outcome = outcomes.Value(None) cocotb.scheduler._unschedule(self) def join(self) -> "cocotb.triggers.Join": """Return a trigger that will fire when the wrapped coroutine exits.""" return cocotb.triggers.Join(self) def has_started(self) -> bool: """Return ``True`` if the Task has started executing.""" return self._started def cancel(self, msg: typing.Optional[str] = None) -> None: """Cancel a Task's further execution. When a Task is cancelled, a :exc:`asyncio.CancelledError` is thrown into the Task. """ self._cancelled = CancelledError(msg) warnings.warn( "Calling this method will cause a CancelledError to be thrown in the " "Task sometime in the future.", FutureWarning, stacklevel=2, ) self.kill() def cancelled(self) -> bool: """Return ``True`` if the Task was cancelled.""" return self._cancelled is not None def done(self) -> bool: """Return ``True`` if the Task has finished executing.""" return self._outcome is not None or self.cancelled() def result(self) -> T: """Return the result of the Task. If the Task ran to completion, the result is returned. If the Task failed with an exception, the exception is re-raised. If the Task was cancelled, the CancelledError is re-raised. If the coroutine is not yet complete, a :exc:`asyncio.InvalidStateError` is raised. """ if not self.done(): raise InvalidStateError("result is not yet available") elif self.cancelled(): raise self._cancelled else: return self._outcome.get() def exception(self) -> typing.Optional[BaseException]: """Return the exception of the Task. If the Task ran to completion, ``None`` is returned. If the Task failed with an exception, the exception is returned. If the Task was cancelled, the CancelledError is re-raised. If the coroutine is not yet complete, a :exc:`asyncio.InvalidStateError` is raised. """ if not self.done(): raise InvalidStateError("result is not yet available") elif self.cancelled(): raise self._cancelled elif isinstance(self._outcome, outcomes.Error): return self._outcome.error else: return None def __bool__(self) -> bool: """``True`` if Task is not done. .. deprecated:: 1.7.0 """ warnings.warn( "Deprecated in favor of the done() method. " "Replace with `not task.done()`.", DeprecationWarning, stacklevel=2, ) return not self.done() def __await__(self) -> typing.Generator[typing.Any, typing.Any, T]: # It's tempting to use `return (yield from self._coro)` here, # which bypasses the scheduler. Unfortunately, this means that # we can't keep track of the result or state of the coroutine, # things which we expose in our public API. If you want the # efficiency of bypassing the scheduler, remove the `@coroutine` # decorator from your `async` functions. # Hand the coroutine back to the scheduler trampoline. return (yield self)
(inst)
29,585
cocotb.task
__await__
null
def __await__(self) -> typing.Generator[typing.Any, typing.Any, T]: # It's tempting to use `return (yield from self._coro)` here, # which bypasses the scheduler. Unfortunately, this means that # we can't keep track of the result or state of the coroutine, # things which we expose in our public API. If you want the # efficiency of bypassing the scheduler, remove the `@coroutine` # decorator from your `async` functions. # Hand the coroutine back to the scheduler trampoline. return (yield self)
(self) -> Generator[Any, Any, ~T]
29,586
cocotb.task
__bool__
``True`` if Task is not done. .. deprecated:: 1.7.0
def __bool__(self) -> bool: """``True`` if Task is not done. .. deprecated:: 1.7.0 """ warnings.warn( "Deprecated in favor of the done() method. " "Replace with `not task.done()`.", DeprecationWarning, stacklevel=2, ) return not self.done()
(self) -> bool
29,587
cocotb.task
__init__
null
def __init__(self, inst): if isinstance(inst, collections.abc.Coroutine): self._natively_awaitable = True elif inspect.isgenerator(inst): self._natively_awaitable = False elif inspect.iscoroutinefunction(inst): raise TypeError( "Coroutine function {} should be called prior to being " "scheduled.".format(inst) ) elif inspect.isasyncgen(inst): raise TypeError( "{} is an async generator, not a coroutine. " "You likely used the yield keyword instead of await.".format( inst.__qualname__ ) ) else: raise TypeError( f"{inst} isn't a valid coroutine! Did you forget to use the yield keyword?" ) self._coro = inst self._started = False self._outcome: outcomes.Outcome = None self._trigger: typing.Optional[cocotb.triggers.Trigger] = None self._cancelled: typing.Optional[CancelledError] = None self._task_id = self._id_count type(self)._id_count += 1 self.__name__ = f"{type(self)._name} {self._task_id}" self.__qualname__ = self.__name__
(self, inst)
29,588
cocotb.task
__iter__
null
def __iter__(self: Self) -> Self: # for use in "yield from" statements return self
(self: ~Self) -> ~Self
29,589
cocotb.task
__repr__
null
def __repr__(self) -> str: coro_stack = self._get_coro_stack() if cocotb.scheduler._current_task is self: fmt = "<{name} running coro={coro}()>" elif self.done(): fmt = "<{name} finished coro={coro}() outcome={outcome}>" elif self._trigger is not None: fmt = "<{name} pending coro={coro}() trigger={trigger}>" elif not self._started: fmt = "<{name} created coro={coro}()>" else: fmt = "<{name} adding coro={coro}()>" try: coro_name = coro_stack[-1].name # coro_stack may be empty if: # - exhausted generator # - finished coroutine except IndexError: coro_name = self._coro.__name__ repr_string = fmt.format( name=self.__name__, coro=coro_name, trigger=self._trigger, outcome=self._outcome, ) return repr_string
(self) -> str
29,590
cocotb.task
__str__
null
def __str__(self) -> str: return f"<{self.__name__}>"
(self) -> str
29,591
cocotb.task
_advance
Advance to the next yield in this coroutine. Args: outcome: The :any:`outcomes.Outcome` object to resume with. Returns: The object yielded from the coroutine or None if coroutine finished
def _advance(self, outcome: outcomes.Outcome) -> typing.Any: """Advance to the next yield in this coroutine. Args: outcome: The :any:`outcomes.Outcome` object to resume with. Returns: The object yielded from the coroutine or None if coroutine finished """ try: self._started = True return outcome.send(self._coro) except ReturnValue as e: self._outcome = outcomes.Value(e.retval) except StopIteration as e: self._outcome = outcomes.Value(e.value) except BaseException as e: self._outcome = outcomes.Error( remove_traceback_frames(e, ["_advance", "send"]) )
(self, outcome: cocotb.outcomes.Outcome) -> Any
29,592
cocotb.task
_get_coro_stack
Get the coroutine callstack of this Task.
def _get_coro_stack(self) -> typing.Any: """Get the coroutine callstack of this Task.""" coro_stack = extract_coro_stack(self._coro) # Remove Trigger.__await__() from the stack, as it's not really useful if self._natively_awaitable and len(coro_stack): if coro_stack[-1].name == "__await__": coro_stack.pop() return coro_stack
(self) -> Any
29,593
cocotb.task
cancel
Cancel a Task's further execution. When a Task is cancelled, a :exc:`asyncio.CancelledError` is thrown into the Task.
def cancel(self, msg: typing.Optional[str] = None) -> None: """Cancel a Task's further execution. When a Task is cancelled, a :exc:`asyncio.CancelledError` is thrown into the Task. """ self._cancelled = CancelledError(msg) warnings.warn( "Calling this method will cause a CancelledError to be thrown in the " "Task sometime in the future.", FutureWarning, stacklevel=2, ) self.kill()
(self, msg: Optional[str] = None) -> NoneType
29,594
cocotb.task
cancelled
Return ``True`` if the Task was cancelled.
def cancelled(self) -> bool: """Return ``True`` if the Task was cancelled.""" return self._cancelled is not None
(self) -> bool
29,595
cocotb.task
close
null
def close(self) -> None: return self._coro.close()
(self) -> NoneType
29,596
cocotb.task
done
Return ``True`` if the Task has finished executing.
def done(self) -> bool: """Return ``True`` if the Task has finished executing.""" return self._outcome is not None or self.cancelled()
(self) -> bool
29,597
cocotb.task
exception
Return the exception of the Task. If the Task ran to completion, ``None`` is returned. If the Task failed with an exception, the exception is returned. If the Task was cancelled, the CancelledError is re-raised. If the coroutine is not yet complete, a :exc:`asyncio.InvalidStateError` is raised.
def exception(self) -> typing.Optional[BaseException]: """Return the exception of the Task. If the Task ran to completion, ``None`` is returned. If the Task failed with an exception, the exception is returned. If the Task was cancelled, the CancelledError is re-raised. If the coroutine is not yet complete, a :exc:`asyncio.InvalidStateError` is raised. """ if not self.done(): raise InvalidStateError("result is not yet available") elif self.cancelled(): raise self._cancelled elif isinstance(self._outcome, outcomes.Error): return self._outcome.error else: return None
(self) -> Optional[BaseException]
29,598
cocotb.task
has_started
Return ``True`` if the Task has started executing.
def has_started(self) -> bool: """Return ``True`` if the Task has started executing.""" return self._started
(self) -> bool
29,599
cocotb.task
join
Return a trigger that will fire when the wrapped coroutine exits.
def join(self) -> "cocotb.triggers.Join": """Return a trigger that will fire when the wrapped coroutine exits.""" return cocotb.triggers.Join(self)
(self) -> cocotb.triggers.Join
29,600
cocotb.task
kill
Kill a coroutine.
def kill(self) -> None: """Kill a coroutine.""" if self._outcome is not None: # already finished, nothing to kill return if _debug: self.log.debug("kill() called on coroutine") # todo: probably better to throw an exception for anyone waiting on the coroutine self._outcome = outcomes.Value(None) cocotb.scheduler._unschedule(self)
(self) -> NoneType
29,601
cocotb.task
result
Return the result of the Task. If the Task ran to completion, the result is returned. If the Task failed with an exception, the exception is re-raised. If the Task was cancelled, the CancelledError is re-raised. If the coroutine is not yet complete, a :exc:`asyncio.InvalidStateError` is raised.
def result(self) -> T: """Return the result of the Task. If the Task ran to completion, the result is returned. If the Task failed with an exception, the exception is re-raised. If the Task was cancelled, the CancelledError is re-raised. If the coroutine is not yet complete, a :exc:`asyncio.InvalidStateError` is raised. """ if not self.done(): raise InvalidStateError("result is not yet available") elif self.cancelled(): raise self._cancelled else: return self._outcome.get()
(self) -> ~T
29,602
cocotb.task
send
null
def send(self, value: typing.Any) -> typing.Any: return self._coro.send(value)
(self, value: Any) -> Any
29,603
cocotb.task
throw
null
def throw(self, exc: BaseException) -> typing.Any: return self._coro.throw(exc)
(self, exc: BaseException) -> Any
29,605
cocotb.log
_filter_from_c
null
def _filter_from_c(logger_name, level): return logging.getLogger(logger_name).isEnabledFor(level)
(logger_name, level)
29,606
cocotb
_initialise_testbench
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`.
def _initialise_testbench(argv_): # pragma: no cover """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: if "COCOTB_LIBRARY_COVERAGE" in os.environ: import coverage global _library_coverage _library_coverage = coverage.coverage( data_file=".coverage.cocotb", config_file=False, branch=True, include=["{}/*".format(os.path.dirname(__file__))], ) _library_coverage.start() _initialise_testbench_(argv_)
(argv_)
29,607
cocotb
_initialise_testbench_
null
def _initialise_testbench_(argv_): # The body of this function is split in two because no coverage is collected on # the function that starts the coverage. By splitting it in two we get coverage # on most of the function. 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: # Skip any library component of the toplevel root_name = root_name.split(".", 1)[1] # sys.path normally includes "" (the current directory), but does not appear to when python is embedded. # Add it back because users expect to be able to import files in their test directory. # TODO: move this to gpi_embed.cpp sys.path.insert(0, "") _setup_logging() # From https://www.python.org/dev/peps/pep-0565/#recommended-filter-settings-for-test-runners # If the user doesn't want to see these, they can always change the global # warning settings in their test module. 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}") memcheck_port = os.getenv("MEMCHECK") if memcheck_port is not None: mem_debug(int(memcheck_port)) log.info( "Running tests with cocotb v%s from %s" % (__version__, os.path.dirname(__file__)) ) # Create the base handle type _process_plusargs() # Seed the Python random number generator to make this repeatable 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) # Setup DUT object from cocotb import simulator 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) global regression_manager regression_manager = RegressionManager.from_discovery(top) global scheduler scheduler = Scheduler(handle_result=regression_manager._handle_result) # start Regression Manager regression_manager._execute()
(argv_)
29,608
cocotb.log
_log_from_c
This is for use from the C world, and allows us to insert C stack information.
def _log_from_c(logger_name, level, filename, lineno, msg, function_name): """ This is for use from the C world, and allows us to insert C stack information. """ logger = logging.getLogger(logger_name) if logger.isEnabledFor(level): record = logger.makeRecord( logger.name, level, filename, lineno, msg, None, None, function_name ) logger.handle(record)
(logger_name, level, filename, lineno, msg, function_name)
29,609
cocotb
_process_plusargs
null
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
() -> NoneType
29,611
cocotb
_setup_logging
null
def _setup_logging() -> None: default_config() global log log = logging.getLogger(__name__)
() -> NoneType
29,612
cocotb
_sim_event
Function that can be called externally to signal an event.
def _sim_event(message): """Function that can be called externally to signal an event.""" from cocotb.result import SimFailure # We simply return here as the simulator will exit # so no cleanup is needed msg = f"Failing test at simulator request before test run completion: {message}" scheduler.log.error(msg) scheduler._finish_scheduler(SimFailure(msg))
(message)
29,616
cocotb.decorators
coroutine
Decorator class that allows us to provide common coroutine mechanisms: ``log`` methods will log to ``cocotb.coroutine.name``. :meth:`~cocotb.task.Task.join` method returns an event which will fire when the coroutine exits. Used as ``@cocotb.coroutine``.
class coroutine: """Decorator class that allows us to provide common coroutine mechanisms: ``log`` methods will log to ``cocotb.coroutine.name``. :meth:`~cocotb.task.Task.join` method returns an event which will fire when the coroutine exits. Used as ``@cocotb.coroutine``. """ def __init__(self, func): self._func = func functools.update_wrapper(self, func) @lazy_property def log(self): return SimLog(f"cocotb.coroutine.{self._func.__qualname__}.{id(self)}") def __call__(self, *args, **kwargs): return _RunningCoroutine(self._func(*args, **kwargs), self) def __get__(self, obj, owner=None): """Permit the decorator to be used on class methods and standalone functions""" return type(self)(self._func.__get__(obj, owner)) def __iter__(self): return self def __str__(self): return str(self._func.__qualname__)
(func)
29,617
cocotb.decorators
__call__
null
def __call__(self, *args, **kwargs): return _RunningCoroutine(self._func(*args, **kwargs), self)
(self, *args, **kwargs)
29,618
cocotb.decorators
__get__
Permit the decorator to be used on class methods and standalone functions
def __get__(self, obj, owner=None): """Permit the decorator to be used on class methods and standalone functions""" return type(self)(self._func.__get__(obj, owner))
(self, obj, owner=None)
29,619
cocotb.decorators
__init__
null
def __init__(self, func): self._func = func functools.update_wrapper(self, func)
(self, func)
29,621
cocotb.decorators
__str__
null
def __str__(self): return str(self._func.__qualname__)
(self)
29,622
cocotb
create_task
Construct a coroutine into a Task without scheduling the Task. The Task can later be scheduled with :func:`cocotb.fork`, :func:`cocotb.start`, or :func:`cocotb.start_soon`. .. versionadded:: 1.6.0
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.fork`, :func:`cocotb.start`, or :func:`cocotb.start_soon`. .. versionadded:: 1.6.0 """ return cocotb.scheduler.create_task(coro)
(coro: Union[cocotb.task.Task, collections.abc.Coroutine]) -> cocotb.task.Task
29,624
cocotb.log
default_config
Apply the default cocotb log formatting to the root logger. This hooks up the logger to write to stdout, using either :class:`SimColourLogFormatter` or :class:`SimLogFormatter` depending on whether colored output is requested. It also adds a :class:`SimTimeContextFilter` filter so that :attr:`~logging.LogRecord.created_sim_time` is available to the formatter. The logging level for cocotb logs is set based on the :envvar:`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 :ref:`rotating-logger`. .. versionadded:: 1.4
def default_config(): """Apply the default cocotb log formatting to the root logger. This hooks up the logger to write to stdout, using either :class:`SimColourLogFormatter` or :class:`SimLogFormatter` depending on whether colored output is requested. It also adds a :class:`SimTimeContextFilter` filter so that :attr:`~logging.LogRecord.created_sim_time` is available to the formatter. The logging level for cocotb logs is set based on the :envvar:`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 :ref:`rotating-logger`. .. versionadded:: 1.4 """ # construct an appropriate handler hdlr = logging.StreamHandler(sys.stdout) hdlr.addFilter(SimTimeContextFilter()) if want_color_output(): hdlr.setFormatter(SimColourLogFormatter()) else: hdlr.setFormatter(SimLogFormatter()) logging.setLoggerClass(SimBaseLog) # For backwards compatibility logging.basicConfig() logging.getLogger().handlers = [hdlr] # overwrite default handlers # apply level settings for cocotb log = logging.getLogger("cocotb") try: # All log levels are upper case, convert the user input for convenience. level = os.environ["COCOTB_LOG_LEVEL"].upper() except KeyError: level = _COCOTB_LOG_LEVEL_DEFAULT try: log.setLevel(level) except ValueError: valid_levels = ("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "TRACE") raise ValueError( "Invalid log level %r passed through the " "COCOTB_LOG_LEVEL environment variable. Valid log " "levels: %s" % (level, ", ".join(valid_levels)) ) # Notify GPI of log level, which it uses as an optimization to avoid # calling into Python. logging.getLogger("gpi").setLevel(level)
()
29,625
cocotb._deprecation
deprecated
Emits a DeprecationWarning when the decorated function is called. This decorator works on normal functions, methods, and properties. Usage on properties requires the ``@property`` decorator to appear outside the ``@deprecated`` decorator. Concrete classes can be deprecated by decorating their ``__init__`` or ``__new__`` method. Args: msg: the deprecation message category: the warning class to use
def deprecated( msg: str, category: Type[Warning] = DeprecationWarning ) -> Callable[[AnyCallableT], AnyCallableT]: """Emits a DeprecationWarning when the decorated function is called. This decorator works on normal functions, methods, and properties. Usage on properties requires the ``@property`` decorator to appear outside the ``@deprecated`` decorator. Concrete classes can be deprecated by decorating their ``__init__`` or ``__new__`` method. Args: msg: the deprecation message category: the warning class to use """ def decorator(f: AnyCallableT) -> AnyCallableT: @functools.wraps(f) def wrapper(*args: Any, **kwargs: Any) -> Any: warnings.warn(msg, category=category, stacklevel=2) return f(*args, **kwargs) return wrapper return decorator
(msg: str, category: Type[Warning] = <class 'DeprecationWarning'>) -> Callable[[~AnyCallableT], ~AnyCallableT]
29,626
cocotb.decorators
external
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 external: """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. """ def __init__(self, func): self._func = func self._log = SimLog(f"cocotb.external.{self._func.__qualname__}.{id(self)}") def __call__(self, *args, **kwargs): return cocotb.scheduler._run_in_executor(self._func, *args, **kwargs) def __get__(self, obj, owner=None): """Permit the decorator to be used on class methods and standalone functions""" return type(self)(self._func.__get__(obj, owner))
(func)
29,627
cocotb.decorators
__call__
null
def __call__(self, *args, **kwargs): return cocotb.scheduler._run_in_executor(self._func, *args, **kwargs)
(self, *args, **kwargs)
29,629
cocotb.decorators
__init__
null
def __init__(self, func): self._func = func self._log = SimLog(f"cocotb.external.{self._func.__qualname__}.{id(self)}")
(self, func)
29,630
cocotb
fork
Schedule a coroutine to be run concurrently. See :ref:`coroutines` for details on its use. .. deprecated:: 1.7.0 This function has been deprecated in favor of :func:`cocotb.start_soon` and :func:`cocotb.start`. In most cases you can simply substitute ``cocotb.fork`` with ``cocotb.start_soon``. For more information on when to use ``start_soon`` vs ``start`` see :ref:`coroutines`.
def fork(coro: Union[Task, Coroutine]) -> Task: """ Schedule a coroutine to be run concurrently. See :ref:`coroutines` for details on its use. .. deprecated:: 1.7.0 This function has been deprecated in favor of :func:`cocotb.start_soon` and :func:`cocotb.start`. In most cases you can simply substitute ``cocotb.fork`` with ``cocotb.start_soon``. For more information on when to use ``start_soon`` vs ``start`` see :ref:`coroutines`. """ warnings.warn( "cocotb.fork has been deprecated in favor of cocotb.start_soon and cocotb.start.\n" "In most cases you can simply substitute cocotb.fork with cocotb.start_soon.\n" "For more information about when you would want to use cocotb.start see the docs,\n" "https://docs.cocotb.org/en/latest/coroutines.html#concurrent-execution", DeprecationWarning, stacklevel=2, ) return scheduler._add(coro)
(coro: Union[cocotb.task.Task, collections.abc.Coroutine]) -> cocotb.task.Task
29,631
cocotb.decorators
function
Decorator class that allows a function to block. This allows a coroutine that consumes simulation time to be called by a thread started with :class:`cocotb.external`; in other words, to internally block while externally appear to yield.
class function: """Decorator class that allows a function to block. This allows a coroutine that consumes simulation time to be called by a thread started with :class:`cocotb.external`; in other words, to internally block while externally appear to yield. """ def __init__(self, func): self._coro = cocotb.coroutine(func) @lazy_property def log(self): return SimLog(f"cocotb.function.{self._coro.__qualname__}.{id(self)}") def __call__(self, *args, **kwargs): return cocotb.scheduler._queue_function(self._coro(*args, **kwargs)) def __get__(self, obj, owner=None): """Permit the decorator to be used on class methods and standalone functions""" return type(self)(self._coro._func.__get__(obj, owner))
(func)
29,632
cocotb.decorators
__call__
null
def __call__(self, *args, **kwargs): return cocotb.scheduler._queue_function(self._coro(*args, **kwargs))
(self, *args, **kwargs)
29,633
cocotb.decorators
__get__
Permit the decorator to be used on class methods and standalone functions
def __get__(self, obj, owner=None): """Permit the decorator to be used on class methods and standalone functions""" return type(self)(self._coro._func.__get__(obj, owner))
(self, obj, owner=None)
29,634
cocotb.decorators
__init__
null
def __init__(self, func): self._coro = cocotb.coroutine(func)
(self, func)
29,638
cocotb
mem_debug
null
def mem_debug(port): import cocotb.memdebug cocotb.memdebug.start(port)
(port)
29,641
cocotb
process_plusargs
null
# Copyright (c) 2013 Potential Ventures Ltd # Copyright (c) 2013 SolarFlare Communications Inc # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of Potential Ventures Ltd, # SolarFlare Communications Inc nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL POTENTIAL VENTURES LTD BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ 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 typing import Dict, List, Optional, Union import cocotb.handle from cocotb._deprecation import deprecated 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__ # Things we want in the cocotb namespace from cocotb.decorators import ( # isort: skip # noqa: F401 coroutine, external, function, test, ) from cocotb.log import _filter_from_c, _log_from_c # isort: skip # noqa: F401 def _setup_logging() -> None: default_config() global log log = logging.getLogger(__name__)
() -> NoneType
29,646
cocotb
start
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
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)
(coro: Union[cocotb.task.Task, collections.abc.Coroutine]) -> cocotb.task.Task