【问题标题】:Python - package in parallel directory not found from *behave* testPython - 从 *behave* 测试中找不到并行目录中的包
【发布时间】:2020-07-09 01:10:24
【问题描述】:

我正在尝试在 Python 中完成 behave 测试。

简单的行为测试本身没有问题。但是,当我尝试使用我已经创建并且位于并行目录中的包中的模块时,我正在苦苦挣扎。

目录结构类似于:

src
 ├── connection
 │    │
 │    └── api_connector.py
 │
 ├── behave_tests
 │    │
 │    ├─ steps
 │    │  │
 │    │  └ testCommands.py
 │    │
 │    ├── testConnection.feature
 │    └── testCommands.feature
 │
 └── unit_tests

通常,behavebehave_tests 目录中启动。起初,它运行良好。用于行为测试的所有 Python 代码都在文件 testCommands.py 中,只使用了来自 python 核心的包。

但后来我更改了 testCommands.py 以使用我自己的包 connection 中的代码,该包已经过测试和工作。

testCommands.py 我写了输入行

from connection.api_connector import ApiConnector, SerialApiConnector

但是这个输入行没有被行为解析,它输出:

ModuleNotFoundError: No module named 'connection'

我尝试通过将以下行添加到 test_commands.py

的顶部,将我的包 connection 附加到 python 模块路径
import sys
sys.path.append('/home/username/projects/projectname/src/connection/')

但这并没有帮助。

我如何告诉 behave 使用我的 connection 包?

【问题讨论】:

标签: python module package behavior


【解决方案1】:

经过进一步阅读,我能够找到解决方案。

  1. 为了让 Python 将目录 connection 识别为一个包,我必须将空的 __init__.py 文件添加到两个目录中:srcconnection .
  2. 为了能够使用绝对导入来处理包连接PYTHONPATH 环境变量必须指向src 目录。

例如在 linux shell 中,我通过键入设置 PYTHONPATH

export PYTHONPATH=/home/{username}/test_project/src

然后,python 解释器以及 behave 查找并解析有问题的模块,只要它们是从这个 shell 中启动的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多