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

如何测试开发中的Python包?以自定义indent包为例

解决Python src/结构包的测试导入问题

问题根源

你的ModuleNotFoundError本质是Python解释器在默认路径里找不到src/indent包——因为src目录不在Python的sys.path搜索路径里,不管是直接跑测试文件还是用unittest discover,默认都只会把测试文件所在的tests目录加入路径。

三种可行的解决方法

1. 临时给测试文件添加src路径

在test_indent.py的最开头加入以下代码,手动把项目根目录下的src路径加入Python搜索路径:

import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))

之后再正常导入indent模块即可。这种方式适合快速验证测试逻辑,不用改环境或安装包。

2. 用pip安装可编辑模式(推荐长期开发用)

在项目根目录执行以下命令,把你的indent包以可编辑模式安装到Python环境:

pip install -e .

这会在Python的site-packages里创建一个指向你本地src/indent的链接,之后不管你是直接跑测试文件、用unittest discover还是用其他测试框架,都能直接导入indent模块,完全不用处理路径问题。

3. 给unittest discover指定根目录

如果你不想修改测试文件也不想安装包,运行unittest discover时可以加-t参数指定项目根目录,让unittest自动识别src里的包:

python -m unittest discover -s tests -t .
  • -s tests指定测试目录为tests
  • -t .指定项目根目录为当前目录,这样unittest会从根目录开始搜索包

测试文件编写规范示例

确保你的test_indent.py符合unittest的标准结构:

import unittest
from indent import add_indent  # 假设你的包有add_indent函数

class TestIndentFunctions(unittest.TestCase):
    def test_add_indent_single_line(self):
        self.assertEqual(add_indent("test", 2), "  test")
    
    def test_add_indent_empty_string(self):
        self.assertEqual(add_indent("", 4), "    ")

if __name__ == '__main__':
    unittest.main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 03:35:27