【问题标题】:Import error running unittest in Python3在 Python3 中导入错误运行 unittest
【发布时间】: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


【解决方案1】:

我对 Python 中的导入以及 python 如何处理模块感到困惑。

project/
    module/
        __init__.py
        a.py
        b.py
    test/
        test_a.py
        test_b.py
    main.py

这是我的新目录树。文件包含:

main.py:

from module.b import Something

b.py:

from .a import Something

a.py:

from unittest import TestCase
from module.a import Something

test_b.py:

from unittest import TestCase
from module.a import Something
from module.b import Something

像这样,它工作正常,应用和测试。

【讨论】:

  • 结构为什么要这样?
  • 我想你想说的是:'In test_a.py' 而不是 'In a.py'。
  • 同样重要的是要提到“模块”必须安装在站点包中。否则,您必须将其添加到 sys.path。
【解决方案2】:

恕我直言,Python 是一种用户友好且直观的语言,它的导入系统是我见过的最不友好的语言之一。

虽然可能很丑,但我通常会做类似 (python 3.6+) 之类的事情:

try:
    from a import class_defined_in_a_py
except (ModuleNotFoundError, ImportError):
    from .a import class_defined_in_a_py

第一个导入适用于应用程序,第二个适用于测试。

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 1970-01-01
    • 2014-04-07
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多