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

如何从tests目录导入模块目录?pytest项目导入问题求助

pytest测试模块导入问题解决方案

方案1:修正sys.path配置

你当前sys.path.append("../example/")的写法错误,应该把项目根目录添加到Python路径里,这样才能识别example包。修改test_1.py如下:

import sys
import os
# 把项目根目录添加到路径,避免相对路径坑
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# 从example包的example模块导入test类
from example.example import test

# 注意:test是类,必须实例化才能用
test_obj = test()
print(test_obj.a, test_obj.b)

方案2:用相对导入(需按包运行)

想用相对导入的话,不能直接单独运行test_1.py,得从项目根目录以包的方式启动pytest。
先改test_1.py:

# 相对导入example包下的example模块里的test类
from ..example.example import test

test_obj = test()
print(test_obj.a, test_obj.b)

然后在project目录下执行命令:

python -m pytest tests/test_1.py -v

方案3:修正setup.py配置(推荐)

执行python setup.py develop后能导入包但找不到方法,大概率是setup.py没正确配置包,或者__init__.py没导出类。

  1. 调整setup.py里的包配置:
    找到setup函数中的packages参数,改成:
packages=find_packages(exclude=["tests*"]),

这会自动识别项目里的example包。
2. 可选优化:在example/__init__.py里添加导出,方便后续导入:

from .example import test

之后重新执行:

python setup.py develop

这时test_1.py可以直接这么写:

from example import test

test_obj = test()
print(test_obj.a, test_obj.b)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:11:11