簡體   English   中英

在 Python3 中導入錯誤運行 unittest

[英]Import error running unittest in Python3

我在 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 *

有沒有辦法解決這個問題?

我對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

像這樣,它工作正常,應用程序和測試。

恕我直言,Python 是一種用戶友好且直觀的語言,它的導入系統是我見過的最不友好的系統之一。

盡管可能很丑,但我通常會做類似(python 3.6+)的事情:

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

第一個導入適用於應用程序,第二個適用於測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM