JenkinsPipelineUnit

JenkinsPipelineUnit

Jenkins流水线代码单元测试框架

JenkinsPipelineUnit是针对Jenkins流水线代码的单元测试框架。它支持对Groovy Pipeline DSL编写的流水线进行配置和逻辑测试,提供Jenkins命令模拟、作业配置模拟、执行堆栈跟踪和回归测试等功能。该框架兼容Java 11+版本,可通过Maven或Gradle集成到项目中,方便开发人员进行流水线代码的自动化测试。

JenkinsPipeline单元测试Groovy持续集成Github开源项目

JenkinsPipelineUnit Testing Framework

Jenkins Pipeline Unit is a testing framework for unit testing Jenkins pipelines, written in Groovy Pipeline DSL.

Linux/Windows Build status Mac Build status GitHub release (latest SemVer) Gitter chat

If you use Jenkins as your CI workhorse (like us @ lesfurets.com) and you enjoy writing pipeline-as-code, you already know that pipeline code is very powerful but can get pretty complex.

This testing framework lets you write unit tests on the configuration and conditional logic of the pipeline code, by providing a mock execution of the pipeline. You can mock built-in Jenkins commands, job configurations, see the stacktrace of the whole execution and even track regressions.

Table of Contents

  1. Usage
  2. Configuration
  3. Declarative Pipeline
  4. Testing Shared Libraries
  5. Writing Testable Libraries
  6. Note On CPS
  7. Contributing
  8. Demos and Examples

Usage

Add to Your Project as Test Dependency

JenkinsPipelineUnit requires Java 11, since this is also the minimum version required by Jenkins. Also note that JenkinsPipelineUnit is not currently compatible with Groovy 4, please see this issue for more details.

Note: Starting from version 1.2, artifacts are published to https://repo.jenkins-ci.org/releases.

Maven

<repositories> <repository> <id>jenkins-ci-releases</id> <url>https://repo.jenkins-ci.org/releases/</url> </repository> ... </repositories> <dependencies> <dependency> <groupId>com.lesfurets</groupId> <artifactId>jenkins-pipeline-unit</artifactId> <version>1.9</version> <scope>test</scope> </dependency> ... </dependencies>

Gradle

repositories { maven { url 'https://repo.jenkins-ci.org/releases/' } ... } dependencies { testImplementation "com.lesfurets:jenkins-pipeline-unit:1.9" ... }

Start Writing Tests

You can write your tests in Groovy or Java, using the test framework you prefer. The easiest entry point is extending the abstract class BasePipelineTest, which initializes the framework with JUnit.

Let's say you wrote this awesome pipeline script, which builds and tests your project:

def execute() { node() { String utils = load 'src/test/jenkins/lib/utils.jenkins' String revision = stage('Checkout') { checkout scm return utils.currentRevision() } gitlabBuilds(builds: ['build', 'test']) { stage('build') { gitlabCommitStatus('build') { sh "mvn clean package -DskipTests -DgitRevision=$revision" } } stage('test') { gitlabCommitStatus('test') { sh "mvn verify -DgitRevision=$revision" } } } } } return this

Now using the Jenkins Pipeline Unit you can write a unit test to see if it does the job:

import com.lesfurets.jenkins.unit.BasePipelineTest class TestExampleJob extends BasePipelineTest { @Test void shouldExecuteWithoutErrors() { loadScript('job/exampleJob.jenkins').execute() printCallStack() } }

This test will print the call stack of the execution, which should look like so:

exampleJob.run() exampleJob.execute() exampleJob.node(groovy.lang.Closure) exampleJob.load(src/test/jenkins/lib/utils.jenkins) utils.run() exampleJob.stage(Checkout, groovy.lang.Closure) exampleJob.checkout({$class=GitSCM, branches=[{name=feature_test}], extensions=[], userRemoteConfigs=[{credentialsId=gitlab_git_ssh, url=github.com/lesfurets/JenkinsPipelineUnit.git}]}) utils.currentRevision() utils.sh({returnStdout=true, script=git rev-parse HEAD}) exampleJob.gitlabBuilds({builds=[build, test]}, groovy.lang.Closure) exampleJob.stage(build, groovy.lang.Closure) exampleJob.gitlabCommitStatus(build, groovy.lang.Closure) exampleJob.sh(mvn clean package -DskipTests -DgitRevision=bcc19744) exampleJob.stage(test, groovy.lang.Closure) exampleJob.gitlabCommitStatus(test, groovy.lang.Closure) exampleJob.sh(mvn verify -DgitRevision=bcc19744)

Mocking Jenkins Variables

You can define both environment variables and job execution parameters.

import com.lesfurets.jenkins.unit.BasePipelineTest class TestExampleJob extends BasePipelineTest { @Override @BeforeEach void setUp() { super.setUp() // Assigns false to a job parameter ENABLE_TEST_STAGE addParam('ENABLE_TEST_STAGE', 'false') // Assigns 1.0.0-rc.1 to the environment variable TAG_NAME addEnvVar('TAG_NAME', '1.0.0-rc.1') // Defines the previous execution status binding.getVariable('currentBuild').previousBuild = [result: 'UNSTABLE'] } @Test void verifyParam() { assertEquals('false', binding.getVariable('params')['ENABLE_TEST_STAGE']) } }

After calling super.setUp(), the test helper instance is available, as well as many helper methods. The test helper already provides basic variables such as a very simple currentBuild definition. You can redefine them as you wish.

Note that super.setUp() must be called prior to using most features. This is commonly done using your own setUp method, decorated with @Override and @BeforeEach.

Parameters added via addParam are immutable, which reflects the same behavior in Jenkins. Attempting to modify the params map in the binding will result in an error.

Mocking Jenkins Commands

You can register interceptors to mock pipeline methods, including Jenkins commands, which may or may not return a result.

import com.lesfurets.jenkins.unit.BasePipelineTest class TestExampleJob extends BasePipelineTest { @Override @BeforeEach void setUp() { super.setUp() helper.registerAllowedMethod('sh', [Map]) { args -> return 'bcc19744' } helper.registerAllowedMethod('timeout', [Map, Closure], null) helper.registerAllowedMethod('timestamps', []) { println 'Printing timestamp' } helper.registerAllowedMethod('myMethod', [String, int]) { String s, int i -> println "Executing myMethod mock with args: '${s}', '${i}'" } } }

The test helper already includes mocks for all base pipeline steps as well as a steps from a few widely-used plugins. You need to register allowed methods if you want to override these mocks and add others. Note that you need to provide a method signature and a callback (closure or lambda) in order to allow a method. Any method call which is not recognized will throw an exception.

Please refer to the BasePipelineTest class for the list of currently supported mocks.

Some tricky methods such as load and parallel are implemented directly in the helper. If you want to override those, make sure that you extend the PipelineTestHelper class.

Mocking readFile and fileExists

The readFile and fileExists steps can be mocked to return a specific result for a given file name. This can be useful for testing pipelines for which file operations can influence subsequent steps. An example of such a testing scenario follows:

// Jenkinsfile node { stage('Process output') { if (fileExists('output') && readFile('output') == 'FAILED!!!') { currentBuild.result = 'FAILURE' error 'Build failed' } } }
@Test void exampleReadFileTest() { helper.addFileExistsMock('output', true) helper.addReadFileMock('output', 'FAILED!!!') runScript('Jenkinsfile') assertJobStatusFailure() }

Mocking Shell Steps

The shell steps (sh, bat, etc) are used by many pipelines for a variety of tasks. They can be mocked to either (a) statically return:

  • A string for standard output
  • A return code

Or (b), to execute a closure that returns a Map (with stdout and exitValue entries). The closure will be executed when the shell is called, allowing for dynamic behavior.

Here is a sample pipeline and corresponding unit tests for each of these variants.

// Jenkinsfile node { stage('Mock build') { String systemType = sh(returnStdout: true, script: 'uname') if (systemType == 'Debian') { sh './build.sh --release' int status = sh(returnStatus: true, script: './test.sh') if (status > 0) { currentBuild.result = 'UNSTABLE' } else { def result = sh( returnStdout: true, script: './processTestResults.sh --platform debian', ) if (!result.endsWith('SUCCESS')) { currentBuild.result = 'FAILURE' error 'Build failed!' } } } } }
@Test void debianBuildSuccess() { helper.addShMock('uname', 'Debian', 0) helper.addShMock('./build.sh --release', '', 0) helper.addShMock('./test.sh', '', 0) // Have the sh mock execute the closure when the corresponding script is run: helper.addShMock('./processTestResults.sh --platform debian') { script -> // Do something "dynamically" first... return [stdout: "Executing ${script}: SUCCESS", exitValue: 0] } runScript("Jenkinsfile") assertJobStatusSuccess() } @Test void debianBuildUnstable() { helper.addShMock('uname', 'Debian', 0) helper.addShMock('./build.sh --release', '', 0) helper.addShMock('./test.sh', '', 1) runScript('Jenkinsfile') assertJobStatusUnstable() }

Note that in all cases, the script executed by sh must exactly match the string passed to helper.addShMock, including the script arguments, whitespace, etc. For more flexible matching, you can use a pattern (regular expression) and even capture groups:

helper.addShMock(~/.\/build.sh\s--(.*)/) { String script, String arg -> assert (arg == 'debug') || (arg == 'release') return [stdout: '', exitValue: 2] }

Also, mocks are stacked, so if two mocks match a call, the last one wins. Combined with a match-everything mock, you can tighten your tests a bit:

@BeforeEach void setUp() { super.setUp() helper = new PipelineTestHelper() // Basic `sh` mock setup: // - generate an error on unexpected calls // - ignore any echo (debug) outputs, they are not relevant // - all further shell mocks are configured in the test helper.addShMock() { throw new Exception('Unexpected sh call') } helper.addShMock(~/echo\s.*/, '', 0) }

Analyzing the Mock Execution

The helper registers every method call to provide a stacktrace of the mock execution.

@Test void shouldExecuteWithoutErrors() { runScript('Jenkinsfile') assertJobStatusSuccess() assertThat(helper.callStack.findAll { call -> call.methodName == 'sh' }.any { call -> callArgsToString(call).contains('mvn verify') }).isTrue() }

This will also check that mvn verify was called during the job execution.

Checking Pipeline Status

Let's say you have a simple script, and you'd like to check its behavior if a step fails.

// Jenkinsfile node() { git 'some_repo_url' sh 'make' }

You can mock the sh step to just update the pipeline status to FAILURE. To verify that your pipeline is failing, you need to check the status with BasePipelineTest.assertJobStatusFailure().

@Test void checkBuildStatus() { helper.registerAllowedMethod('sh', [String]) { cmd -> if (cmd == 'make') { binding.getVariable('currentBuild').result = 'FAILURE' } } runScript('Jenkinsfile') assertJobStatusFailure() }

Checking Pipeline Exceptions

Sometimes it is useful to verify that a specific exception was thrown during the pipeline run. JUnit 4 and 5 have slightly different mechanisms for doing this.

For both examples below, assume that the following pipeline is being tested:

To do so you can use org.junit.rules.ExpectedException

// Jenkinsfile node { throw new IllegalArgumentException('oh no!') }

JUnit 4

class TestCase extends BasePipelineTest { @Test(expected = IllegalArgumentException) void verifyException() { runScript('Jenkinsfile') } }

JUnit 5

import static org.junit.jupiter.api.Assertions.assertThrows class TestCase extends BasePipelineTest { @Test void verifyException() { assertThrows(IllegalArgumentException) { runScript('Jenkinsfile') } } }

Compare the Callstack with a Previous Implementation

One other use of the callstacks is to check your pipeline executions for possible regressions. You have a dedicated method you can call if you extend BaseRegressionTest:

@Test void testPipelineNonRegression() { loadScript('job/exampleJob.jenkins').execute() super.testNonRegression('example') }

This will compare the current callstack of the job to the one you have in a text callstack reference file. To update this file with new callstack, just set this JVM argument when running your tests: -Dpipeline.stack.write=true. You then can go ahead and commit this change in your SCM to check in the change.

Preserve Original Callstack Argument References

The default behavior of the callstack capture is to clone each call's arguments to preserve their values at time of the call should those arguments mutate downstream. That is a good guard when your scripts are passing ordinary mutable variables as arguments.

However, argument types that are not Cloneable are captured as String values. Most of the time this is a perfect fallback. But for some complex types, or for types that don't implement toString(), it can be tricky or impossible to validate the call values in a test.

Take the following simple example:

Map pretendArgsFromFarUpstream = [ foo: 'bar', foo2: 'more bar please', aNestedMap: [aa: 1, bb: 2], plusAList: [1, 2, 3, 4], ].asImmutable() node() { doSomethingWithThis(pretendArgsFromFarUpstream) }

pretendArgsFromFarUpstream is an immutable map and will be recorded as a String in the callstack. Your test may want to perform fine-grained validations via map key referencing instead of pattern matching or similar parsing. For example:

assertEquals(2, arg.aNestedMap.bb)

You may want to perform this kind of validation, particularly if your pipelines pass final and/or immutable variables as arguments. You can retain the direct reference to the variable in the callstack by setting this switch in your test setup:

helper.cloneArgsOnMethodCallRegistration = false

Running Inline Scripts

In case you want to have some script executed directly within a test case rather than creating a resource file for it, loadInlineScript and runInlineScript can be used.

@Test void testSomeScript() { Object script = loadInlineScript(''' node { stage('Build') { sh 'make' } } ''') script.execute() printCallStack() assertJobStatusSuccess() }

Note that inline scripts cannot be debugged via breakpoints as there is no file to attach to!

Configuration

The abstract class BasePipelineTest configures the helper with useful conventions:

  • It looks for pipeline scripts in your project in root (./.) and src/main/jenkins paths.
  • Jenkins pipelines let you load other scripts from a parent script with load command. However load takes the full path relative to the project root. The test helper mock successfully the load command to load the scripts. To make relative paths work, you need to configure the path of the project where your

编辑推荐精选

TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多