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

2024-04-27 02:31:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,来自Java背景。你知道吗

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

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?你知道吗


Tags: 项目函数pytesthelloinitjava结构
1条回答
网友
1楼 · 发布于 2024-04-27 02:31:56

你有两个小问题。首先,您从错误的目录运行test命令,其次,您还没有完全正确地构建项目。你知道吗

通常,当我在开发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

相关问题 更多 >