You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

配置Pytest跨多目录查找AWS Lambda测试用例

解决pytest多栈目录下测试模块命名空间冲突问题

问题分析

核心矛盾是多个CloudFormation栈目录下的tests模块命名重复,在项目根目录执行pytest时,Python模块导入系统无法区分不同栈的测试模块,进而触发ModuleNotFoundError。单个栈运行测试正常,是因为此时仅该栈目录被加入Python路径,不存在命名冲突。

解决方案

以下两种方案无需修改现有目录结构,可实现根目录执行pytest运行所有测试:

方案1:修改pytest导入模式为append

在项目根目录的pytest.ini中添加import_mode = append配置,让pytest将每个测试文件所在的栈目录追加到Python路径末尾(而非默认的前置),确保每个测试模块优先使用自身所在栈目录下的模块,避免命名冲突。

修改后的pytest.ini内容:

[pytest]
testpaths = stack1 stack2
import_mode = append

方案2:通过conftest.py动态添加栈目录到Python路径

在项目根目录的conftest.py中添加代码,自动识别所有栈目录并将其加入Python路径,保证每个栈的src和tests模块都能被正确识别。

修改后的conftest.py内容:

import sys
from pathlib import Path

# 获取项目根目录下所有栈目录(可根据实际栈命名规则调整筛选逻辑)
root_dir = Path(__file__).parent
stack_dirs = [d for d in root_dir.iterdir() if d.is_dir() and d.name.startswith("stack")]

# 将每个栈目录加入Python路径
for dir_path in stack_dirs:
    sys.path.append(str(dir_path))

同时保持pytest.ini的testpaths配置:

[pytest]
testpaths = stack1/tests stack2/tests

验证

完成上述配置后,在项目根目录执行pytest,所有栈的测试用例应能被正确发现并执行,不会再出现模块找不到的错误。

内容的提问来源于stack exchange,提问作者RyWilliamson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 04:00:09