{"id":13458483,"url":"https://github.com/jenkinsci/JenkinsPipelineUnit","last_synced_at":"2025-03-24T15:31:23.576Z","repository":{"id":37270181,"uuid":"79999686","full_name":"jenkinsci/JenkinsPipelineUnit","owner":"jenkinsci","description":"Framework for unit testing Jenkins pipelines ","archived":false,"fork":false,"pushed_at":"2025-03-18T07:45:24.000Z","size":1300,"stargazers_count":1553,"open_issues_count":107,"forks_count":398,"subscribers_count":51,"default_branch":"master","last_synced_at":"2025-03-20T12:50:42.327Z","etag":null,"topics":["hactoberfest","jenkins","pipelines-as-code","test"],"latest_commit_sha":null,"homepage":"","language":"Groovy","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jenkinsci.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-01-25T09:21:57.000Z","updated_at":"2025-03-18T07:45:27.000Z","dependencies_parsed_at":"2023-11-21T09:29:26.900Z","dependency_job_id":"2f0fee70-777f-48ee-a51b-9688c35db6ff","html_url":"https://github.com/jenkinsci/JenkinsPipelineUnit","commit_stats":{"total_commits":558,"total_committers":79,"mean_commits":7.063291139240507,"dds":0.7974910394265233,"last_synced_commit":"1038755b07e7263b2db8a4e75543d2ed29b302f2"},"previous_names":["lesfurets/jenkinspipelineunit"],"tags_count":30,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jenkinsci%2FJenkinsPipelineUnit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jenkinsci%2FJenkinsPipelineUnit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jenkinsci%2FJenkinsPipelineUnit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jenkinsci%2FJenkinsPipelineUnit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jenkinsci","download_url":"https://codeload.github.com/jenkinsci/JenkinsPipelineUnit/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245298030,"owners_count":20592522,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hactoberfest","jenkins","pipelines-as-code","test"],"created_at":"2024-07-31T09:00:53.020Z","updated_at":"2025-03-24T15:31:18.565Z","avatar_url":"https://github.com/jenkinsci.png","language":"Groovy","funding_links":[],"categories":["References","Groovy","jenkins"],"sub_categories":["Do on your Jenkins controller machine"],"readme":"# `JenkinsPipelineUnit` Testing Framework\n\nJenkins Pipeline Unit is a testing framework for unit testing Jenkins pipelines, written\nin [Groovy Pipeline DSL](https://jenkins.io/doc/book/pipeline/).\n\n[![Linux/Windows Build status](https://ci.jenkins.io/job/jenkinsci-libraries/job/JenkinsPipelineUnit/job/master/badge/icon)](https://ci.jenkins.io/blue/organizations/jenkins/jenkinsci-libraries%2FJenkinsPipelineUnit/activity?branch=master)\n[![Mac Build status](https://github.com/jenkinsci/JenkinsPipelineUnit/actions/workflows/test.yml/badge.svg?branch=master)](https://github.com/jenkinsci/JenkinsPipelineUnit/actions?query=event%3Apush+branch%3Amaster)\n[![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/jenkinsci/JenkinsPipelineUnit?label=changelog)](https://github.com/jenkinsci/JenkinsPipelineUnit/releases)\n[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/JenkinsPipelineUnit)\n\nIf you use Jenkins as your CI workhorse (like us @\n[lesfurets.com](https://www.lesfurets.com)) and you enjoy writing _pipeline-as-code_, you\nalready know that pipeline code is very powerful but can get pretty complex.\n\nThis testing framework lets you write unit tests on the configuration and conditional\nlogic of the pipeline code, by providing a mock execution of the pipeline. You can mock\nbuilt-in Jenkins commands, job configurations, see the stacktrace of the whole execution\nand even track regressions.\n\n# Table of Contents\n\n1. [Usage](#usage)\n1. [Configuration](#configuration)\n1. [Declarative Pipeline](#declarative-pipelines)\n1. [Testing Shared Libraries](#testing-pipelines-that-use-shared-libraries)\n1. [Writing Testable Libraries](#writing-testable-libraries)\n1. [Note On CPS](#note-on-cps)\n1. [Contributing](#contributing)\n1. [Demos and Examples](#demos-and-examples)\n\n## Usage\n\n### Add to Your Project as Test Dependency\n\nJenkinsPipelineUnit requires Java 11, since this is also the minimum version required by\nJenkins. Also note that JenkinsPipelineUnit is not currently compatible with Groovy 4,\nplease see [this issue](https://github.com/jenkinsci/JenkinsPipelineUnit/issues/521) for\nmore details.\n\n**Note:** Starting from version `1.2`, artifacts are published to\n`https://repo.jenkins-ci.org/releases`.\n\n#### Maven\n\n```xml\n\u003crepositories\u003e\n    \u003crepository\u003e\n    \u003cid\u003ejenkins-ci-releases\u003c/id\u003e\n    \u003curl\u003ehttps://repo.jenkins-ci.org/releases/\u003c/url\u003e\n    \u003c/repository\u003e\n    ...\n\u003c/repositories\u003e\n\n\u003cdependencies\u003e\n    \u003cdependency\u003e\n        \u003cgroupId\u003ecom.lesfurets\u003c/groupId\u003e\n        \u003cartifactId\u003ejenkins-pipeline-unit\u003c/artifactId\u003e\n        \u003cversion\u003e1.9\u003c/version\u003e\n        \u003cscope\u003etest\u003c/scope\u003e\n    \u003c/dependency\u003e\n    ...\n\u003c/dependencies\u003e\n```\n\n#### Gradle\n\n```groovy\nrepositories {\n    maven { url 'https://repo.jenkins-ci.org/releases/' }\n    ...\n}\n\ndependencies {\n    testImplementation \"com.lesfurets:jenkins-pipeline-unit:1.9\"\n    ...\n}\n```\n\n### Start Writing Tests\n\nYou can write your tests in Groovy or Java, using the test framework you prefer. The\neasiest entry point is extending the abstract class `BasePipelineTest`, which initializes\nthe framework with JUnit.\n\nLet's say you wrote this awesome pipeline script, which builds and tests your project:\n\n```groovy\ndef execute() {\n    node() {\n        String utils = load 'src/test/jenkins/lib/utils.jenkins'\n        String revision = stage('Checkout') {\n            checkout scm\n            return utils.currentRevision()\n        }\n        gitlabBuilds(builds: ['build', 'test']) {\n            stage('build') {\n                gitlabCommitStatus('build') {\n                    sh \"mvn clean package -DskipTests -DgitRevision=$revision\"\n                }\n            }\n\n            stage('test') {\n                gitlabCommitStatus('test') {\n                    sh \"mvn verify -DgitRevision=$revision\"\n                }\n            }\n        }\n    }\n}\n\nreturn this\n```\n\nNow using the Jenkins Pipeline Unit you can write a unit test to see if it does the job:\n\n```groovy\nimport com.lesfurets.jenkins.unit.BasePipelineTest\n\nclass TestExampleJob extends BasePipelineTest {\n    @Test\n    void shouldExecuteWithoutErrors() {\n        loadScript('job/exampleJob.jenkins').execute()\n        printCallStack()\n    }\n}\n```\n\nThis test will print the call stack of the execution, which should look like so:\n\n```text\n   exampleJob.run()\n   exampleJob.execute()\n      exampleJob.node(groovy.lang.Closure)\n         exampleJob.load(src/test/jenkins/lib/utils.jenkins)\n            utils.run()\n         exampleJob.stage(Checkout, groovy.lang.Closure)\n            exampleJob.checkout({$class=GitSCM, branches=[{name=feature_test}], extensions=[], userRemoteConfigs=[{credentialsId=gitlab_git_ssh, url=github.com/lesfurets/JenkinsPipelineUnit.git}]})\n            utils.currentRevision()\n               utils.sh({returnStdout=true, script=git rev-parse HEAD})\n         exampleJob.gitlabBuilds({builds=[build, test]}, groovy.lang.Closure)\n            exampleJob.stage(build, groovy.lang.Closure)\n               exampleJob.gitlabCommitStatus(build, groovy.lang.Closure)\n                  exampleJob.sh(mvn clean package -DskipTests -DgitRevision=bcc19744)\n            exampleJob.stage(test, groovy.lang.Closure)\n               exampleJob.gitlabCommitStatus(test, groovy.lang.Closure)\n                  exampleJob.sh(mvn verify -DgitRevision=bcc19744)\n```\n\n### Mocking Jenkins Variables\n\nYou can define both environment variables and job execution parameters.\n\n```groovy\nimport com.lesfurets.jenkins.unit.BasePipelineTest\n\nclass TestExampleJob extends BasePipelineTest {\n    @Override\n    @BeforeEach\n    void setUp() {\n        super.setUp()\n        // Assigns false to a job parameter ENABLE_TEST_STAGE\n        addParam('ENABLE_TEST_STAGE', 'false')\n        // Assigns 1.0.0-rc.1 to the environment variable TAG_NAME\n        addEnvVar('TAG_NAME', '1.0.0-rc.1')\n        // Defines the previous execution status\n        binding.getVariable('currentBuild').previousBuild = [result: 'UNSTABLE']\n    }\n\n    @Test\n    void verifyParam() {\n        assertEquals('false', binding.getVariable('params')['ENABLE_TEST_STAGE'])\n    }\n}\n```\n\nAfter calling `super.setUp()`, the test `helper` instance is available, as well as many\nhelper methods. The test helper already provides basic variables such as a very simple\n`currentBuild` definition. You can redefine them as you wish.\n\nNote that `super.setUp()` must be called prior to using most features. This is commonly done\nusing your own `setUp` method, decorated with `@Override` and `@BeforeEach`.\n\nParameters added via `addParam` are immutable, which reflects the same behavior\nin Jenkins. Attempting to modify the `params` map in the binding will result in an error.\n\n### Mocking Jenkins Commands\n\nYou can register interceptors to mock pipeline methods, including Jenkins commands, which\nmay or may not return a result.\n\n```groovy\nimport com.lesfurets.jenkins.unit.BasePipelineTest\n\nclass TestExampleJob extends BasePipelineTest {\n    @Override\n    @BeforeEach\n    void setUp() {\n        super.setUp()\n        helper.registerAllowedMethod('sh', [Map]) { args -\u003e return 'bcc19744' }\n        helper.registerAllowedMethod('timeout', [Map, Closure], null)\n        helper.registerAllowedMethod('timestamps', []) { println 'Printing timestamp' }\n        helper.registerAllowedMethod('myMethod', [String, int]) { String s, int i -\u003e\n            println \"Executing myMethod mock with args: '${s}', '${i}'\"\n        }\n    }\n}\n```\n\nThe test helper already includes mocks for all base pipeline steps as well as a steps from\na few widely-used plugins. You need to _register allowed methods_ if you want to override\nthese mocks and add others. Note that you need to provide a method signature and a\ncallback (closure or lambda) in order to allow a method. Any method call which is not\nrecognized will throw an exception.\n\nPlease refer to the `BasePipelineTest` class for the list of currently supported mocks.\n\nSome tricky methods such as `load` and `parallel` are implemented directly in the helper.\nIf you want to override those, make sure that you extend the `PipelineTestHelper` class.\n\n### Mocking `readFile` and `fileExists`\n\nThe `readFile` and `fileExists` steps can be mocked to return a specific result for a\ngiven file name. This can be useful for testing pipelines for which file operations can\ninfluence subsequent steps. An example of such a testing scenario follows:\n\n```groovy\n// Jenkinsfile\nnode {\n    stage('Process output') {\n        if (fileExists('output') \u0026\u0026 readFile('output') == 'FAILED!!!') {\n            currentBuild.result = 'FAILURE'\n            error 'Build failed'\n        }\n    }\n}\n```\n\n```groovy\n@Test\nvoid exampleReadFileTest() {\n    helper.addFileExistsMock('output', true)\n    helper.addReadFileMock('output', 'FAILED!!!')\n\n    runScript('Jenkinsfile')\n\n    assertJobStatusFailure()\n}\n```\n\n### Mocking Shell Steps\n\nThe shell steps (`sh`, `bat`, etc) are used by many pipelines for a variety of tasks.\nThey can be mocked to either (a) statically return:\n\n- A string for standard output\n- A return code\n\nOr (b), to execute a closure that returns a `Map` (with `stdout` and `exitValue` entries).\nThe closure will be executed when the shell is called, allowing for dynamic behavior.\n\nHere is a sample pipeline and corresponding unit tests for each of these variants.\n\n```groovy\n// Jenkinsfile\nnode {\n    stage('Mock build') {\n        String systemType = sh(returnStdout: true, script: 'uname')\n        if (systemType == 'Debian') {\n            sh './build.sh --release'\n            int status = sh(returnStatus: true, script: './test.sh')\n            if (status \u003e 0) {\n                currentBuild.result = 'UNSTABLE'\n            } else {\n                def result = sh(\n                    returnStdout: true,\n                    script: './processTestResults.sh --platform debian',\n                )\n                if (!result.endsWith('SUCCESS')) {\n                    currentBuild.result = 'FAILURE'\n                    error 'Build failed!'\n                }\n            }\n        }\n    }\n}\n```\n\n```groovy\n@Test\nvoid debianBuildSuccess() {\n    helper.addShMock('uname', 'Debian', 0)\n    helper.addShMock('./build.sh --release', '', 0)\n    helper.addShMock('./test.sh', '', 0)\n    // Have the sh mock execute the closure when the corresponding script is run:\n    helper.addShMock('./processTestResults.sh --platform debian') { script -\u003e\n        // Do something \"dynamically\" first...\n        return [stdout: \"Executing ${script}: SUCCESS\", exitValue: 0]\n    }\n\n    runScript(\"Jenkinsfile\")\n\n    assertJobStatusSuccess()\n}\n\n@Test\nvoid debianBuildUnstable() {\n    helper.addShMock('uname', 'Debian', 0)\n    helper.addShMock('./build.sh --release', '', 0)\n    helper.addShMock('./test.sh', '', 1)\n\n    runScript('Jenkinsfile')\n\n    assertJobStatusUnstable()\n}\n```\n\nNote that in all cases, the `script` executed by `sh` must *exactly* match the string\npassed to `helper.addShMock`, including the script arguments, whitespace, etc. For more\nflexible matching, you can use a pattern (regular expression) and even capture groups:\n\n```groovy\nhelper.addShMock(~/.\\/build.sh\\s--(.*)/) { String script, String arg -\u003e\n    assert (arg == 'debug') || (arg == 'release')\n    return [stdout: '', exitValue: 2]\n}\n```\n\nAlso, mocks are stacked, so if two mocks match a call, the last one wins. Combined with a\nmatch-everything mock, you can tighten your tests a bit:\n\n```groovy\n@BeforeEach\nvoid setUp() {\n    super.setUp()\n    helper = new PipelineTestHelper()\n    // Basic `sh` mock setup:\n    // - generate an error on unexpected calls\n    // - ignore any echo (debug) outputs, they are not relevant\n    // - all further shell mocks are configured in the test\n    helper.addShMock() { throw new Exception('Unexpected sh call') }\n    helper.addShMock(~/echo\\s.*/, '', 0)\n}\n```\n\n### Analyzing the Mock Execution\n\nThe helper registers every method call to provide a stacktrace of the mock execution.\n\n```groovy\n@Test\nvoid shouldExecuteWithoutErrors() {\n    runScript('Jenkinsfile')\n\n    assertJobStatusSuccess()\n    assertThat(helper.callStack.findAll { call -\u003e\n        call.methodName == 'sh'\n    }.any { call -\u003e\n        callArgsToString(call).contains('mvn verify')\n    }).isTrue()\n}\n```\n\nThis will also check that `mvn verify` was called during the job execution.\n\n### Checking Pipeline Status\n\nLet's say you have a simple script, and you'd like to check its behavior if a step fails.\n\n```groovy\n// Jenkinsfile\nnode() {\n    git 'some_repo_url'\n    sh 'make'\n}\n```\n\nYou can mock the `sh` step to just update the pipeline status to `FAILURE`. To verify that\nyour pipeline is failing, you need to check the status with\n`BasePipelineTest.assertJobStatusFailure()`.\n\n```groovy\n@Test\nvoid checkBuildStatus() {\n    helper.registerAllowedMethod('sh', [String]) { cmd -\u003e\n        if (cmd == 'make') {\n            binding.getVariable('currentBuild').result = 'FAILURE'\n        }\n    }\n\n    runScript('Jenkinsfile')\n\n    assertJobStatusFailure()\n}\n```\n\n### Checking Pipeline Exceptions\n\nSometimes it is useful to verify that a specific exception was thrown during the pipeline\nrun. JUnit 4 and 5 have slightly different mechanisms for doing this.\n\nFor both examples below, assume that the following pipeline is being tested:\n\nTo do so you can use `org.junit.rules.ExpectedException`\n\n```groovy\n// Jenkinsfile\nnode {\n    throw new IllegalArgumentException('oh no!')\n}\n```\n\n#### JUnit 4\n\n```groovy\nclass TestCase extends BasePipelineTest {\n    @Test(expected = IllegalArgumentException)\n    void verifyException() {\n        runScript('Jenkinsfile')\n    }\n}\n```\n\n#### JUnit 5\n```groovy\nimport static org.junit.jupiter.api.Assertions.assertThrows\n\nclass TestCase extends BasePipelineTest {\n    @Test\n    void verifyException() {\n        assertThrows(IllegalArgumentException) { runScript('Jenkinsfile') }\n    }\n}\n```\n\n### Compare the Callstack with a Previous Implementation\n\nOne other use of the callstacks is to check your pipeline executions for possible\nregressions. You have a dedicated method you can call if you extend `BaseRegressionTest`:\n\n```groovy\n@Test\nvoid testPipelineNonRegression() {\n    loadScript('job/exampleJob.jenkins').execute()\n    super.testNonRegression('example')\n}\n```\n\nThis will compare the current callstack of the job to the one you have in a text callstack\nreference file. To update this file with new callstack, just set this JVM argument when\nrunning your tests: `-Dpipeline.stack.write=true`. You then can go ahead and commit this\nchange in your SCM to check in the change.\n\n### Preserve Original Callstack Argument References\n\nThe default behavior of the callstack capture is to clone each call's arguments to\npreserve their values at time of the call should those arguments mutate downstream. That\nis a good guard when your scripts are passing ordinary mutable variables as arguments.\n\nHowever, argument types that are not `Cloneable` are captured as `String` values. Most of\nthe time this is a perfect fallback. But for some complex types, or for types that don't\nimplement `toString()`, it can be tricky or impossible to validate the call values in a\ntest.\n\nTake the following simple example:\n\n```groovy\nMap pretendArgsFromFarUpstream = [\n    foo: 'bar',\n    foo2: 'more bar please',\n    aNestedMap: [aa: 1, bb: 2],\n    plusAList: [1, 2, 3, 4],\n].asImmutable()\n\nnode() {\n    doSomethingWithThis(pretendArgsFromFarUpstream)\n}\n```\n\n`pretendArgsFromFarUpstream` is an immutable map and will be recorded as a `String` in the\ncallstack. Your test may want to perform fine-grained validations via map key referencing\ninstead of pattern matching or similar parsing. For example:\n\n```groovy\nassertEquals(2, arg.aNestedMap.bb)\n```\n\nYou may want to perform this kind of validation, particularly if your pipelines pass\n`final` and/or immutable variables as arguments. You can retain the direct reference to\nthe variable in the callstack by setting this switch in your test setup:\n\n```groovy\nhelper.cloneArgsOnMethodCallRegistration = false\n```\n\n### Running Inline Scripts\n\nIn case you want to have some script executed directly within a test case rather than\ncreating a resource file for it, `loadInlineScript` and `runInlineScript` can be used.\n\n```groovy\n@Test\nvoid testSomeScript() {\n    Object script = loadInlineScript('''\n        node {\n            stage('Build') {\n                sh 'make'\n            }\n        }\n    ''')\n\n    script.execute()\n\n    printCallStack()\n    assertJobStatusSuccess()\n}\n```\n\nNote that inline scripts cannot be debugged via breakpoints as there is no file to attach\nto!\n\n## Configuration\n\nThe abstract class `BasePipelineTest` configures the helper with useful conventions:\n\n- It looks for pipeline scripts in your project in root (`./.`) and `src/main/jenkins`\n  paths.\n- Jenkins pipelines let you load other scripts from a parent script with `load` command.\n  However `load` takes the full path relative to the project root. The test helper mock\n  successfully the `load` command to load the scripts. To make relative paths work, you\n  need to configure the path of the project where your pipeline scripts are, which\n  defaults to `.`.\n- Pipeline script extension, which defaults to jenkins (matches any `*.jenkins` file)\n\nOverriding these default values is easy:\n\n```groovy\nclass TestExampleJob extends BasePipelineTest {\n    @Override\n    @BeforeEach\n    void setUp() {\n        baseScriptRoot = 'jenkinsJobs'\n        scriptRoots += 'src/main/groovy'\n        scriptExtension = 'pipeline'\n        super.setUp()\n    }\n}\n```\n\nThis will work fine for such a project structure:\n\n```\n jenkinsJobs\n └── src\n     ├── main\n     │   └── groovy\n     │       └── ExampleJob.pipeline\n     └── test\n         └── groovy\n             └── TestExampleJob.groovy\n```\n\n## Declarative Pipelines\n\nTo test a declarative pipeline, you'll need to subclass the `DeclarativePipelineTest`\nclass instead of `BasePipelineTest`\n\n```groovy\n// Jenkinsfile\npipeline {\n    agent none\n    stages {\n        stage('Example Build') {\n            agent { docker 'maven:3-alpine' }\n            steps {\n                echo 'Hello, Maven'\n                sh 'mvn --version'\n            }\n        }\n        stage('Example Test') {\n            agent { docker 'openjdk:8-jre' }\n            steps {\n                echo 'Hello, JDK'\n                sh 'java -version'\n            }\n        }\n    }\n}\n```\n\n```groovy\nimport com.lesfurets.jenkins.unit.declarative.*\n\nclass TestExampleDeclarativeJob extends DeclarativePipelineTest {\n    @Test\n    void shouldExecuteWithoutErrors() {\n        runScript(\"Jenkinsfile\")\n\n        assertJobStatusSuccess()\n        printCallStack()\n    }\n}\n```\n\n### DeclarativePipelineTest\n\nThe DeclarativePipelineTest class extends `BasePipelineTest`, so you can verify your\ndeclarative job the same way as scripted pipelines.\n\n## Testing Pipelines That Use Shared Libraries\n\nWith [Shared Libraries](https://jenkins.io/doc/book/pipeline/shared-libraries/), Jenkins\nlets you share common code from pipelines across different repositories. Shared libraries\nare configured in the Jenkins settings and imported with `@Library` annotation or the\n`library` step.\n\nTesting pipeline scripts using external libraries is not trivial because the shared\nlibrary code is another repository. JenkinsPipelineUnit lets you test shared libraries and\npipelines that depend on these libraries.\n\nHere is an example pipeline using a shared library:\n\n```groovy\n@Library('commons')\n\nimport net.courtanet.jenkins.Utils\n\nsayHello 'World'\n\nnode() {\n    stage ('Checkout') {\n        def utils = new Utils()\n        checkout \"${utils.gitTools()}\"\n    }\n    stage ('Build') {\n        sh './gradlew build'\n    }\n    stage ('Post Build') {\n        String json = libraryResource 'net/courtanet/jenkins/request.json'\n        sh \"curl -H 'Content-Type: application/json' -X POST -d '$json' ${acme.url}\"\n    }\n}\n```\n\nThis pipeline is using a shared library called `commons`. Now let's test it:\n\n```groovy\n// You need to import the class first\nimport static com.lesfurets.jenkins.unit.global.lib.LibraryConfiguration.library\n\nclass TestCase extends BasePipelineTest {\n    @Test\n    void testLibrary() {\n        Object library = library()\n            .name('commons')\n            .retriever(gitSource('git@example.com:libs/commons.git'))\n            .targetPath('path/to/clone')\n            .defaultVersion(\"master\")\n            .allowOverride(true)\n            .implicit(false)\n            .build()\n        helper.registerSharedLibrary(library)\n\n        runScript('job/library/exampleJob.jenkins')\n\n        printCallStack()\n    }\n}\n```\n\nNotice how the shared library is defined and registered to the helper. The library\ndefinition is done via a fluent API which lets you set the same configurations as in\n[Jenkins Global Pipeline\nLibraries](https://jenkins.io/doc/book/pipeline/shared-libraries/#using-libraries).\n\nThe `retriever` and `targetPath` fields tell the framework how to fetch the sources of the\nlibrary, and to which local path. The framework comes with two naive but useful\nretrievers, `gitSource` and `localSource`. You can write your own retriever by\nimplementing the `SourceRetriever` interface.\n\nNote that properties `defaultVersion`, `allowOverride` and `implicit` are optional with\ndefault values `master`, `true` and `false`.\n\nNow if we execute this test, the framework will fetch the sources from the Git repository\nand load classes, scripts, global variables and resources found in the library. The\ncallstack of this execution will look like the following:\n\n```text\nLoading shared library commons with version master\nlibraryJob.run()\n  libraryJob.sayHello(World)\n  sayHello.echo(Hello, World.)\n  libraryJob.node(groovy.lang.Closure)\n     libraryJob.stage(Checkout, groovy.lang.Closure)\n        Utils.gitTools()\n        libraryJob.checkout({branch=master})\n     libraryJob.stage(Build, groovy.lang.Closure)\n        libraryJob.sh(./gradlew build)\n     libraryJob.stage(Post Build, groovy.lang.Closure)\n        libraryJob.libraryResource(net/courtanet/jenkins/request.json)\n        libraryJob.sh(curl -H 'Content-Type: application/json' -X POST -d '{\"name\" : \"Ben\"}' http://acme.com)\n```\n\n### Library Source Retrievers\n\nThere are a few types of `SourceRetriever` implementations in addition to the previously\ndescribed `GitSource` one.\n\n#### ProjectSource Retriever\n\nThe `ProjectSource` retriever is useful if you write tests for the library itself. So it\nlets you load the library files directly from the project root folder (where the `src`\nand `vars` folders are located).\n\nThen you can use `projectSource` to point to the location of the library files. Calling\n`projectSource()` with no arguments will look for files in the project root. With\n`.defaultVersion('\u003cnotNeeded\u003e')`,  you can load it in pipelines using `commons@master` or\n`commons@features` which would use the same repository.\n\n```groovy\nimport static com.lesfurets.jenkins.unit.global.lib.ProjectSource.projectSource\n\nclass TestCase extends BasePipelineTest {\n    @Override\n    @BeforeEach\n    void setUp() {\n        super.setUp()\n        Object library = library()\n            .name('commons')\n            .defaultVersion('\u003cnotNeeded\u003e')\n            .allowOverride(true)\n            .implicit(true)\n            .targetPath('\u003cnotNeeded\u003e')\n            .retriever(projectSource())\n            .build()\n        helper.registerSharedLibrary(library)\n    }\n}\n```\n\n#### LocalSource Retriever\n\nThe `LocalSource` retriever is useful if you want to verify how well your library\nintegrates with the pipelines. For example you may use pre-copied library files with\ndifferent versions.\n\n```groovy\nimport static com.lesfurets.jenkins.unit.global.lib.LocalSource.localSource\n\nclass TestCase extends BasePipelineTest {\n    @Override\n    @BeforeEach\n    void setUp() {\n        super.setUp()\n        Object library = library()\n            .name('commons')\n            .defaultVersion('master')\n            .allowOverride(true)\n            .implicit(false)\n            .targetPath('\u003cnotNeeded\u003e')\n            .retriever(localSource('/var/tmp/'))\n            .build()\n        helper.registerSharedLibrary(library)\n    }\n}\n```\n\nIn the above example, the retriever would assume that the library files are located at\n`/var/tmp/commons@master`.\n\n### Loading Libraries Dynamically\n\nThere is partial support for loading dynamic libraries. It doesn't implement all the\nfeatures, but it could be useful sometimes.\n\nPipeline example:\n\n```groovy\nObject commonsLib = library 'commons'\n\n// Assume that `sayHello` is a singleton in the `commons` library\nsayHello 'World'\n\n// Create an instance of a class in the `commons` library\nObject utils = net.courtanet.jenkins.Utils.new()\n```\n\nTest class example:\n\n```groovy\n@Test\nvoid testDynamicLibrary() {\n    Object library = library()\n        .name('commons')\n        .retriever(gitSource('git@example.com:libs/commons.git'))\n        .targetPath('path/to/clone')\n        .defaultVersion('master')\n        .allowOverride(true)\n        .implicit(false)\n        .build()\n    helper.registerSharedLibrary(library)\n    // Registration for pipeline method 'library' must be made after registering the\n    // shared library. Unfortunately, this cannot be moved to the super class.\n    helper.registerAllowedMethod('library', [String], { String name -\u003e\n        helper.getLibLoader().loadLibrary(name)\n        println helper.getLibLoader().libRecords\n        return new LibClassLoader(helper, null)\n    })\n\n    loadScript('job/library/exampleJob.jenkins')\n\n    printCallStack()\n}\n```\n\n### Library Global Variables with Library Object Arguments\n\n\nYou might have a library that defines global variables with library class instances as\narguments. For example, consider the following library class and global variable:\n\n```groovy\n// src/com/example/Monster.groovy\npackage com.example\n\nclass Monster {\n    String moniker\n\n    Monster(String moniker) {\n      this.moniker = moniker\n    }\n}\n```\n\n```groovy\n// vars/monster.groovy\nimport com.example.Monster\n\nvoid call(Monster monster) {\n    println \"${monster.moniker} is always very scary\"\n}\n```\n\nYour pipeline uses both as follows:\n\n```groovy\nMonster vampire = new Monster('Dracula')\nmonster(vampire)\n// Should print \"Dracula is always very scary\"\n```\n\nIf this does not yield the expected output but instead throws a `MissingMethodException`\nwith the cause `No signature of method: Jenkinsfile.monster() is applicable for argument\ntypes: (org.test.Monster) values: [com.example.Monster1@d34db33f]` you may need to disable\nlibrary class preloading in your test setup, which you do with the following switch.\n\n```groovy\nhelper.libLoader.preloadLibraryClasses = false\n```\n\nYou may need to do this on a test-by-test basis, as disabling class preloading can cause\nproblems in other cases. For example, when you have library classes that require access to\nthe `env` global.\n\n## Writing Testable Libraries\n\nWe recommend the following best-practices for organizing pipeline code:\n\n* Keep complex logic in the `Jenkinsfile` to a minimum\n  - When possible, move complexity to external scripts that the `Jenkinsfile` executes\n  - Move shared functionality to [pipeline libraries](https://www.jenkins.io/doc/book/pipeline/shared-libraries/)\n  - Likewise, any tricky Groovy logic that can't be easily moved to external scripts\n    should also be placed in pipeline libraries\n* In pipeline libraries, organize logic in classes under `src`\n  - Ideally, JenkinsPipelineUnit is used to test *only* these classes\n* Use the `vars` singletons to instantiate classes from `src`\n\n### On External Scripts\n\nIn general, it's better to avoid having complex build logic inside of build pipelines.\nAlthough tools like `JenkinsPipelineUnit` are useful in testing pipelines, it's much\neasier to run build scripts locally (meaning, outside of a Jenkins environment). Languages\nlike Python have much more sophisticated linting and testing tools than Groovy does.\n\nThat said, [CodeNarc](https://codenarc.org/) can be used to lint Groovy code, including\n`Jenkinsfile` files.\n\n### On Pipeline Library Organization\n\nWe recommend organizing pipeline libraries such that the bulk of the logic is organized\ninto classes, and the singletons being thin wrappers around these classes. This approach\nhas several advantages:\n\n* It makes it easier to use OOP practices to organize the code\n* It solves the problem of having to mock singletons inside of other singletons for tests\n* It forces the script context to be injected into the class, which means less mocking of\n  `@Library` calls and such\n\n#### Example Pipeline Library Organization\n\nLet's say we have a library responsible for a very complex operation, in this case, adding\ntwo numbers together. 😄 Here's what that library (let's call it `HardMath`) might look\nlike:\n\n```groovy\n// src/com/example/HardMath.groovy\npackage com.example\n\nclass HardMath implements Serializable {\n  // Jenkinsfile script context, note that all pipeline steps must use this context\n  Object script = null\n\n  int complexOperation(int a, int b) {\n    // Note the script context is required for `echo`, as it is a pipeline step\n    script.echo \"Adding ${a} to ${b}\"\n    return a + b\n  }\n}\n```\n\n```groovy\n// vars/hardmath.groovy\nimport com.example.HardMath\n\nint complexOperation(int a, int b) {\n  return new HardMath(script: this).complexOperation(a, b)\n}\n```\n\n```groovy\n// test/com/example/HardMathTest.groovy\npackage com.example\n\nimport static org.junit.jupiter.api.Assertions.assertEquals\n\nimport com.lesfurets.jenkins.unit.BasePipelineTest\nimport org.junit.jupiter.api.BeforeEach\nimport org.junit.jupiter.api.Test\n\n\nclass HardMathTest extends BasePipelineTest {\n  Object script = null\n\n  @Override\n  @BeforeEach\n  void setUp() {\n    super.setUp()\n    this.script = loadScript('test/resources/EmptyPipeline.groovy')\n  }\n\n  @Test\n  void testComplexOperation() {\n    int result = new HardMath(script: script).complexOperation(1, 3)\n    assertEquals(4, result)\n  }\n}\n```\n\n```groovy\n// test/resources/EmptyPipeline.groovy\nreturn this\n```\n\nAnd finally, in some other project's `Jenkinsfile`:\n\n```groovy\n// Jenkinsfile\n@Library('hardmath')\n\nnode {\n  stage('Hard Math') {\n    int result = hardmath.complexOperation(5, 6)\n    echo \"The result is ${result}\"\n  }\n}\n```\n\nFor a larger real-world example of a pipeline library organized like the above and tested\nwith JenkinsPipelineUnit, have a look at\n[`python-pipeline-utils`](https://github.com/Ableton/python-pipeline-utils/).\n\n## Note on CPS\n\nIf you already fiddled with Jenkins pipeline DSL, you may have experienced strange errors\nduring execution on Jenkins. This is because Jenkins does not directly execute your\npipeline in Groovy, but transforms the pipeline code into an intermediate format in order\nto run Groovy code in [Continuation Passing\nStyle](https://en.wikipedia.org/wiki/Continuation-passing_style) (CPS).\n\nThe usual errors are partly due to the [the sandboxing Jenkins\napplies](https://wiki.jenkins-ci.org/display/JENKINS/Script+Security+Plugin#ScriptSecurityPlugin-GroovySandboxing)\nfor security reasons, and partly due to the [serializability Jenkins\nimposes](https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md#serializing-local-variables).\n\nJenkins requires that at each execution step, the whole script context is serializable, in\norder to stop and resume the job execution. To simulate this aspect, CPS versions of the\nhelpers transform your scripts into the CPS format and check if at each step your script\ncontext is serializable.\n\nTo use this _*experimental*_ feature, you can use the abstract class `BasePipelineTestCPS`\ninstead of `BasePipelineTest`. You may see some changes in the callstacks that the helper\nregisters. Note also that the serialization used to test is not the same as what Jenkins\nuses. You may find some incoherence in that respect.\n\n## Contributing\n\nJenkinsPipelineUnit aims to help developers code and test Jenkins pipelines with a shorter\ndevelopment cycle. It addresses some of the requirements traced in\n[JENKINS-33925](https://issues.jenkins-ci.org/browse/JENKINS-33925). If you are willing to\ncontribute please don't hesitate to discuss in issues and open a pull-request.\n\n## Demos and Examples\n\n| URL | Frameworks and Tools | Test Subject | Test Layers |\n|-----|----------------------|--------------|-------------|\n| https://github.com/macg33zr/pipelineUnit | Spock, Gradle(Groovy)  | Jenkinsfile, scripted pipeline, SharedLibrary | UnitTest |\n| https://github.com/mkobit/jenkins-pipeline-shared-library-example | Spock, Gradle (Kotlin), Junit | SharedLibrary | Integration, Unit|\n| https://github.com/stchar/pipeline-sharedlib-testharness          | Junit, Gradle(Groovy) | SharedLibrary | Integration, Unit |\n| https://github.com/stchar/pipeline-dsl-seed                       | Junit, Spock, Gradle(Groovy) | scripted pipeline | Integration(jobdsl), Unit |\n| https://github.com/SpencerMalone/JenkinsPipelineIntegration       | Spock, Gradle(Groovy) | SharedLibrary | Integration |\n| https://github.com/venosov/jenkins-pipeline-shared-library-example-victor       | Junit, Gradle(Kotlin) | SharedLibrary | Unit |\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjenkinsci%2FJenkinsPipelineUnit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjenkinsci%2FJenkinsPipelineUnit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjenkinsci%2FJenkinsPipelineUnit/lists"}