### Example Declarative Pipeline Structure Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A sample Jenkinsfile demonstrating a declarative pipeline with multiple stages, each using a different Docker agent and executing basic commands. ```groovy // Jenkinsfile pipeline { agent none stages { stage('Example Build') { agent { docker 'maven:3-alpine' } steps { echo 'Hello, Maven' sh 'mvn --version' } } stage('Example Test') { agent { docker 'openjdk:8-jre' } steps { echo 'Hello, JDK' sh 'java -version' } } } } ``` -------------------------------- ### Jenkinsfile Example with File Operations Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md An example Jenkinsfile that checks for the existence of 'output' and reads its content to determine build status. This demonstrates a scenario where file operations influence pipeline execution. ```groovy // Jenkinsfile node { stage('Process output') { if (fileExists('output') && readFile('output') == 'FAILED!!!') { currentBuild.result = 'FAILURE' error 'Build failed' } } } ``` -------------------------------- ### Example Jenkins Pipeline Script Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md An example of a Jenkins pipeline script that performs checkout, build, and test stages using shell commands and utility functions. ```groovy 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 ``` -------------------------------- ### Register and Load Dynamic Library in Test Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Registers a shared library using `gitSource` and then loads a script that utilizes this library. This setup is for testing dynamic library loading. ```groovy @Test void testDynamicLibrary() { Object library = library() .name('commons') .retriever(gitSource('git@example.com:libs/commons.git')) .targetPath('path/to/clone') .defaultVersion('master') .allowOverride(true) .implicit(false) .build() helper.registerSharedLibrary(library) // Registration for pipeline method 'library' must be made after registering the // shared library. Unfortunately, this cannot be moved to the super class. helper.registerAllowedMethod('library', [String], { String name -> helper.getLibLoader().loadLibrary(name) println helper.getLibLoader().libRecords return new LibClassLoader(helper, null) }) loadScript('job/library/exampleJob.jenkins') printCallStack() } ``` -------------------------------- ### Mocking readFile and fileExists for Testing Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Mock the 'fileExists' and 'readFile' steps to return specific values for testing file-dependent pipeline logic. This example sets up mocks to simulate a 'FAILED!!!' output file, leading to a build failure. ```groovy @Test void exampleReadFileTest() { helper.addFileExistsMock('output', true) helper.addReadFileMock('output', 'FAILED!!!') runScript('Jenkinsfile') assertJobStatusFailure() } ``` -------------------------------- ### Jenkinsfile Using a Pipeline Library Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md An example Jenkinsfile that utilizes a shared pipeline library. It loads the library and calls a function defined within it. ```groovy // Jenkinsfile @Library('hardmath') node { stage('Hard Math') { int result = hardmath.complexOperation(5, 6) echo "The result is ${result}" } } ``` -------------------------------- ### Example Pipeline Using a Shared Library Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md This Groovy script demonstrates a Jenkins pipeline that imports and uses a shared library named 'commons'. It includes stages for checkout, build, and post-build actions. ```groovy @Library('commons') import net.courtanet.jenkins.Utils sayHello 'World' node() { stage ('Checkout') { def utils = new Utils() checkout "${utils.gitTools()}" } stage ('Build') { sh './gradlew build' } stage ('Post Build') { String json = libraryResource 'net/courtanet/jenkins/request.json' sh "curl -H 'Content-Type: application/json' -X POST -d '$json' ${acme.url}" } } ``` -------------------------------- ### Mocking Jenkins Variables in Tests Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Example of mocking Jenkins environment variables and job parameters within a test class that extends BasePipelineTest. This setup is done in the setUp method using addParam and addEnvVar. ```groovy 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']) } } ``` -------------------------------- ### Disable Library Class Preloading in Test Setup Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A switch to disable library class preloading in the test setup. This may be necessary when library classes require access to the `env` global, but disabling it can cause issues in other cases. ```groovy helper.libLoader.preloadLibraryClasses = false ``` -------------------------------- ### Example Shared Library Call Stack Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md This text output shows the call stack of a Jenkins pipeline execution that uses a shared library. It details the sequence of method calls and stages executed during the pipeline run. ```text Loading shared library commons with version master libraryJob.run() libraryJob.sayHello(World) sayHello.echo(Hello, World.) libraryJob.node(groovy.lang.Closure) libraryJob.stage(Checkout, groovy.lang.Closure) Utils.gitTools() libraryJob.checkout({branch=master}) libraryJob.stage(Build, groovy.lang.Closure) libraryJob.sh(./gradlew build) libraryJob.stage(Post Build, groovy.lang.Closure) libraryJob.libraryResource(net/courtanet/jenkins/request.json) libraryJob.sh(curl -H 'Content-Type: application/json' -X POST -d '{"name" : "Ben"}' http://acme.com) ``` -------------------------------- ### Use Library Class and Global Variable in Pipeline Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Example of how to use the `Monster` class and the `monster` global variable defined in a shared library within a Jenkins pipeline. ```groovy Monster vampire = new Monster('Dracula') monster(vampire) // Should print "Dracula is always very scary" ``` -------------------------------- ### Call Stack of Pipeline Execution Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md The expected call stack output from executing the example Jenkins pipeline test. This shows the sequence of function calls and their arguments. ```text 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) ``` -------------------------------- ### Example Immutable Map Argument Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Demonstrates passing an immutable map as an argument. Immutable arguments are captured as strings by default, but can be validated via map key referencing if `cloneArgsOnMethodCallRegistration` is set to false. ```groovy Map pretendArgsFromFarUpstream = [ foo: 'bar', foo2: 'more bar please', aNestedMap: [aa: 1, bb: 2], plusAList: [1, 2, 3, 4], ].asImmutable() node() { doSomethingWithThis(pretendArgsFromFarUpstream) } ``` -------------------------------- ### Test Declarative Pipeline Job Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Subclass DeclarativePipelineTest to test a declarative pipeline. This example shows how to run a script, assert job success, and print the call stack. ```groovy import com.lesfurets.jenkins.unit.declarative.* class TestExampleDeclarativeJob extends DeclarativePipelineTest { @Test void shouldExecuteWithoutErrors() { runScript("Jenkinsfile") assertJobStatusSuccess() printCallStack() } } ``` -------------------------------- ### Jenkinsfile with Shell Steps Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A sample Jenkinsfile demonstrating the use of `sh` for checking system type, executing build scripts, running tests, and processing results. It includes conditional logic based on script output and return status. ```groovy 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!' } } } } } ``` -------------------------------- ### Defining a Stage with Checkout Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestRegression_example.txt Shows how to define a 'Checkout' stage and perform a Git checkout with specific branch and repository configurations. ```Groovy 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}) ``` -------------------------------- ### Pipeline Library Singleton Wrapper Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Creates a singleton script in the 'vars' directory to instantiate and use a class from the 'src' directory. It injects the script context into the class. ```groovy // vars/hardmath.groovy import com.example.HardMath int complexOperation(int a, int b) { return new HardMath(script: this).complexOperation(a, b) } ``` -------------------------------- ### Mocking Shell Steps with Regular Expressions Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Demonstrates mocking shell steps using regular expressions for flexible script matching. This allows capturing arguments and asserting their values. ```groovy helper.addShMock(~'./build.sh\s--(.*)') { String script, String arg -> assert (arg == 'debug') || (arg == 'release') return [stdout: '', exitValue: 2] } ``` -------------------------------- ### Define and Run Parameters Job Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestParametersJob_parameters.txt Instantiate and run a parameters job. Use this to set up and execute pipeline logic that relies on defined parameters. ```groovy parameters.run() ``` -------------------------------- ### Loading Utility Scripts Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestRegression_example.txt Demonstrates loading external Jenkins pipeline scripts for reuse. ```Groovy exampleJob.load(src/test/jenkins/lib/utils.jenkins) utils.run() ``` ```Groovy exampleJob.load(src/test/jenkins/lib/properties.jenkins) properties.run() ``` -------------------------------- ### Setting Up Default Shell Mocks Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Configures default mocks for `sh` steps using `@BeforeEach`. This includes a catch-all mock for unexpected calls and a mock to ignore `echo` commands. ```groovy @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) } ``` -------------------------------- ### Load Shared Library Dynamically in Pipeline Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Demonstrates loading a shared library named 'commons' in a pipeline script. It shows how to call a singleton method and instantiate a class from the library. ```groovy Object commonsLib = library 'commons' // Assume that `sayHello` is a singleton in the `commons` library sayHello 'World' // Create an instance of a class in the `commons` library Object utils = net.courtanet.jenkins.Utils.new() ``` -------------------------------- ### Configure ProjectSource Retriever Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Use `projectSource()` to load library files directly from the project root. This is useful when testing the library itself. Calling `projectSource()` with no arguments looks for files in the project root. ```groovy import static com.lesfurets.jenkins.unit.global.lib.ProjectSource.projectSource class TestCase extends BasePipelineTest { @Override @BeforeEach void setUp() { super.setUp() Object library = library() .name('commons') .defaultVersion('') .allowOverride(true) .implicit(true) .targetPath('') .retriever(projectSource()) .build() helper.registerSharedLibrary(library) } } ``` -------------------------------- ### Job Execution and Node Allocation Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestRegression_example.txt Illustrates executing a job and allocating it to a specific node using a closure. ```Groovy exampleJob.execute() exampleJob.node(groovy.lang.Closure) ``` -------------------------------- ### Simulate withCredentials.run() in Jenkins Pipeline Unit Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestWithCredentialsJob_withCredentials.txt This snippet demonstrates the basic structure for simulating the withCredentials step within a Jenkins Pipeline Unit test. It sets up the context for credential handling. ```groovy withCredentials.run() withCredentials.node(groovy.lang.Closure) withCredentials.usernamePassword({credentialsId=my_cred_id, usernameVariable=user, passwordVariable=pass}) withCredentials.string({credentialsId=docker_cred, variable=docker_pass}) withCredentials.string({credentialsId=ssh_cred, variable=ssh_pass}) withCredentials.withCredentials([[user, pass], docker_pass, ssh_pass], groovy.lang.Closure) withCredentials.echo(User/Pass = user/pass) withCredentials.echo(Docker = docker_pass) withCredentials.echo(SSH = ssh_pass) withCredentials.usernamePassword({credentialsId=my_cred_id, usernameVariable=user, passwordVariable=pass}) withCredentials.string({credentialsId=docker_cred, variable=docker_pass}) withCredentials.string({credentialsId=ssh_cred, variable=ssh_pass}) withCredentials.withCredentials([[user, pass], docker_pass, ssh_pass], groovy.lang.Closure) withCredentials.echo(Nested User/Pass = user/pass) withCredentials.echo(Nested Docker = docker_pass) withCredentials.echo(Nested SSH = ssh_pass) withCredentials.echo(Restored User/Pass = user/pass) withCredentials.echo(Restored Docker = docker_pass) withCredentials.echo(Restored SSH = ssh_pass) withCredentials.echo(Cleared User/Pass = null/null) withCredentials.echo(Cleared Docker = null) withCredentials.echo(Cleared SSH = null) ``` -------------------------------- ### GitLab Builds Stage with Sub-Stages Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestRegression_example.txt Illustrates a 'gitlabBuilds' stage containing 'build' and 'test' sub-stages, each with its own commit status and commands. ```Groovy exampleJob.gitlabBuilds({builds=[build, test]}, groovy.lang.Closure) exampleJob.stage(build, groovy.lang.Closure) exampleJob.gitlabCommitStatus(build, groovy.lang.Closure) exampleJob.sleep(20) exampleJob.sh(mvn clean package -DskipTests -DgitRevision=bcc19744) ``` ```Groovy exampleJob.stage(test, groovy.lang.Closure) exampleJob.gitlabCommitStatus(test, groovy.lang.Closure) exampleJob.println(value) exampleJob.sh(mvn verify -DgitRevision=bcc19744) ``` -------------------------------- ### Configure Test Environment for Scripted Pipelines Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Extend BasePipelineTest to customize script roots, script extension, and base script root for testing scripted pipelines. Ensure super.setUp() is called. ```groovy class TestExampleJob extends BasePipelineTest { @Override @BeforeEach void setUp() { baseScriptRoot = 'jenkinsJobs' scriptRoots += 'src/main/groovy' scriptExtension = 'pipeline' super.setUp() } } ``` -------------------------------- ### Checkout Release Tag Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/RELEASE.md Checks out the specific Git tag corresponding to the released version. ```bash git checkout v1.7 ``` -------------------------------- ### Jenkinsfile for Status Checking Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A simple Jenkinsfile that clones a repository and executes a `make` command. This is used to demonstrate how to check pipeline status when a step fails. ```groovy // Jenkinsfile node() { git 'some_repo_url' sh 'make' } ``` -------------------------------- ### Checkout Release Branch Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/RELEASE.md Fetches the latest changes and checks out the master branch for release preparation. ```bash git fetch git checkout -B master origin/master ``` -------------------------------- ### Configure LocalSource Retriever Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Use `localSource('/var/tmp/')` to load library files from a specified local directory. This is useful for verifying library integration with pipelines using pre-copied library files. ```groovy import static com.lesfurets.jenkins.unit.global.lib.LocalSource.localSource class TestCase extends BasePipelineTest { @Override @BeforeEach void setUp() { super.setUp() Object library = library() .name('commons') .defaultVersion('master') .allowOverride(true) .implicit(false) .targetPath('') .retriever(localSource('/var/tmp/')) .build() helper.registerSharedLibrary(library) } } ``` -------------------------------- ### Trigger Gradle Release Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/RELEASE.md Initiates the release process using Gradle. The command prompts for the new version and the next development version. ```bash ./gradlew release ``` -------------------------------- ### Basic Job Execution and Sleep Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestRegression_example.txt Shows basic job execution and pausing for a specified duration. ```Groovy exampleJob.run() exampleJob.sleep(20) ``` -------------------------------- ### Unit Test for Debian Build Success Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A unit test using `PipelineTestHelper` to mock `sh` steps for a Debian build. It verifies a successful build scenario, including dynamic execution of a script via a closure. ```groovy @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() } ``` -------------------------------- ### Echo Parameter Value Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestWithCredentialsAndParametersJob_withCredentialsAndParameters.txt Demonstrates how to echo the value of a string parameter within the test. This is useful for verifying parameter handling. ```groovy withCredentialsAndParameters.echo('myStringParam' value is default: my default value) ``` -------------------------------- ### Set Job Parameters and Properties Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestWithCredentialsAndParametersJob_withCredentialsAndParameters.txt Configure the parameters and properties for a Jenkins job during a pipeline unit test. This allows for setting up the job's execution context. ```groovy withCredentialsAndParameters.parameters([null, null]) ``` ```groovy withCredentialsAndParameters.properties([null]) ``` -------------------------------- ### Publish Artifacts with Artifactory Credentials Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/RELEASE.md Publishes build artifacts to the Jenkins Artifactory repository. Requires setting up ~/.gradle/gradle.properties with artifactory_user and artifactory_password. ```bash # create ~/.gradle/gradle.properties with the following content: # artifactory_user=jenkins.io_username # artifactory_password=s3cr3t ./gradlew artifactoryPublish ``` -------------------------------- ### Handle Null Parameters and Properties Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestParametersJob_parameters.txt Add null values to parameters and properties lists. This might be used for optional or unset configurations. ```groovy parameters.parameters([null, null]) ``` ```groovy parameters.properties([null]) ``` -------------------------------- ### Define String Parameter with Default Value Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestParametersJob_parameters.txt Define a string parameter with a default value and a description. This is useful for parameters that have a common or expected input. ```groovy parameters.string({name=myStringParam, defaultValue=my default value, description=My string typed parameter}) ``` -------------------------------- ### Empty Pipeline Script for Testing Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A minimal Groovy script used as a placeholder for the Jenkins script context during testing. It simply returns the script context itself. ```groovy // test/resources/EmptyPipeline.groovy return this ``` -------------------------------- ### Analyzing Shell Command Execution Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Verifies that a specific shell command, like `mvn verify`, was executed during the pipeline run by inspecting the `callStack`. ```groovy @Test void shouldExecuteWithoutErrors() { runScript('Jenkinsfile') assertJobStatusSuccess() assertThat(helper.callStack.findAll { call -> call.methodName == 'sh' }.any { call -> callArgsToString(call).contains('mvn verify') }).isTrue() } ``` -------------------------------- ### Unit Test for Debian Build Unstable Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A unit test mocking `sh` steps to simulate an unstable Debian build scenario where the test script returns a non-zero exit code. ```groovy @Test void debianBuildUnstable() { helper.addShMock('uname', 'Debian', 0) helper.addShMock('./build.sh --release', '', 0) helper.addShMock('./test.sh', '', 1) runScript('Jenkinsfile') assertJobStatusUnstable() } ``` -------------------------------- ### Test Pipeline for Non-Regression Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Compares the current callstack of a job to a reference file. Set the JVM argument `-Dpipeline.stack.write=true` to update the reference file. ```groovy import org.junit.Test class MyPipelineTest extends BaseRegressionTest { @Test void testPipelineNonRegression() { loadScript('job/exampleJob.jenkins').execute() super.testNonRegression('example') } } ``` -------------------------------- ### Define Boolean and String Parameters Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestWithCredentialsAndParametersJob_withCredentialsAndParameters.txt Use this to define boolean and string parameters for a Jenkins job within a pipeline unit test. Specify name, description, and default values as needed. ```groovy withCredentialsAndParameters.booleanParam({name=myBooleanParam, description=My boolean typed parameter}) ``` ```groovy withCredentialsAndParameters.string({name=myStringParam, defaultValue=my default value, description=My string typed parameter}) ``` -------------------------------- ### Jenkinsfile for Exception Testing Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A minimal Jenkinsfile designed to throw an `IllegalArgumentException` to test exception handling in unit tests. ```groovy // Jenkinsfile node { throw new IllegalArgumentException('oh no!') } ``` -------------------------------- ### Use Defined Credentials in Pipeline Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestWithCredentialsAndParametersJob_withCredentialsAndParameters.txt Simulate the use of defined credentials within the pipeline script during a test. This ensures that credential variables are correctly injected and accessible. ```groovy withCredentialsAndParameters.withCredentials([GITLAB_API_TOKEN], groovy.lang.Closure) ``` -------------------------------- ### Add Gradle Dependency for JenkinsPipelineUnit Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Add this Groovy configuration to your Gradle project's build.gradle file to include JenkinsPipelineUnit as a test dependency. Make sure to configure the necessary repositories. ```groovy repositories { maven { url 'https://repo.jenkins-ci.org/releases/' } ... } dependencies { testImplementation "com.lesfurets:jenkins-pipeline-unit:1.9" ... } ``` -------------------------------- ### Echo Credential Variable Value Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestWithCredentialsAndParametersJob_withCredentialsAndParameters.txt Verify that the credential variable is accessible and holds the expected value after being defined and used in the pipeline during a test. ```groovy withCredentialsAndParameters.echo('my-gitlab-api-token' credential variable value: GITLAB_API_TOKEN) ``` -------------------------------- ### Define Credentials for a Job Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestWithCredentialsAndParametersJob_withCredentialsAndParameters.txt Configure a specific credential, like a GitLab API token, to be used by the Jenkins job during the test. This involves setting the credentials ID and the environment variable name. ```groovy withCredentialsAndParameters.string({credentialsId=my-gitlab-api-token, variable=GITLAB_API_TOKEN}) ``` -------------------------------- ### Add Maven Dependency for JenkinsPipelineUnit Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Include this XML configuration in your Maven project's pom.xml to add JenkinsPipelineUnit as a test dependency. Ensure your repositories include the jenkins-ci-releases repository. ```xml jenkins-ci-releases https://repo.jenkins-ci.org/releases/ ... com.lesfurets jenkins-pipeline-unit 1.9 test ... ``` -------------------------------- ### Execute Inline Script in Test Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Loads and executes a script directly within a test case using `loadInlineScript`. Inline scripts cannot be debugged with breakpoints. ```groovy @Test void testSomeScript() { Object script = loadInlineScript(''' node { stage('Build') { sh 'make' } } ''') script.execute() printCallStack() assertJobStatusSuccess() } ``` -------------------------------- ### Echo String Parameter Value Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestParametersJob_parameters.txt Echo the value of a string parameter within the pipeline. This is useful for debugging or confirming parameter values. ```groovy parameters.echo('myStringParam' value is default: my default value) ``` -------------------------------- ### Unit Test for Checking Pipeline Status Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Tests a Jenkinsfile by mocking the `sh` step to set the build result to `FAILURE` when `make` is called. It then asserts that the job status is indeed failure. ```groovy @Test void checkBuildStatus() { helper.registerAllowedMethod('sh', [String]) { cmd -> if (cmd == 'make') { binding.getVariable('currentBuild').result = 'FAILURE' } } runScript('Jenkinsfile') assertJobStatusFailure() } ``` -------------------------------- ### Test Case for Shared Library Integration Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md This Groovy test case uses JenkinsPipelineUnit to test a pipeline that depends on a shared library. It configures the shared library using a fluent API and registers it with the test helper. ```groovy // You need to import the class first import static com.lesfurets.jenkins.unit.global.lib.LibraryConfiguration.library class TestCase extends BasePipelineTest { @Test void testLibrary() { Object library = library() .name('commons') .retriever(gitSource('git@example.com:libs/commons.git')) .targetPath('path/to/clone') .defaultVersion("master") .allowOverride(true) .implicit(false) .build() helper.registerSharedLibrary(library) runScript('job/library/exampleJob.jenkins') printCallStack() } } ``` -------------------------------- ### Define Library Class and Global Variable Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Defines a `Monster` class and a `monster` global variable in a Jenkins shared library. The global variable takes an instance of the `Monster` class as an argument. ```groovy // src/com/example/Monster.groovy package com.example class Monster { String moniker Monster(String moniker) { this.moniker = moniker } } ``` ```groovy // vars/monster.groovy import com.example.Monster void call(Monster monster) { println "${monster.moniker} is always very scary" } ``` -------------------------------- ### Unit Test for Jenkins Pipeline Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A Groovy unit test class extending BasePipelineTest to test a Jenkins pipeline script. It loads the script and executes it, then prints the call stack. ```groovy import com.lesfurets.jenkins.unit.BasePipelineTest class TestExampleJob extends BasePipelineTest { @Test void shouldExecuteWithoutErrors() { loadScript('job/exampleJob.jenkins').execute() printCallStack() } } ``` -------------------------------- ### Pipeline Library Unit Test for Complex Operation Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A JUnit test class for a pipeline library component using JenkinsPipelineUnit. It sets up the test environment and asserts the correctness of the complex operation. ```groovy // test/com/example/HardMathTest.groovy package com.example import static org.junit.jupiter.api.Assertions.assertEquals import com.lesfurets.jenkins.unit.BasePipelineTest import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class HardMathTest extends BasePipelineTest { Object script = null @Override @BeforeEach void setUp() { super.setUp() this.script = loadScript('test/resources/EmptyPipeline.groovy') } @Test void testComplexOperation() { int result = new HardMath(script: script).complexOperation(1, 3) assertEquals(4, result) } } ``` -------------------------------- ### Pipeline Library Class for Complex Operations Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Defines a Groovy class within a pipeline library to encapsulate complex logic. It requires a script context for pipeline steps like 'echo'. ```groovy // src/com/example/HardMath.groovy package com.example class HardMath implements Serializable { // Jenkinsfile script context, note that all pipeline steps must use this context Object script = null int complexOperation(int a, int b) { // Note the script context is required for `echo`, as it is a pipeline step script.echo "Adding ${a} to ${b}" return a + b } } ``` -------------------------------- ### JUnit 5 Test for Exception Verification Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A JUnit 5 test class that uses `assertThrows` to verify that a specific exception is thrown when running the Jenkinsfile. ```groovy import static org.junit.jupiter.api.Assertions.assertThrows class TestCase extends BasePipelineTest { @Test void verifyException() { assertThrows(IllegalArgumentException) { runScript('Jenkinsfile') } } } ``` -------------------------------- ### Mocking Jenkins Pipeline Methods Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Register custom interceptors to mock pipeline methods like 'sh', 'timeout', 'timestamps', and custom methods. This is useful for controlling the behavior of Jenkins commands during tests. Ensure you provide a method signature and a callback. ```groovy 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}'" } } } ``` -------------------------------- ### Define Boolean Parameter Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/src/test/resources/callstacks/TestParametersJob_parameters.txt Define a boolean parameter for a Jenkins pipeline. Specify the name and a descriptive text for the parameter. ```groovy parameters.booleanParam({name=myBooleanParam, description=My boolean typed parameter}) ``` -------------------------------- ### JUnit 4 Test for Exception Verification Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md A JUnit 4 test class that uses the `@Test(expected = ...)` annotation to verify that a specific exception is thrown when running the Jenkinsfile. ```groovy class TestCase extends BasePipelineTest { @Test(expected = IllegalArgumentException) void verifyException() { runScript('Jenkinsfile') } } ``` -------------------------------- ### Disable Argument Cloning for Callstack Registration Source: https://github.com/jenkinsci/jenkinspipelineunit/blob/master/README.md Set this property to `false` to retain direct references to variables in the callstack, useful for validating complex or immutable arguments. ```groovy helper.cloneArgsOnMethodCallRegistration = false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.