如何在测试中导入测试模块?

How to import tested modules in tests?

我是 Python 的新人,来自 Java 背景。

假设我正在开发一个 Python 项目包 hello:

hello_python/
  hello/
    hello.py
    __init__.py
  test/
    test_hello1.py
    test_hello2.py

我相信项目结构是正确的。

假设 hello.py 包含我想在测试中使用的函数 do_hello()。如何在测试 test_hello1.pytest_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__.pys 的正确模块.