我是 Python 新手,有 Java 背景。
假设我正在开发一个带有包 hello
的 Python 项目:
hello_python/
hello/
hello.py
__init__.py
test/
test_hello1.py
test_hello2.py
我相信项目结构是正确的。
假设 hello.py
包含我想在测试中使用的函数 do_hello()
。如何在测试test_hello1.py
和test_hello2.py
中导入do_hello
?
最佳答案
您这里有 2 个小问题。首先,您从错误的目录运行测试命令,其次,您没有完全正确地构建项目。
通常,当我开发 python 项目时,我会尝试将所有内容都集中在项目的根目录上,在您的情况下,该根目录是 hello_python/
。默认情况下,Python 在其加载路径上具有当前工作目录,因此如果您有这样的项目:
hello_python/
hello/
hello.py
__init__.py
test/
test_hello1.py
test_hello2.py
# hello/hello.py
def do_hello():
return 'hello'
# test/test_hello.py
import unittest2
from hello.hello import do_hello
class HelloTest(unittest2.TestCase):
def test_hello(self):
self.assertEqual(do_hello(), 'hello')
if __name__ == '__main__':
unittest2.main()
其次,test
现在不是一个模块,因为您错过了该目录中的__init__.py
。您应该有一个如下所示的层次结构:
hello_python/
hello/
hello.py
__init__.py
test/
__init__.py # <= This is what you were missing
test_hello1.py
test_hello2.py
当我在我的机器上尝试时,运行 python -m unittest test.hello_test
对我来说效果很好。
你可能会发现这还是有点麻烦。我强烈建议安装nose ,这将让您只需从项目的根目录调用 nosetests
即可自动查找并执行所有测试 - 前提是您拥有带有 __init__.py
的正确模块。
关于python - 如何在测试中导入被测试的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43920141/