Python 导入错误 - 运行单元测试

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

为什么我在项目中遇到模块导入错误。所有包都在项目下,它们都有 __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'

最佳答案

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

来自文档 ( 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.

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

关于Python 导入错误 - 运行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51376731/

相关文章:

c++ - 参数化继承的元类

python-3.x - 从 boto3 table.batch_writer 对象获取 Http 响应

node.js - 导入 Node 核心模块会破坏 Karma 测试(使用 @open-wc/testing-karma)

ios - AFNetworking Post 请求的单元测试

javascript - 日期对象值发生变化 - JavaScript

java - 使用 JDBC 与 MySQL、JAVA REST 和 Python REST 进行序列化

python - 如何删除 pyside/pyqt 中 ui 组件的属性?

python - Yahoo BOSS V2授权麻烦

python - 如何使用 Selenium Python 清除文本字段

python - python 中的图像数组