【问题标题】:pytest fails when run in folder which has __init__.pypytest 在具有 __init__.py 的文件夹中运行时失败
【发布时间】:2021-09-27 11:04:15
【问题描述】:

运行pytest 命令的文件夹里面有__init__.py。这就是为什么测试无法从utils 导入模块的原因。此行为符合 docs 中规定的 pytest 要求,即 basedir 不应包含 __init__.py

有没有办法在包含__init__.py 的目录中运行pytest

下面是文件夹结构。

.
├── __init__.py
├── tests
└── utils

如果从文件夹中删除__init__.py,则pytest 成功。

【问题讨论】:

  • 为什么不从不同的目录运行 pytest?确实,如果您尝试运行一个包,并且该包的基本目录不在您的 sys.path/PYTHONPATH 上,那么确实包相对导入将无法正常工作。
  • 你建议在哪个目录运行它?由于 pytest 行为,我会偶然发现同样的问题:determine basedir: this is the first “upward” (towards the root) directory not containing an __init__.py

标签: python python-3.x pytest


【解决方案1】:

有效的解决方案是将以下代码添加到 tests 文件夹内的测试模块中:

import sys

sys.path.append('../../')

然后,在文件夹 tests 内运行 pytest 即可。 (如果在根项目文件夹中运行,它仍然会失败。

【讨论】:

    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多