【问题标题】:How to install python plugin before running pytest tests?如何在运行 pytest 测试之前安装 python 插件?
【发布时间】:2021-09-08 21:23:20
【问题描述】:

在使用 pytest 开始测试之前,我需要安装一个简单的 python 文件的 python 插件。我在 setup.py 中使用了 entry_points。我的问题有点复杂,所以让我们通过一个例子来解决这个问题,我们稍后会回到这个问题。

有两个包 - 一个是 core,另一个是 mypackage

Core 提供了添加组名为“my.plugin”的插件的功能。

核心封装逻辑

from importlib_metadata import entry_points 
def plugin_method(some_data):
    plugins = entry_points()['my.plugin']
    loaded_plugins = []
    for p in plugins:
       loaded_plugins.apend(p.load())
    #Does some processing on the data and decides which method to call from plugin
    #call plugin method
return result

我的包逻辑

setup.py

setup(
...
entry_points={'my.plugin': 'plugin1= plugin1.logic'}
...
)

logic.py

def method1(method_data):
    print('method1 called')
    return 1

def method2(method_data):
    print('method1 called')
    return 2

ma​​in.py

def method_uses_plugin()
    # create data
    plugin_method(data)

插件工作正常。 :)


问题

我为 method_uses_plugin 方法编写了一个测试用例。如果我在我的机器上安装了 pypackage 它工作正常,但如果安装未完成(在 jenkins 管道中????)

我们通常不会安装包来运行测试用例,因为测试用例应该直接使用源代码。

我们可能需要使用 pytest 来在 entry_points 中注册插件。我尝试了很多链接,但没有任何效果。

我的用例有点复杂,但可以找到类似的问题here

【问题讨论】:

  • 为什么不能安装插件进行测试?看起来测试的代码需要安装插件。
  • @MrBean 因为我想用源代码运行测试。我可以只安装插件而不是整个包吗?
  • cc - @MrBeanBremen
  • 我不确定,但为什么不在 Jenkins 中以通常的方式 (pip install .) 安装你的包?是不是很广阔?
  • 谢谢,@MrBeanBremen,如果你能用一个非常有帮助的例子来解释它。我可以将其标记为答案。

标签: python-3.x jenkins pytest python-unittest setuptools


【解决方案1】:

有两个用例可以在实际源代码上运行测试。

在您的本地计算机中

如果你想在工作时测试源代码,你可以简单地使用以下命令以可编辑模式安装你的包:

pip install -e .

手册页中 -e 的文档:

-e,--editable <path/url>
     Install a project in editable mode (i.e.  setuptools "develop mode") from a local project path or a VCS url.

这会将包链接到代码的. 位置,这意味着对源代码所做的任何更改都将反映在包上。

在持续集成 (CI) 中

由于您的 CI 在 docker 容器上运行,您只需复制其中的源代码,使用 pip install . 安装它,最后运行 pytest

【讨论】:

    【解决方案2】:

    如果一切都失败了,您可以尝试将您的代码转换为可执行文件,并使用批处理命令为您需要的任意数量的包运行 pip install,然后运行您的程序。我相信 Jenkins 你可以以管理员身份运行批处理文件。

    Invoke pip install from batch file

    Run Batch file as an administrator in Jenkins

    【讨论】:

      猜你喜欢
      • 2011-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2020-12-01
      相关资源
      最近更新 更多