Python 3.12中Aloe框架Examples表格失效问题求助
Python 3.12 下 Aloe 测试用例 Examples 表格执行失败的解决办法
问题情况
升级到Python 3.12后,Aloe测试用例无法正常运行,问题集中在Feature文件末尾的Examples表格:
- 带表头的Examples表格会直接触发报错
- 删掉Examples表头,将表格直接插入对应步骤后即可正常执行
- 错误提示为ERROR: Failure: ValueError (AST node line range (7, 3) is not valid),指向Examples表格的第一行数据
已尝试但无效的操作:
- 在虚拟环境/非虚拟环境中运行测试
- 简化Examples表格的结构
错误详情
完整错误栈信息:
====================================================================== ERROR: Failure: ValueError (AST node line range (7, 3) is not valid) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/bhuang/aloe_testing/lib/python3.12/site-packages/nose/failure.py", line 35, in runTest raise self.exc_val.with_traceback(self.tb) File "/home/bhuang/aloe_testing/lib/python3.12/site-packages/nose/plugins/manager.py", line 124, in generate for r in result: File "/home/bhuang/aloe_testing/lib/python3.12/site-packages/aloe/plugin.py", line 190, in loadTestsFromFile test = self.test_class.from_file(file_) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/bhuang/aloe_testing/lib/python3.12/site-packages/aloe/testclass.py", line 175, in from_file for example in cls.make_examples(scenario, i + 1): File "/home/bhuang/aloe_testing/lib/python3.12/site-packages/aloe/testclass.py", line 265, in make_examples make_function( File "/home/bhuang/aloe_testing/lib/python3.12/site-packages/aloe/codegen.py", line 42, in make_function code = compile(func, source_file, 'exec') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: AST node line range (7, 3) is not valid ---------------------------------------------------------------------- Ran 1 test in 0.001s FAILED (errors=1)
示例代码
Feature 文件
Feature: Test a step using some form of automation Scenario Outline: Given a sample, it will start and complete the step. Given I have a sample <s_name> Examples: |s_name| |S123 |
Step 定义文件
@step('Given I have a sample (\w+)') def test_add_sample(step, s_name): print(s_name) # 代码根本没走到这一步,问题出在Examples编译阶段
原因和解决办法
原因
Python 3.12 对AST(抽象语法树)节点的行范围校验做了严格升级,旧版本的Aloe在动态生成测试代码时,错误生成了起始行号大于结束行号的AST节点(比如错误中的(7,3)),触发了Python的新校验规则,导致编译失败。
解决办法
- 升级Aloe到兼容版本:这是最稳妥的方案,目前Aloe 0.12.0及以上版本已修复该Python 3.12兼容问题,执行以下命令升级:
pip install --upgrade aloe - 临时修改源码(不推荐长期使用):如果暂时无法升级,可以找到虚拟环境中的
aloe/codegen.py文件,修改make_function函数,确保动态生成的代码行号逻辑正确,避免出现起始行号大于结束行号的情况;或者暂时注释掉行号绑定逻辑(但会影响错误定位的准确性)。
内容的提问来源于stack exchange,提问作者Barb
相关产品推荐
相关产品推荐

