【发布时间】:2017-06-01 18:55:22
【问题描述】:
我在 Python 3.6 中导入文件时遇到问题。我的目录树如下:
project/
app/
├── __init__.py
├── a.py
└── b.py
test/
├── __init__.py
├── test_a.py
└── test_b.py
使用b.py 中的以下导入语句,它适用于我的应用程序(但测试无效):
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 中的导入语句如下所示:
from unittest import TestCase
from app.cell import *
有没有办法解决这个问题?
【问题讨论】:
-
你能把你的__init__.py的内容贴出来吗?
-
我觉得分享repository对你来说更容易。在那里你可以看到所有信息,因为在这篇文章中我不会假装展示我的具体案例。
-
关于您的问题,
__init__.py是空的,就像我可以看到的许多示例一样。 -
psst,请查看
pytest,它类似于惯用的 Python,而不是重复使用 Java 模式,而且您很有可能会更喜欢它 -
是的,这更像 Pythonic,但包含 unittest,我不想导入更多库。
标签: python python-3.x python-unittest