首页 > 解决方案 > CANoe:如何使用 CANoe COM 接口从 Python 的 XML 测试模块中选择和启动测试用例?

问题描述


目前我能够:

如何访问加载了测试设置 (tse) 文件的 XML 测试模块并选择要执行的测试?

标签: pythonwindowscomcanoe

解决方案


代码段中的最后一行很可能是导致问题的原因。我一直在尝试解决这个问题很长一段时间,终于找到了解决方案。

不知何故,当你执行该行self.test_setup.TestEnvironments.Item(1)

win32com 创建一个类型的对象,TestSetupItem它没有访问测试用例所需的属性或方法。相反,我们想要访问集合类型的对象TestSetupFoldersTestModules. TestSetupItem即使我在测试环境中有一个 XML 测试模块(称为 AutomationTestSeq),win32com 也会创建类型对象,如您在此处看到的

我找到了三种可能的解决方案。


  1. 在每次运行之前手动清除生成的缓存。

使用win32com.client.DispatchWithEventswin32com.client.gencache.EnsureDispatch生成一堆描述 CANoe 对象模型的 python 文件。

如果您之前使用过其中任何一个,TestEnvironments.Item(1)将始终返回TestSetupItem而不是更合适的类型对象。

要删除缓存,您需要删除该C:\Users\{username}\AppData\Local\Temp\gen_py\{python version}文件夹。

每次都这样做当然不是很实用。


  1. 强制 win32com 始终使用动态调度。您可以使用以下方法执行此操作:

canoe = win32com.client.dynamic.Dispatch("CANoe.Application") 从现在开始使用创建的任何对象都canoe将被动态调度。

强制动态调度比每次手动清除缓存文件夹更容易。这总是给了我很好的结果。但是这样做不会让您对对象有任何洞察力。您将无法看到对象的可接受属性和方法。


  1. 类型转换TestSetupItemTestSetupFoldersor TestModules

这有一个风险,如果你不正确地进行类型转换,你会得到意想不到的结果。但到目前为止对我来说效果很好。简而言之:win32.CastTo(test_env, "ITestEnvironment2")。这将确保您按照 CANoe 技术参考使用推荐的对象层次结构。

请注意,您还必须进行类型转换TestSequenceItem才能TestCase访问测试用例判断和启用/禁用测试用例。

下面是一个不错的示例脚本。

"""Execute XML Test Cases without a pass verdict"""
import sys
from time import sleep
import win32com.client as win32

CANoe = win32.DispatchWithEvents("CANoe.Application")
CANoe.Open("canoe.cfg")

test_env = CANoe.Configuration.TestSetup.TestEnvironments.Item('Test Environment')

# Cast required since test_env is originally of type <ITestEnvironment>
test_env = win32.CastTo(test_env, "ITestEnvironment2")
# Get the XML TestModule (type <TSTestModule>) in the test setup
test_module = test_env.TestModules.Item('AutomationTestSeq')

# {.Sequence} property returns a collection of <TestCases> or <TestGroup>
# or <TestSequenceItem> which is more generic
seq = test_module.Sequence
for i in range(1, seq.Count+1):
    # Cast from <ITestSequenceItem> to <ITestCase> to access {.Verdict}
    # and the {.Enabled} property
    tc = win32.CastTo(seq.Item(i), "ITestCase")
    if tc.Verdict != 1: # Verdict 1 is pass
        tc.Enabled = True
        print(f"Enabling Test Case {tc.Ident} with verdict {tc.Verdict}")
    else:
        tc.Enabled = False
        print(f"Disabling Test Case {tc.Ident} since it has already passed")


CANoe.Measurement.Start()
sleep(5)   # Sleep because measurement start is not instantaneous
test_module.Start()
sleep(1)

推荐阅读