gpt4 book ai didi

python unittest导入类子目录

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:37 26 4
gpt4 key购买 nike

我有一个结构如下的项目:

|tools/
|-- test/
| |-- __init__.py
| |-- test_class1.py
| |-- test_class2.py
|
|-- tools/
|-- __init__.py
| |-- class1.py
| |-- class2.py
|
|-- test_runner (Python script that calls unittest.TestLoader().discover('test'))
|-- README.md

我想运行 test_runner 并让它执行 test 文件夹中的所有测试。我的个人测试会有这样一行:from test_class import TestClass 来测试适当的类。

test_runner 看起来像这样:

#!/usr/bin/env python

import unittest
import sys
import os
sys.path.append(os.path.realpath(__file__) + '/tools')

suite = unittest.TestLoader().discover('test')
results = unittest.TextTestRunner(verbosity=2).run(suite)
if len(results.errors) > 0 or len(results.failures) > 0:
sys.exit(1)
sys.exit()

现在这不起作用,我的测试文件无法导入它们相应的类。如果我执行 export PYTHONPATH=/path/to/file 我可以让它工作,但我想通过脚本让它工作。

我也试过 sys.path.insert(0, os.path.dirname(__file__) + '/tools') 但这不起作用,因为 file当我使用 sys.path.insert 时不返回任何内容。

最佳答案

只要确保您使用绝对导入,通过指定您的包名称(在您的情况下为“工具”)。您根本不必修改系统路径。

例如,使用此项目结构并运行 main.py:

project
main.py
package1
__init__.py
module1.py
package2
__init__.py
module2.py

在module1.py中,你应该使用

from package2 import module2

from package2.module2 import myclass

这是绝对重要的。无需修改系统路径

关于python unittest导入类子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19694626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com