py_canoe.core.configuration.Configuration

The Configuration object represents the active configuration.

Source code in src\py_canoe\core\configuration.py
50
51
52
53
54
55
56
57
58
59
def __init__(self, app: 'Application'):
    self.app = app
    self.com_object = win32com.client.Dispatch(self.app.com_object.Configuration)
    # self.configuration_events: ConfigurationEvents = win32com.client.WithEvents(self.com_object, ConfigurationEvents)
    self.configuration_test_configurations = lambda: self.test_configurations
    self.configuration_test_setup = lambda: self.test_setup
    self.__test_setup_environments = self.configuration_test_setup().test_environments.fetch_all_test_environments()
    self.__test_configurations = self.configuration_test_configurations().fetch_all_test_configurations()
    self.__test_modules = list()
    self.__test_units = list()

c_libraries property

Return collection of C Libraries Object

comment property

Return configuration comment.

add_database(database_file, network)

Add a database file to the specified channel/network

Parameters:
  • database_file (str) –

    Path to the database file

  • network (str | int) –

    Network name or channel number

Returns:
  • bool( bool ) –

    True for success, False for failure

Source code in src\py_canoe\core\configuration.py
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
def add_database(self, database_file: str, network: str | int) -> bool:
    """
    Add a database file to the specified channel/network

    Args:
        database_file (str): Path to the database file
        network (str | int): Network name or channel number

    Returns:
        bool: True for success, False for failure
    """
    try:
        if self.app.measurement.running:
            logger.warning("Cannot add database while measurement is running. Please stop the measurement first.")
            return False
        else:
            # Determine whether it is a network name or a channel number
            if isinstance(network, str):
                # Get the channel number based on the network name
                for bus in self.simulation_setup.buses.item():
                    bus: Bus
                    bus_name = getattr(bus, 'name', '')
                    if bus_name == network:
                        try:
                            bus.databases.add(database_file)
                        except AttributeError:
                            return self._add_database_to_channel(database_file, 1)
                        logger.info(f'Database "{database_file}" added successfully to network "{network}".')
                        return True
                logger.warning(f'Network "{network}" not found. Cannot add database.')
                return False
            elif isinstance(network, int):
                for bus in self.simulation_setup.buses.item():
                    bus: Bus
                    channels = bus.channels.item()
                    logger.info(f"Checking bus channels: {[channel.number for channel in channels]}")
                    if not channels:
                        return self._add_database_to_channel(database_file, network)
                    for channel in channels:
                        channel: Channel
                        if channel.number == network:
                            return self._add_database_to_channel(database_file, network)
                return self._add_database_to_channel(database_file, network)
            else:
                logger.warning(f'Invalid network type: {type(network)}. Must be str (network name) or int (channel number).')
                return False
    except Exception as e:
        import traceback
        traceback.print_exc()
        logger.error(f"Error adding database '{database_file}': {e}")
        return False

add_netWork(network_name, network_type=BusType.CAN, sw_channel=1)

Adds a new network to the configuration.

Parameters:
  • network_name (str) –

    Name of the new network.

  • network_type (BusType, default: CAN ) –

    Bus type. Defaults to BusType.CAN.

  • sw_channel (int, default: 1 ) –

    Software channel index (1-based) to assign. Defaults to 1.

Returns:
  • Bus

    The newly added :class:Bus, or None if a network with

  • Bus

    the same name already exists.

Source code in src\py_canoe\core\configuration.py
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def add_netWork(self, network_name: str, network_type: BusType = BusType.CAN,
                sw_channel: int = 1) -> Bus:
    """Adds a new network to the configuration.

    Args:
        network_name: Name of the new network.
        network_type: Bus type.  Defaults to ``BusType.CAN``.
        sw_channel: Software channel index (1-based) to assign.
            Defaults to 1.

    Returns:
        The newly added :class:`Bus`, or *None* if a network with
        the same name already exists.
    """
    try:
        bus = self.simulation_setup.buses.add(network_name, network_type)
        if bus is None:
            logger.warning(f"Network {network_name} already exists.")
            return None
        # Assign the software channel if it differs from the default (CAN 1)
        if sw_channel != 1 and bus.channels.count > 0:
            bus.channels.remove(1)
        bus.channels.add(1, sw_channel)
        return bus
    except Exception as e:
        logger.error(f"Failed to add network '{network_name}': {e}")
        return None

fetch_test_modules()

Get all test modules from all test environments and store them in self.__test_modules.

Source code in src\py_canoe\core\configuration.py
61
62
63
64
65
66
67
def fetch_test_modules(self):
    """Get all test modules from all test environments and store them in self.__test_modules."""
    for te_name, te_inst in self.__test_setup_environments.items():
        for tm_name, tm_inst in te_inst.get_all_test_modules().items():
            # A TestSetupItem object that either can be a TestModule object or a TestSetupFolder object.
            # A TestSetupFolder has items that contain nested TestSetupItems.
            self.__test_modules.append({'name': tm_name, 'object': tm_inst, 'environment': te_name})

fetch_test_units()

Get all test units from all test configurations and store them in self.__test_units.

Source code in src\py_canoe\core\configuration.py
69
70
71
72
73
74
75
def fetch_test_units(self):
    """Get all test units from all test configurations and store them in self.__test_units."""
    for tc_name, tc_inst in self.__test_configurations.items():
        for tu_index in range(1, tc_inst.test_units.count + 1):
            tu_inst = tc_inst.test_units.item(tu_index)
            self.__test_units.append({'name': tu_inst.name, 'object': tu_inst, 'test_configuration': tc_name})
    return self.__test_units

get_compilation_result()

Get CAPL compilation result with error details.

Compiles all CAPL code in the current configuration and returns detailed result including success status and error information.

Returns:
  • dict( dict[str, object] ) –

    Dictionary with keys: - "success" (bool): True if compilation succeeded, False otherwise - "error" (str | None): Error message if compilation failed, None on success

Example

result = config.get_compilation_result() if result["success"]: ... print("Compilation OK") ... else: ... print(f"Compilation failed: {result['error']}")

Source code in src\py_canoe\core\configuration.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def get_compilation_result(self) -> dict[str, object]:
    """Get CAPL compilation result with error details.

    Compiles all CAPL code in the current configuration and returns
    detailed result including success status and error information.

    Returns:
        dict: Dictionary with keys:
            - "success" (bool): True if compilation succeeded, False otherwise
            - "error" (str | None): Error message if compilation failed, None on success

    Example:
        >>> result = config.get_compilation_result()
        >>> if result["success"]:
        ...     print("Compilation OK")
        ... else:
        ...     print(f"Compilation failed: {result['error']}")
    """
    result = self._compile_and_verify_internal()
    if result["success"]:
        logger.info('CAPL compilation succeeded')
    else:
        logger.warning(f'CAPL compilation failed: {result["error"]}')
    return result

get_test_module_result(test_module_name, report_timeout=30.0)

Get test module execution result including report path, test case verdicts, and aggregated statistics.

Should be called after execute_test_module() to retrieve the results.

Note: This method does NOT depend on the module's started state. It reads the verdict and report information directly from the test module object, and waits (up to report_timeout seconds) for the report-generated event if it has not fired yet. All returned data are plain Python objects (snapshots), not live COM objects, so they remain valid after the CANoe session ends.

Parameters:
  • test_module_name (str) –

    name of the test module.

  • report_timeout (float, default: 30.0 ) –

    maximum time in seconds to wait for the report-generated event before giving up. Defaults to 30.0.

Returns:
  • dict( dict ) –

    A dictionary with keys:

    • "test_module" (str): name of the test module
    • "verdict" (int): overall test module verdict (0-5)
    • "verdict_name" (str): human-readable verdict name
    • "report" (dict): report information with keys:
      • "success" (bool): whether report generation succeeded
      • "source_full_name" (str): XML report path
      • "generated_full_name" (str): HTML report path
    • "test_cases" (list[dict]): list of test case snapshots, each with keys: name, title, enabled, verdict, verdict_name
    • "total" (int): total number of test cases
    • "passed" (int): number of passed test cases
    • "failed" (int): number of failed test cases
    • "other" (int): number of test cases with other verdicts (NotAvailable, None, Inconclusive, ErrorInTestSystem)
    • "pass_rate" (float): pass rate as a percentage (0.0-100.0), 0.0 when there are no test cases
Example

result = cfg.get_test_module_result("MyModule") print(f"Module: {result['test_module']}") print(f"Verdict: {result['verdict_name']}") print(f"Pass rate: {result['pass_rate']:.1f}%") print(f"Passed: {result['passed']}/{result['total']}") print(f"Report: {result['report']['generated_full_name']}") for tc in result['test_cases']: ... print(f" {tc['name']}: {tc['verdict_name']}")

Source code in src\py_canoe\core\configuration.py
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
def get_test_module_result(self, test_module_name: str, report_timeout: float = 30.0) -> dict:
    """Get test module execution result including report path, test case
    verdicts, and aggregated statistics.

    Should be called after execute_test_module() to retrieve the results.

    Note: This method does NOT depend on the module's started state. It reads
    the verdict and report information directly from the test module object,
    and waits (up to ``report_timeout`` seconds) for the report-generated
    event if it has not fired yet. All returned data are plain Python objects
    (snapshots), not live COM objects, so they remain valid after the CANoe
    session ends.

    Args:
        test_module_name (str): name of the test module.
        report_timeout (float): maximum time in seconds to wait for the
            report-generated event before giving up. Defaults to 30.0.

    Returns:
        dict: A dictionary with keys:

            - "test_module" (str): name of the test module
            - "verdict" (int): overall test module verdict (0-5)
            - "verdict_name" (str): human-readable verdict name
            - "report" (dict): report information with keys:
                - "success" (bool): whether report generation succeeded
                - "source_full_name" (str): XML report path
                - "generated_full_name" (str): HTML report path
            - "test_cases" (list[dict]): list of test case snapshots, each
              with keys: name, title, enabled, verdict, verdict_name
            - "total" (int): total number of test cases
            - "passed" (int): number of passed test cases
            - "failed" (int): number of failed test cases
            - "other" (int): number of test cases with other verdicts
              (NotAvailable, None, Inconclusive, ErrorInTestSystem)
            - "pass_rate" (float): pass rate as a percentage (0.0-100.0),
              0.0 when there are no test cases

    Example:
        >>> result = cfg.get_test_module_result("MyModule")
        >>> print(f"Module: {result['test_module']}")
        >>> print(f"Verdict: {result['verdict_name']}")
        >>> print(f"Pass rate: {result['pass_rate']:.1f}%")
        >>> print(f"Passed: {result['passed']}/{result['total']}")
        >>> print(f"Report: {result['report']['generated_full_name']}")
        >>> for tc in result['test_cases']:
        ...     print(f"  {tc['name']}: {tc['verdict_name']}")
    """
    try:
        tm_obj = self._find_test_module(test_module_name)
        if tm_obj is None:
            return {}

        # Wait for the report-generated event (bounded by report_timeout) so
        # the report paths are populated. If it already fired, this returns
        # immediately. We do NOT gate on TM_STARTED, because the module may
        # have been stopped (which resets TM_STARTED) by the time results
        # are requested. Use a monotonic clock so the wait is not
        # skewed by GIL/thread scheduling.
        deadline = time.monotonic() + report_timeout
        while not tm_obj.test_module_events.TM_REPORT_GENERATED and time.monotonic() < deadline:
            wait(0.01)
        if not tm_obj.test_module_events.TM_REPORT_GENERATED:
            logger.warning(
                f'Test module "{test_module_name}" report was not generated '
                f'within {report_timeout}s; report paths may be empty.'
            )

        # overall verdict
        verdict = tm_obj.verdict
        verdict_name = tm_obj.VALUE_TABLE_VERDICT.get(verdict, "Unknown")

        # report information from event sink
        report_info = tm_obj.test_module_events.TEST_REPORT_INFORMATION
        report = {
            "success": report_info.get("success", False),
            "source_full_name": report_info.get("source_full_name", ""),
            "generated_full_name": report_info.get("generated_full_name", ""),
        }

        # Convert live COM objects to plain dicts so the data survives
        # after the CANoe session ends and COM objects become invalid.
        raw_cases = tm_obj.get_all_test_cases()
        test_cases = [tc.to_dict() for tc in raw_cases.values()]

        # Aggregate statistics
        total = len(test_cases)
        passed = sum(1 for tc in test_cases if tc["verdict"] == 1)
        failed = sum(1 for tc in test_cases if tc["verdict"] == 2)
        other = total - passed - failed
        pass_rate = (passed / total * 100.0) if total > 0 else 0.0

        return {
            "test_module": test_module_name,
            "verdict": verdict,
            "verdict_name": verdict_name,
            "report": report,
            "test_cases": test_cases,
            "total": total,
            "passed": passed,
            "failed": failed,
            "other": other,
            "pass_rate": pass_rate,
        }

    except Exception as e:
        logger.error(f'failed to get test module result for "{test_module_name}": {e}')
        return {}

remove_all_networks()

Remove ALL networks from the simulation setup.

CANoe requires at least one bus, so this will leave one bus remaining. Returns the number of networks actually removed.

Source code in src\py_canoe\core\configuration.py
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
def remove_all_networks(self) -> int:
    """Remove ALL networks from the simulation setup.

    CANoe requires at least one bus, so this will leave one bus
    remaining.  Returns the number of networks actually removed.
    """
    count = 0
    names = []
    for bus in self.simulation_setup.buses.item():
        names.append(bus.name)
    # Skip the last one — CANoe requires at least one bus
    for name in names[:-1]:
        if self.remove_netWork(name):
            count += 1
    logger.info(f"Removed {count} network(s).")
    return count

remove_netWork(name)

Remove a network by name.

Parameters:
  • name (str) –

    Network name to remove.

Returns:
  • bool

    True if found and removed.

Source code in src\py_canoe\core\configuration.py
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
def remove_netWork(self, name: str) -> bool:
    """Remove a network by name.

    Args:
        name: Network name to remove.

    Returns:
        True if found and removed.
    """
    try:
        self.simulation_setup.buses.remove(name=name)
        logger.info(f"Network '{name}' removed.")
        return True
    except Exception as e:
        logger.error(f"Failed to remove network '{name}': {e}")
        return False

run_compilation()

Run CAPL compilation and return success status.

Compiles all CAPL code in the current configuration. Use get_compilation_result() if you need error details.

Returns:
  • bool( bool ) –

    True if compilation succeeded, False otherwise

Example

if config.run_compilation(): ... print("Compilation OK")

Source code in src\py_canoe\core\configuration.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def run_compilation(self) -> bool:
    """Run CAPL compilation and return success status.

    Compiles all CAPL code in the current configuration.
    Use get_compilation_result() if you need error details.

    Returns:
        bool: True if compilation succeeded, False otherwise

    Example:
        >>> if config.run_compilation():
        ...     print("Compilation OK")
    """
    result = self._compile_and_verify_internal()
    if result["success"]:
        logger.info('CAPL compilation passed')
    else:
        logger.warning(f'CAPL compilation failed: {result["error"]}')
    return result["success"]