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

Python 如何在测试中导入已测试的模块?,python,unit-testing,python-import,Python,Unit Testing,Python Import,我是Python新手,来自Java背景 假设我正在使用包hello开发一个Python项目: hello_python/ hello/ hello.py __init__.py test/ test_hello1.py test_hello2.py 我相信项目结构是正确的 假设hello.py包含我想在测试中使用的函数do\u hello()。如何在teststest\u hello 1.py和test\u hello 2.py中导入do\u hello

我是Python新手,来自Java背景

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

hello_python/
  hello/
    hello.py
    __init__.py
  test/
    test_hello1.py
    test_hello2.py
我相信项目结构是正确的


假设
hello.py
包含我想在测试中使用的函数
do\u hello()。如何在tests
test\u hello 1.py
test\u hello 2.py
中导入
do\u hello

这里有两个小问题。首先,您从错误的目录运行了test命令,其次,您的项目结构不太正确

通常,在开发python项目时,我会尽量将所有内容都集中在项目的根上,在您的例子中,这就是
hello\u 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()
hello_python/
  hello/
    hello.py
    __init__.py
  test/
    __init__.py    #  <= This is what you were missing
    test_hello1.py
    test_hello2.py
其次,
test
现在不是一个模块,因为您错过了该目录中的
\uuuu init\uuuuuuuuuuuuy.py
。您应该具有如下所示的层次结构:

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()
hello_python/
  hello/
    hello.py
    __init__.py
  test/
    __init__.py    #  <= This is what you were missing
    test_hello1.py
    test_hello2.py
hello\u python/
你好/
你好,派伊
__初始值
试验/

__在测试中导入init___; py#与在任何其他代码中导入没有什么不同。在您的情况下,您可以从hello.hello导入do\u hello
。谢谢。我得到了它。现在测试在
PyCharm
中正常运行。但是,当我在当前目录下的命令行
python-m unittest test\u hello\u server
中运行测试时,我得到了
ImportError:没有名为hello\u server.hello\u server的模块。因为父目录不在pythonpath上。相反,您应该从内部
hello\u python
开始,然后执行
python-m unittest test.test\u hello
或其他任何操作。现在就尝试吧。Got
AttributeError:'module'对象没有属性“test\u hello”
刚刚注意到您使用
-m
开关运行
python
。现在对我有用了!非常感谢。你的例子有一个小问题。当我执行单元测试时,没有测试实际运行,因为测试方法
hello\u test
不是以
test
开头的。
TestCase
的实例只运行方法
test.*
作为它们的常规测试。@Michael哇!我用手抄写而不是复制粘贴,这对我来说是很好的。