Python 单元测试无法解析导入语句
Python unittest failing to resolve import statements
我的文件结构如下所示
project
src
__init__.py
main.py
module.py
secondary.py
test
test_module.py
module.py
import secondary
x = False
secondary.py
pass
test_module.py
from unittest import TestCase
from src import module
class ModuleTest(TestCase):
def test_module(self):
self.assertTrue(module.x)
在/project/
中调用python3 -m unittest discover
会报错:
File "/Users/Me/Code/project/test/test_module.py", line 6, in <module>
from src import module
File "/Users/Me/Code/project/src/module.py", line 1, in <module>
import secondary
ImportError: No module named 'secondary'
我该怎么做才能正确导入 secondary.py
?
在 Python 3(以及 Python 2 和 from __future__ import absolute_import
中),当从同一个包中导入另一个模块时,您必须明确说明您想要什么模块。您在 module.py
(import secondary
) 中使用的语法仅在 secondary
是 Python 模块搜索路径中文件夹中的 top-level 模块时才有效。
要从您自己的包中明确请求相对导入,请改用 from . import secondary
。或者,进行绝对导入,使用包的名称以及模块(from src import secondary
,或 import src.secondary
并在模块的其他地方使用 src.secondary
而不仅仅是 secondary
) .
我的文件结构如下所示
project
src
__init__.py
main.py
module.py
secondary.py
test
test_module.py
module.py
import secondary
x = False
secondary.py
pass
test_module.py
from unittest import TestCase
from src import module
class ModuleTest(TestCase):
def test_module(self):
self.assertTrue(module.x)
在/project/
中调用python3 -m unittest discover
会报错:
File "/Users/Me/Code/project/test/test_module.py", line 6, in <module>
from src import module
File "/Users/Me/Code/project/src/module.py", line 1, in <module>
import secondary
ImportError: No module named 'secondary'
我该怎么做才能正确导入 secondary.py
?
在 Python 3(以及 Python 2 和 from __future__ import absolute_import
中),当从同一个包中导入另一个模块时,您必须明确说明您想要什么模块。您在 module.py
(import secondary
) 中使用的语法仅在 secondary
是 Python 模块搜索路径中文件夹中的 top-level 模块时才有效。
要从您自己的包中明确请求相对导入,请改用 from . import secondary
。或者,进行绝对导入,使用包的名称以及模块(from src import secondary
,或 import src.secondary
并在模块的其他地方使用 src.secondary
而不仅仅是 secondary
) .