在Python3中运行unittest时发生导入错误

2024-03-28 22:34:34 发布

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

在Python3.6中导入文件时遇到问题。我的目录树如下所示:

project/
    app/
    ├── __init__.py
    ├── a.py
    └── b.py
    test/
    ├── __init__.py
    ├── test_a.py
    └── test_b.py

它使用b.py中的以下import语句运行我的应用程序(但不运行测试):

from a import *

但是,它在b.py中使用另一个不工作(但可以工作测试):

from .a import *

所以,我选择from a import *。执行类似于python3 -m unittest的测试时,总是会出现以下错误:

E.
======================================================================
ERROR: tests.test_cell (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: tests.test_cell
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 428, in _find_test_path
    module = self._get_module_from_name(name)
  File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name
    __import__(name)
  File "/Users/serrodcal/Repositories/project/tests/test_b.py", line 2, in <module>
    from app.b import *
  File "/Users/serrodcal/Repositories/project/app/b.py", line 1, in <module>
    from a import *
ModuleNotFoundError: No module named 'a'


----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (errors=1)

在这种情况下,我在test_b.py中的import语句如下所示:

from unittest import TestCase
from app.cell import *

有什么办法解决这个问题吗?


Tags: nameinfrompytestimportprojectapp