Python Import Error - Run unittest

。_饼干妹妹 提交于 2019-12-11 02:49:26

问题


Why am I getting import error for a module I have in the project. All the packages are under the project, they all have __init __.py and other scripts do not give the same error. Python version is 3.6. Code was written in Unix environment.

Here is the import error I get. I am trying to run a test here.

Ran 1 test in 0.001s

FAILED (errors=1)

Error
Traceback (most recent call last):
  File "/usr/lib/python3.6/unittest/case.py", line 59, in testPartExecutor
    yield
  File "/usr/lib/python3.6/unittest/case.py", line 605, in run
    testMethod()
  File "/usr/lib/python3.6/unittest/loader.py", line 34, in testFailure
    raise self._exception
ImportError: Failed to import test module: test_SMSHandler
Traceback (most recent call last):
  File "/usr/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName
    module = __import__(module_name)
  File "/home/sevvalboylu/server/app/api/test_SMSHandler.py", line 11, in <module>
    from middleware.services import Sender
ModuleNotFoundError: No module named 'middleware'

回答1:


Looks like you are missing a project's root path in PYTHONPATH

From the docs (Modules - The Module Source Path)

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

If this solution doesn't work for you, please post the project's tree to make it easier find the problem.




回答2:


I've experienced a similar problem with import error when running unit tests (with correct importable structure), but the cause and the solution are different to described in the answer above. Still this is relevant and may help somebody.

In my case I have structure like that (__init__.py present but omitted below for brevity):

mypkg
  \-- foo.py
another
tests
  \-- some
        \-- <tests here>
      mypkg  <--- same name as top level module mypkg
        \-- test_a.py

When running from top level directory imports in test_a.py of modules from mypkg were failing:

# test_a.py
from mypkg import foo  # causes ModuleNotFoundError: No module named 'mypkg.foo'

Renaming mypkg folder under tests folder into something else solved the problem.



来源:https://stackoverflow.com/questions/51376731/python-import-error-run-unittest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!