Pytest 内部应用程序插件未被发现

问题描述 投票:0回答:1

我一直在尝试开始使用基本的 Pytest 内部应用程序插件。根据 v8.1.1 Pytest doc,在

MyPlugin.py
文件中加载
test_TestPlugin.py
应该可以通过所述 test_ 文件中的
pytest_plugins = ["MyPlugin",]
实现。但是,运行
pytest -s
会出现导入错误:“没有名为 'MyPlugin' 的模块”。

插件和 test_ 文件都位于同一个

tests/
目录中。

MyPlugin.py

import pytest

@pytest.hookimpl()
def pytest_runtest_setup(item:pytest.Item):
    print("Hook executed!")

test_TestPlugin.py

pytest_plugins = ["MyPlugin",]

def test_quick():
    assert 1 == 1

我已经尝试过:

  1. pytest_plugins
    放入 conftest.py 中。给出相同的导入错误。
  2. 在“MyPlugin”前面加上插件和 test_ 文件所在的目录:
    pytest_plugins = ["tests.MyPlugin",]
    。这确实有效,但不是预期的也不是首选的。

感谢任何和所有帮助!

plugins pytest hook
1个回答
0
投票

使用

pytest_plugins
变量加载插件也会将插件作为模块导入。然而,如果
import MyPlugin
不起作用,
pytest_plugins = ["MyPlugin",]
也不起作用,正如 MrBean Bremen 指出的那样。为什么导入
MyPlugin
不起作用?因为调用
pytest
不会将当前工作目录添加到 sys.path 中。尽管这是
python
调用中的默认行为,8.1.x 文档说。

让我们来看看什么是可以做的,什么是不应该做的:

运行时将cwd添加到sys.path中
pytest

将cwd添加到sys.path可以通过通过python调用pytest来完成:

python -m pytest
从用户flub回答的如何在 py.test 中加载自定义插件得到这个。

使用相对或绝对导入

正如问题中提到的,使用

pytest_plugins = ["tests.MyPlugin",]
而不仅仅是插件名称就可以了。

使用虚拟环境安装插件

首先将插件变成可安装包然后安装它,例如使用 Pipenv 或 Poetry 等 venv 管理器,会将模块添加到 sys.path:安装的 venv 包最终会出现在

site-packages
目录中,该目录会在运行时添加到 sys.path 中。

避免
__init__.py
使您的插件可导入

这个答案中,用户wim解释了为什么不建议使用

__init__.py
使cwd出现在sys.path上,以及为什么应该使用venv安装或
python -m pytest
。但是,请注意,答案部分已经过时:“不依赖”
__init__.py
的最佳理由不再是因为 Pytest 将“使 importlib 成为未来版本中的默认值”。在 8.1.1 文档中:“在可预见的未来,默认值将保持
prepend
”,这意味着
__init__.py
将继续工作(但仍然不建议)。

© www.soinside.com 2019 - 2024. All rights reserved.