【问题标题】:Python Import Error - Run unittestPython 导入错误 - 运行 unittest
【发布时间】:2018-12-24 21:08:56
【问题描述】:

为什么我在项目中的某个模块出现导入错误。所有的包都在项目下,它们都有 __init __.py 和其他脚本没有给出同样的错误。 Python 版本是 3.6。代码是在 Unix 环境下编写的。

这是我得到的导入错误。我正在尝试在这里进行测试。

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'

【问题讨论】:

标签: python python-3.x unit-testing testing runtime-error


【解决方案1】:

看起来您在PYTHONPATH 中缺少项目的根路径

来自文档 (Modules - The Module Source Path)

当一个名为 spam 的模块被导入时,解释器首先搜索 对于具有该名称的内置模块。如果没有找到,然后搜索 对于一个名为 spam.py 的文件,在由 变量 sys.path。 sys.path 从这些位置初始化:

  • 包含输入脚本的目录(或当前目录 当没有指定文件时)。
  • PYTHONPATH(目录名称列表,与 shell 变量 PATH 具有相同的语法)。
  • 依赖于安装的默认值。

如果此解决方案不适合您,请发布项目树以便更轻松地找到问题。

【讨论】:

  • 我没有真正理解你的建议,你的意思是我的 PYTHONPATH 中没有中间件吗?我该如何检查?
  • @sevcodes 是的,我就是这个意思。您可以使用以下命令获取 PYTHONPATH 内容:python -c "import sys; print(sys.path)"
  • 检查你的项目的根目录是否包含middleware
  • 好的,我查过了,中间件不存在。如何将其添加到路径中?
  • Nvm 我找到了方法,谢谢你的想法!现在将这个标记为答案
【解决方案2】:

我在运行单元测试(具有正确的可导入结构)时遇到了类似的导入错误问题,但原因和解决方案与上面的答案中描述的不同。这仍然是相关的,可能会对某人有所帮助。

在我的例子中,我有这样的结构(__init__.py 存在,但为简洁起见在下面省略):

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

test_a.py 中的顶级目录导入运行时,来自mypkg 的模块失败:

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

tests 文件夹下的mypkg 文件夹重命名为其他内容可以解决问题。

【讨论】:

    猜你喜欢
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多