「Jenkins-Pipeline」- 单元测试 | Unit Testing for Jenkins Shared Libraries

问题

我们所遭遇的问题

在开发初期时,我们通过“运行 Pipeline”的方式来调试和修正问题。随着项目的增长,作业运行周期较长,我们需要通过单元测试来对代码进行调试,而不能再通过运行调试的方式来运行测试代码。

针对 Jenkins Pipeline 单元测试

如果使用 Jenkins 作为 CI 主力,并且喜欢编写 Pipeline as Code,那么已经知道 Pipeline 代码非常强大。

但是 Pipeline 可能会变得非常复杂。所以需要提供 Pipeline 的模拟执行,来对 Pipeline 代码的配置和条件逻辑编写单元测试。同时,需要模拟内置 Jenkins 命令、作业配置,查看整个执行的堆栈跟踪,甚至跟踪回归。

分析

# 08/13/2024 根据 Unit Testing for Jenkins Shared Libraries 文章,我们了解到相关;

# 08/14/2024 根据 Pipeline Development Tools/Pipeline Unit Testing Framework 文档;

Gradle + JUnit

Adrian Kuper/How-To: Setup a unit-testable Jenkins shared pipeline library – DEV Community
kuper-adrian/jenkins-shared-library-example: Example for a Jenkins shared library with unit tests

The idea is to keep the steps under “var” as simple as possible and move most of your logic and heavy lifting to classes under src. Then you can write unit tests for your classes and test them locally before pushing the changes.

Maven + JUnit + GMavenPlus

# 12/20/2022 当前,我们通过 Maven 进行共享库的管理:通过 JUnit 进行单元测试。通过 GMavenPlus Plugin 进行 Groovy 编译;

虽然 GMavenPlus 是 Groovy 官方的插件,但是在技术选型时我们依旧有些担心,日后可能会使用 Gradle 管理。

Jenkins Shared Library Test Harness Example
https://github.com/stchar/pipeline-sharedlib-testharness

Pipeline Unit Testing Framework(推荐)

官网:https://www.jenkins.io/doc/book/pipeline/development/#unit-test
文档:https://github.com/jenkinsci/JenkinsPipelineUnit/blob/master/README.md
仓库:https://github.com/jenkinsci/JenkinsPipelineUnit

The Pipeline Unit Testing Framework allows you to unit test Pipelines and Shared Libraries before running them in full. It provides a mock execution environment where real Pipeline steps are replaced with mock objects that you can use to check for expected behavior. New and rough around the edges, but promising. The README for that project contains examples and usage instructions. 简而言之,其为出现在官方文档中的 Pipeline 的单元测试工具,其用于测试 Pipeline 和共享库。

GitHub/jenkinsci/JenkinsPipelineUnit 能够进行单元测试,上次提交是 5d 之前(08/14/2024),所以该项目或许可用。

性质:

  • 其能够进行 Pipelines and Shared Libraries 的测试。