├── .gitignore ├── Jenkinsfile ├── LICENSE.txt ├── README.md ├── build.gradle ├── exampleJobs ├── globalVariable │ └── Jenkinsfile └── parallel │ └── Jenkinsfile ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── pipelineLibrary └── vars │ ├── helloMessage.groovy │ └── stepWithParams.groovy └── pipelineTests └── groovy ├── testSupport ├── PipelineSpockTestBase.groovy ├── PipelineTestHelper.groovy └── WhenExitException.groovy └── tests ├── callstacks ├── GlobalVariableJobTestSpec_Jenkinsfile_should_complete_with_success.txt ├── JenkinsfileTestSpec_Jenkinsfile_Should_Run_Gradle_validate_false_gradle_build test.txt ├── JenkinsfileTestSpec_Jenkinsfile_Should_Run_Gradle_validate_null_gradle_null.txt ├── JenkinsfileTestSpec_Jenkinsfile_Should_Run_Gradle_validate_true_gradle_test.txt ├── ParallelJobTestSpec_Parallel_Jenkinsfile_should_complete_with_success.txt └── stepWithParamsTestSpec_should_echo_values.txt ├── job ├── JenkinsfileTestSpec.groovy └── exampleJobs │ ├── globalVariable │ └── GlobalVariableJobTestSpec.groovy │ └── parallel │ └── ParallelJobTestSpec.groovy └── library ├── helloMessageTestSpec.groovy └── stepWithParamsTestSpec.groovy /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | .gradle/ 3 | .idea/ 4 | *.iml -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | /** 2 | * Helper to validate a pipeline. 3 | * 4 | * @param pipelineFile - Pipeline file to validate 5 | * @return An error count 6 | */ 7 | int validatePipeline(String pipelineFile) { 8 | Boolean valid = validateDeclarativePipeline(pipelineFile) 9 | if(!valid) { 10 | echo "The file ${pipelineFile} is not a valid declarative pipeline" 11 | return 1 12 | } 13 | return 0 14 | } 15 | 16 | /** 17 | * A CI pipeline for Jenkins pipeline jobs. It will validate the jobs and run the unit tests with Gradle 18 | */ 19 | pipeline { 20 | 21 | agent any 22 | 23 | parameters { 24 | booleanParam(name: 'VALIDATE', defaultValue: true, description: 'Whether to run validation stage') 25 | string(name: 'GRADLE_TASKS_OPTIONS', defaultValue: 'clean build test -i', description: 'Tasks and options for the gradle command') 26 | } 27 | 28 | options { 29 | buildDiscarder(logRotator(numToKeepStr: '10')) 30 | timestamps() 31 | } 32 | 33 | triggers { 34 | pollSCM('*/5 * * * *') 35 | } 36 | 37 | stages { 38 | 39 | stage('Checkout') { 40 | steps { 41 | deleteDir() 42 | checkout scm 43 | } 44 | } 45 | 46 | stage('validate') { 47 | 48 | when { expression { return params.VALIDATE } } 49 | 50 | steps { 51 | script { 52 | 53 | int validationErrors = 0 54 | 55 | // Validate the example jobs. This will only work for declarative 56 | validationErrors += validatePipeline('exampleJobs/parallel/Jenkinsfile') 57 | validationErrors += validatePipeline('exampleJobs/globalVariable/Jenkinsfile') 58 | 59 | // Validate this job 60 | validationErrors += validatePipeline('Jenkinsfile') 61 | 62 | // Fail here if any not valid - need to fix this first 63 | if(validationErrors > 0) { 64 | error("One or more of the pipeline files are not valid. Validation errors: ${validationErrors}") 65 | } 66 | } 67 | } 68 | } 69 | 70 | stage('build') { 71 | 72 | steps { 73 | withEnv(["GRADLE_HOME=${tool name: 'GRADLE_3', type: 'hudson.plugins.gradle.GradleInstallation'}"]) { 74 | withEnv(["PATH=${env.PATH}:${env.GRADLE_HOME}/bin"]) { 75 | 76 | // Checking the env 77 | echo "GRADLE_HOME=${env.GRADLE_HOME}" 78 | echo "PATH=${env.PATH}" 79 | 80 | sh "gradle ${params.GRADLE_TASKS_OPTIONS}" 81 | } 82 | } 83 | } 84 | } 85 | 86 | 87 | } 88 | 89 | post { 90 | always { 91 | echo 'pipeline unit tests completed - recording JUnit results' 92 | junit 'build/test-results/**/*.xml' 93 | } 94 | 95 | success { 96 | echo 'pipeline unit tests PASSED' 97 | } 98 | 99 | failure { 100 | echo 'pipeline unit tests FAILED' 101 | } 102 | 103 | changed { 104 | echo 'pipeline unit tests results have CHANGED' 105 | } 106 | 107 | unstable { 108 | echo 'pipeline unit tests have gone UNSTABLE' 109 | } 110 | } 111 | } -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pipelineUnit 2 | 3 | This project demonstrates how to write unit tests for Jenkins pipeline code including declarative pipelines, scripted pipelines and shared library code under the /vars area. The framework does not strictly validate the pipeline syntax but it will emulate the pipeline using the JenkinsPipelineUnit framework and can validate any groovy script sections in the pipeline and logic. It may not be complete for all pipeline syntax. 4 | 5 | It is using Spock, Gradle and Groovy and the JenkinsPipelineUnit framework available here: https://github.com/lesfurets/JenkinsPipelineUnit 6 | 7 | The unit test is actually testing the Jenkinsfile that builds this Gradle project on Jenkins. 8 | 9 | The below is an example of a unit test output from Jenkins console: 10 | 11 | ``` 12 | tests.job.JenkinsfileTestSpec > Jenkinsfile should run gradle tests with expected command line STANDARD_OUT 13 | post failure skipped as not FAILURE 14 | post unstable skipped as SUCCESS 15 | >>>>>> pipeline call stack ------------------------------------------------- 16 | Jenkinsfile.run() 17 | Jenkinsfile.pipeline(groovy.lang.Closure) 18 | Jenkinsfile.agent(groovy.lang.Closure) 19 | Jenkinsfile.options(groovy.lang.Closure) 20 | Jenkinsfile.logRotator({numToKeepStr=10}) 21 | Jenkinsfile.buildDiscarder(null) 22 | Jenkinsfile.timestamps() 23 | Jenkinsfile.triggers(groovy.lang.Closure) 24 | Jenkinsfile.pollSCM(*/5 * * * *) 25 | Jenkinsfile.stages(groovy.lang.Closure) 26 | Jenkinsfile.stage(Checkout, groovy.lang.Closure) 27 | Jenkinsfile.steps(groovy.lang.Closure) 28 | Jenkinsfile.deleteDir() 29 | Jenkinsfile.checkout(groovy.lang.Closure) 30 | Jenkinsfile.stage(build, groovy.lang.Closure) 31 | Jenkinsfile.steps(groovy.lang.Closure) 32 | Jenkinsfile.tool({name=GRADLE_3, type=hudson.plugins.gradle.GradleInstallation}) 33 | Jenkinsfile.withEnv([GRADLE_HOME=GRADLE_3_HOME], groovy.lang.Closure) 34 | Jenkinsfile.withEnv([PATH=/some/path:GRADLE_3_HOME/bin], groovy.lang.Closure) 35 | Jenkinsfile.echo(GRADLE_HOME=GRADLE_3_HOME) 36 | Jenkinsfile.echo(PATH=/some/path:GRADLE_3_HOME/bin) 37 | Jenkinsfile.sh(gradle clean build test -i) 38 | Jenkinsfile.stage(validate, groovy.lang.Closure) 39 | Jenkinsfile.steps(groovy.lang.Closure) 40 | Jenkinsfile.echo(TODO: syntactic validation of Jenkinsfiles) 41 | Jenkinsfile.post(groovy.lang.Closure) 42 | Jenkinsfile.always(groovy.lang.Closure) 43 | Jenkinsfile.echo(pipeline unit tests completed) 44 | Jenkinsfile.success(groovy.lang.Closure) 45 | Jenkinsfile.echo(pipeline unit tests PASSED) 46 | Jenkinsfile.failure(groovy.lang.Closure) 47 | Jenkinsfile.changed(groovy.lang.Closure) 48 | Jenkinsfile.echo(pipeline unit tests results have CHANGED) 49 | Jenkinsfile.unstable(groovy.lang.Closure) 50 | Jenkinsfile.execute() 51 | ``` 52 | 53 | 54 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'groovy' 2 | 3 | repositories { 4 | mavenCentral() 5 | } 6 | 7 | dependencies { 8 | compile 'org.codehaus.groovy:groovy-all:2.4.11' 9 | 10 | /** 11 | * JenkinsPipelineUnit for testing pipelines from: 12 | * https://github.com/lesfurets/JenkinsPipelineUnit 13 | */ 14 | testCompile 'com.lesfurets:jenkins-pipeline-unit:1.1' 15 | 16 | /** 17 | * For Spock unit tests 18 | */ 19 | testCompile 'org.spockframework:spock-core:1.1-groovy-2.4' 20 | testCompile 'cglib:cglib-nodep:3.2.2' 21 | testCompile 'org.objenesis:objenesis:1.2' 22 | testCompile 'org.assertj:assertj-core:3.7.0' 23 | 24 | } 25 | 26 | test { 27 | systemProperty "pipeline.stack.write", project.getProperty("pipeline.stack.write") 28 | } 29 | 30 | sourceSets { 31 | 32 | test { 33 | groovy { 34 | srcDirs= ['pipelineTests/groovy'] 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /exampleJobs/globalVariable/Jenkinsfile: -------------------------------------------------------------------------------- 1 | /** 2 | * This is a pipeline to analyse an issue I had with JenkinsPipelineUnit 3 | * around variables recorded in the callstack. 4 | * 5 | * With JenkinsPipelineUnit v1.1 the callstack is like this: 6 | * 7 | * Jenkinsfile.run() 8 | * Jenkinsfile.pipeline(groovy.lang.Closure) 9 | * Jenkinsfile.agent(groovy.lang.Closure) 10 | * Jenkinsfile.stages(groovy.lang.Closure) 11 | * Jenkinsfile.stage(One, groovy.lang.Closure) 12 | * Jenkinsfile.steps(groovy.lang.Closure) 13 | * Jenkinsfile.script(groovy.lang.Closure) 14 | * Jenkinsfile.doWithProperties({PROP_2=VAL_2, PROP_1=VAL_1}) 15 | * Jenkinsfile.echo(props = {PROP_1=VAL_1}) 16 | * Jenkinsfile.stage(Two, groovy.lang.Closure) 17 | * Jenkinsfile.steps(groovy.lang.Closure) 18 | * Jenkinsfile.script(groovy.lang.Closure) 19 | * Jenkinsfile.doWithProperties({PROP_2=VAL_2, PROP_1=VAL_1}) 20 | * Jenkinsfile.echo(props = {PROP_2=VAL_2, PROP_1=VAL_1}) 21 | * 22 | * The props object passed to doWithProperties() in the first stage is not shown as passed! 23 | * 24 | */ 25 | 26 | // A properties object global in the pipeline (this does work., use it a lot.) 27 | Properties props = new Properties() 28 | 29 | // Simple pipeline 30 | pipeline { 31 | 32 | agent none 33 | 34 | stages { 35 | 36 | // In Stage One add one value to the property and call a library step with it 37 | stage('One') { 38 | steps { 39 | script { 40 | // Add a value to the property 41 | props.setProperty('PROP_1', 'VAL_1') 42 | 43 | // Call a custom library step with the properties containing 1 value 44 | doWithProperties(props) 45 | 46 | // Echo it 47 | echo "props = ${props.toString()}" 48 | } 49 | 50 | } 51 | } 52 | 53 | // In Stage Two add another value to the property and call a library step with it, it should have 2 values 54 | stage('Two') { 55 | steps { 56 | script { 57 | // Add a value to the property 58 | props.setProperty('PROP_2', 'VAL_2') 59 | 60 | // Call a custom library step with the properties containing 2 values 61 | doWithProperties(props) 62 | 63 | // Echo it 64 | echo "props = ${props.toString()}" 65 | } 66 | } 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /exampleJobs/parallel/Jenkinsfile: -------------------------------------------------------------------------------- 1 | /** 2 | * A pipeline to demo running parallel branches using both a dynamic and static coding method. 3 | * 4 | * In the Blue Ocean GUI, a dynamic construction might be better so as not to show parallel 5 | * branches that are skipped in the graphic representation of a run. 6 | */ 7 | 8 | /** 9 | * A map of parallel runs built dynamically in the job. It is a map of closures 10 | */ 11 | def parallelCodeMap = [:] 12 | 13 | /** 14 | * Declarative pipeline 15 | */ 16 | pipeline { 17 | 18 | agent any 19 | 20 | stages { 21 | 22 | stage('Setup') { 23 | 24 | steps { 25 | 26 | // Set up the dynamic parallel code map 27 | script { 28 | 29 | parallelCodeMap['foo'] = { 30 | echo "Running foo branch.." 31 | } 32 | 33 | parallelCodeMap['bar'] = { 34 | echo "Running bar branch..." 35 | } 36 | } 37 | } 38 | } 39 | 40 | stage('Dynamic') { 41 | steps { 42 | script { 43 | parallel( parallelCodeMap ) 44 | } 45 | } 46 | } 47 | 48 | // Pre pipeline v1.2 do it this way, awkward syntax 49 | stage('Static Old Way') { 50 | steps { 51 | parallel ( 52 | 'branch_1' : { 53 | echo "Running static branch 1" 54 | }, 55 | 'branch_2' : { 56 | echo "Running static branch 2" 57 | }, 58 | ) 59 | } 60 | } 61 | 62 | // From pipeline v1.2 do it this way : requires Pipeline Model Definition Plugin v1.2+ 63 | stage('Static New Way') { 64 | 65 | // Support for full parallel stages. Nice. 66 | parallel { 67 | 68 | stage('Stage 1') { 69 | steps { 70 | echo "Running pipeline v1.2 static stage 1" 71 | } 72 | } 73 | 74 | stage('Stage 2') { 75 | steps { 76 | echo "Running pipeline v1.2 static stage 2" 77 | } 78 | } 79 | 80 | stage('Stage Skipped') { 81 | 82 | when { expression { false } } 83 | 84 | steps { 85 | echo "pipeline v1.2 static stage will be skipped" 86 | } 87 | } 88 | } 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Gradle properties for the build 2 | 3 | # Set this true to write callstacks, do not commit like that.. 4 | pipeline.stack.write=false -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/macg33zr/pipelineUnit/0dcd54f46e2733c141da0ce6fb5158f010fee645/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /pipelineLibrary/vars/helloMessage.groovy: -------------------------------------------------------------------------------- 1 | /** 2 | * Something like this in the job: 3 | * 4 | * helloTest { 5 | * message = "hello this is a test" 6 | * } 7 | * 8 | */ 9 | def call(body) { 10 | 11 | def config = [:] 12 | body.resolveStrategy = Closure.DELEGATE_FIRST 13 | body.delegate = config 14 | body() 15 | 16 | node { 17 | echo "hello test message: ${config.message}" 18 | } 19 | } -------------------------------------------------------------------------------- /pipelineLibrary/vars/stepWithParams.groovy: -------------------------------------------------------------------------------- 1 | /** 2 | * Example of a library step with parameters 3 | * 4 | * In the job you can call it like this: 5 | * 6 | * steps { 7 | * stepWithParams("param1 value", "param2 value", 12345) 8 | * } 9 | * 10 | * To mock it in a Unit test of a pipeline add code like this: 11 | * 12 | * helper.registerAllowedMethod('stepWithParams', [String.class, String.class, Integer.class], null) 13 | * 14 | */ 15 | 16 | def call(String param1, String param2, Integer param3) { 17 | 18 | echo "param1 = ${param1}" 19 | echo "param2 = ${param2}" 20 | echo "param3 = ${param3}" 21 | } -------------------------------------------------------------------------------- /pipelineTests/groovy/testSupport/PipelineSpockTestBase.groovy: -------------------------------------------------------------------------------- 1 | package testSupport 2 | 3 | import com.lesfurets.jenkins.unit.RegressionTest 4 | import spock.lang.Specification 5 | 6 | /** 7 | * A base class for Spock testing using the pipeline helper 8 | */ 9 | class PipelineSpockTestBase extends Specification implements RegressionTest { 10 | 11 | /** 12 | * Delegate to the test helper 13 | */ 14 | @Delegate PipelineTestHelper pipelineTestHelper 15 | 16 | /** 17 | * Do the common setup 18 | */ 19 | def setup() { 20 | 21 | // Set callstacks path for RegressionTest 22 | callStackPath = 'pipelineTests/groovy/tests/callstacks/' 23 | 24 | // Create and config the helper 25 | pipelineTestHelper = new PipelineTestHelper() 26 | pipelineTestHelper.setUp() 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /pipelineTests/groovy/testSupport/PipelineTestHelper.groovy: -------------------------------------------------------------------------------- 1 | package testSupport 2 | 3 | import com.lesfurets.jenkins.unit.BasePipelineTest 4 | import static com.lesfurets.jenkins.unit.MethodSignature.method 5 | 6 | 7 | class PipelineTestHelper extends BasePipelineTest { 8 | 9 | /** 10 | * Override the setup for our purposes 11 | */ 12 | @Override 13 | void setUp() { 14 | 15 | // Scripts (Jenkinsfiles etc) loaded from root of project directory and have no extension by default 16 | helper.scriptRoots = [''] 17 | helper.scriptExtension = '' 18 | 19 | // Add support to the helper to unregister a method 20 | helper.metaClass.unRegisterAllowedMethod = { String name, List args -> 21 | allowedMethodCallbacks.remove(method(name, args.toArray(new Class[args.size()]))) 22 | } 23 | 24 | // Setup the parent stuff 25 | super.setUp() 26 | 27 | // Declaring all my stuff 28 | registerDeclarativeMethods() 29 | registerScriptedMethods() 30 | setJobVariables() 31 | } 32 | 33 | /** 34 | * Declarative pipeline methods not in the base 35 | * 36 | * See here: 37 | * https://www.cloudbees.com/sites/default/files/declarative-pipeline-refcard.pdf 38 | */ 39 | void registerDeclarativeMethods() { 40 | 41 | // For execution of the pipeline 42 | helper.registerAllowedMethod('execute', [], {}) 43 | helper.registerAllowedMethod('pipeline', [Closure.class], null) 44 | helper.registerAllowedMethod('options', [Closure.class], null) 45 | 46 | // Handle endvironment section adding the env vars 47 | helper.registerAllowedMethod('environment', [Closure.class], { Closure c -> 48 | 49 | def envBefore = [env: binding.getVariable('env')] 50 | println "Env section - original env vars: ${envBefore.toString()}" 51 | c.resolveStrategy = Closure.DELEGATE_FIRST 52 | c.delegate = envBefore 53 | c() 54 | 55 | def envNew = envBefore.env 56 | envBefore.each { k, v -> 57 | if (k != 'env') { 58 | envNew["$k"] = v 59 | } 60 | 61 | } 62 | println "Env section - env vars set to: ${envNew.toString()}" 63 | binding.setVariable('env', envNew) 64 | }) 65 | 66 | // Handle parameters section adding the default params 67 | helper.registerAllowedMethod('parameters', [Closure.class], { Closure parametersBody -> 68 | 69 | // Register the contained elements 70 | helper.registerAllowedMethod('string', [Map.class], { Map stringParam -> 71 | 72 | // Add the param default for a string 73 | addParam(stringParam.name, stringParam.defaultValue) 74 | 75 | }) 76 | helper.registerAllowedMethod('booleanParam', [Map.class], { Map boolParam -> 77 | // Add the param default for a string 78 | addParam(boolParam.name, boolParam.defaultValue.toString().toBoolean()) 79 | }) 80 | 81 | // Run the body closure 82 | def paramsResult = parametersBody() 83 | 84 | // Unregister the contained elements 85 | helper.unRegisterAllowedMethod('string', [Map.class]) 86 | helper.unRegisterAllowedMethod('booleanParam', [Map.class]) 87 | 88 | // Result to higher level. Is this needed? 89 | return paramsResult 90 | }) 91 | 92 | // If any of these need special handling, it needs to be implemented here or in the tests with a closure instead of null 93 | helper.registerAllowedMethod('triggers', [Closure.class], null) 94 | helper.registerAllowedMethod('pollSCM', [String.class], null) 95 | helper.registerAllowedMethod('cron', [String.class], null) 96 | 97 | helper.registerAllowedMethod('agent', [Closure.class], null) 98 | helper.registerAllowedMethod('label', [String.class], null) 99 | helper.registerAllowedMethod('docker', [String.class], null) 100 | helper.registerAllowedMethod('image', [String.class], null) 101 | helper.registerAllowedMethod('args', [String.class], null) 102 | helper.registerAllowedMethod('dockerfile', [Closure.class], null) 103 | helper.registerAllowedMethod('dockerfile', [Boolean.class], null) 104 | 105 | helper.registerAllowedMethod('timestamps', [], null) 106 | helper.registerAllowedMethod('tools', [Closure.class], null) 107 | helper.registerAllowedMethod('stages', [Closure.class], null) 108 | helper.registerAllowedMethod('validateDeclarativePipeline', [String.class], null) 109 | 110 | helper.registerAllowedMethod('parallel', [Closure.class], null) 111 | 112 | /** 113 | * Handling of a stage skipping execution in tests due to failure, abort, when 114 | */ 115 | helper.registerAllowedMethod('stage', [String.class, Closure.class], { String stgName, Closure body -> 116 | 117 | // Returned from the stage 118 | def stageResult 119 | 120 | // Handling of the when. Only supporting expression right now 121 | helper.registerAllowedMethod('when', [Closure.class], { Closure whenBody -> 122 | 123 | // Handle a when expression 124 | helper.registerAllowedMethod('expression', [Closure.class], { Closure expressionBody -> 125 | 126 | // Run the expression and return any result 127 | def expressionResult = expressionBody() 128 | if(expressionResult == false) { 129 | throw new WhenExitException("Stage '${stgName}' skipped due to when expression returned false") 130 | } 131 | return expressionResult 132 | }) 133 | 134 | // TODO - handle other when clauses in the when 135 | // branch : 'when { branch 'master' }' 136 | // environment : 'when { environment name: 'DEPLOY_TO', value: 'production' }' 137 | 138 | // Run the when body and return any result 139 | return whenBody() 140 | }) 141 | 142 | // Stage is not executed if build fails or aborts 143 | def status = binding.getVariable('currentBuild').result 144 | switch (status) { 145 | case 'FAILURE': 146 | case 'ABORTED': 147 | println "Stage '${stgName}' skipped - job status: '${status}'" 148 | break 149 | default: 150 | 151 | // Run the stage body. A when statement may exit with an exception 152 | try { 153 | stageResult = body() 154 | } 155 | catch (WhenExitException we) { 156 | // The when exited with an exception due to returning false. Swallow it. 157 | println we.getMessage() 158 | } 159 | catch (Exception e) { 160 | // Some sort of error in the pipeline 161 | throw e 162 | } 163 | 164 | } 165 | 166 | // Unregister 167 | helper.unRegisterAllowedMethod('when', [Closure.class.class]) 168 | helper.unRegisterAllowedMethod('expression', [Closure.class]) 169 | 170 | return stageResult 171 | }) 172 | 173 | helper.registerAllowedMethod('steps', [Closure.class], null) 174 | helper.registerAllowedMethod('script', [Closure.class], null) 175 | 176 | helper.registerAllowedMethod('when', [Closure.class], null) 177 | helper.registerAllowedMethod('expression', [Closure.class], null) 178 | helper.registerAllowedMethod('post', [Closure.class], null) 179 | 180 | /** 181 | * Handling the post sections 182 | */ 183 | def postResultEmulator = { String section, Closure c -> 184 | 185 | def currentBuild = binding.getVariable('currentBuild') 186 | 187 | switch (section) { 188 | case 'always': 189 | case 'changed': // How to handle changed? It may happen so just run it.. 190 | return c.call() 191 | break 192 | case 'success': 193 | if(currentBuild.result == 'SUCCESS') { return c.call() } 194 | else { println "post ${section} skipped as not SUCCESS"; return null} 195 | break 196 | case 'unstable': 197 | if(currentBuild.result == 'UNSTABLE') { return c.call() } 198 | else { println "post ${section} skipped as SUCCESS"; return null} 199 | break 200 | case 'failure': 201 | if(currentBuild.result == 'FAILURE') { return c.call() } 202 | else { println "post ${section} skipped as not FAILURE"; return null} 203 | break 204 | case 'aborted': 205 | if(currentBuild.result == 'ABORTED') { return c.call() } 206 | else { println "post ${section} skipped as not ABORTED"; return null} 207 | break 208 | default: 209 | assert false, "post section ${section} is not recognised. Check pipeline syntax." 210 | break 211 | } 212 | } 213 | helper.registerAllowedMethod('always', [Closure.class], postResultEmulator.curry('always')) 214 | helper.registerAllowedMethod('changed', [Closure.class], postResultEmulator.curry('changed')) 215 | helper.registerAllowedMethod('success', [Closure.class], postResultEmulator.curry('success')) 216 | helper.registerAllowedMethod('unstable', [Closure.class], postResultEmulator.curry('unstable')) 217 | helper.registerAllowedMethod('failure', [Closure.class], postResultEmulator.curry('failure')) 218 | } 219 | 220 | /** 221 | * Scripted pipeline methods not in the base 222 | */ 223 | void registerScriptedMethods() { 224 | 225 | /** 226 | * In minutes: 227 | * timeout(20) {} 228 | */ 229 | helper.registerAllowedMethod('timeout', [Integer.class, Closure.class], null) 230 | 231 | helper.registerAllowedMethod('waitUntil', [Closure.class], null) 232 | helper.registerAllowedMethod('writeFile', [Map.class], null) 233 | helper.registerAllowedMethod('build', [Map.class], null) 234 | helper.registerAllowedMethod('tool', [Map.class], { t -> "${t.name}_HOME" }) 235 | 236 | helper.registerAllowedMethod('withCredentials', [Map.class, Closure.class], null) 237 | helper.registerAllowedMethod('withCredentials', [List.class, Closure.class], null) 238 | helper.registerAllowedMethod('usernamePassword', [Map.class], { creds -> return creds }) 239 | 240 | helper.registerAllowedMethod('deleteDir', [], null) 241 | helper.registerAllowedMethod('pwd', [], { 'workspaceDirMocked' }) 242 | 243 | helper.registerAllowedMethod('stash', [Map.class], null) 244 | helper.registerAllowedMethod('unstash', [Map.class], null) 245 | 246 | helper.registerAllowedMethod('checkout', [Closure.class], null) 247 | 248 | helper.registerAllowedMethod('withEnv', [List.class, Closure.class], { List list, Closure c -> 249 | 250 | list.each { 251 | //def env = helper.get 252 | def item = it.split('=') 253 | assert item.size() == 2, "withEnv list does not look right: ${list.toString()}" 254 | addEnvVar(item[0], item[1]) 255 | c.delegate = binding 256 | c.call() 257 | } 258 | }) 259 | 260 | 261 | } 262 | 263 | /** 264 | * Variables that Jenkins expects 265 | */ 266 | void setJobVariables() { 267 | 268 | /** 269 | * Job params - may need to override in specific tests 270 | */ 271 | binding.setVariable('params', [:]) 272 | 273 | /** 274 | * The currentBuild in the job 275 | */ 276 | binding.setVariable('currentBuild', new Expando(result: 'SUCCESS', displayName: 'Build #1234')) 277 | 278 | /** 279 | * agent any 280 | * agent none 281 | */ 282 | binding.setVariable('any', {}) 283 | binding.setVariable('none', {}) 284 | 285 | /** 286 | * checkout scm 287 | */ 288 | binding.setVariable('scm', {}) 289 | 290 | /** 291 | * PATH 292 | */ 293 | binding.setVariable('PATH', '/some/path') 294 | 295 | /** 296 | * Initialize a basic Env passed in from Jenkins - may need to override in specific tests 297 | */ 298 | addEnvVar('BUILD_NUMBER', '1234') 299 | addEnvVar('PATH', '/some/path') 300 | } 301 | 302 | /** 303 | * Prettier print of call stack to whatever taste 304 | */ 305 | @Override 306 | void printCallStack() { 307 | println '>>>>>> pipeline call stack -------------------------------------------------' 308 | super.printCallStack() 309 | println '' 310 | } 311 | 312 | /** 313 | * Helper for adding a params value in tests 314 | */ 315 | void addParam(String name, Object val, Boolean overWrite = false) { 316 | Map params = binding.getVariable('params') as Map 317 | if (params == null) { 318 | params = [:] 319 | binding.setVariable('params', params) 320 | } 321 | if ( (val != null) && (params[name] == null || overWrite)) { 322 | params[name] = val 323 | } 324 | } 325 | 326 | /** 327 | * Helper for adding a environment value in tests 328 | */ 329 | void addEnvVar(String name, String val) { 330 | if (!binding.hasVariable('env')) { 331 | binding.setVariable('env', new Expando(getProperty: { p -> this[p] }, setProperty: { p, v -> this[p] = v })) 332 | } 333 | def env = binding.getVariable('env') as Expando 334 | env[name] = val 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /pipelineTests/groovy/testSupport/WhenExitException.groovy: -------------------------------------------------------------------------------- 1 | package testSupport 2 | 3 | /** 4 | * An exception class to exit a stage due to the when statement 5 | */ 6 | class WhenExitException extends Exception { 7 | 8 | public WhenExitException(String message) 9 | { 10 | super(message); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /pipelineTests/groovy/tests/callstacks/GlobalVariableJobTestSpec_Jenkinsfile_should_complete_with_success.txt: -------------------------------------------------------------------------------- 1 | Jenkinsfile.run() 2 | Jenkinsfile.pipeline(groovy.lang.Closure) 3 | Jenkinsfile.agent(groovy.lang.Closure) 4 | Jenkinsfile.stages(groovy.lang.Closure) 5 | Jenkinsfile.stage(One, groovy.lang.Closure) 6 | Jenkinsfile.steps(groovy.lang.Closure) 7 | Jenkinsfile.script(groovy.lang.Closure) 8 | Jenkinsfile.doWithProperties({PROP_2=VAL_2, PROP_1=VAL_1}) 9 | Jenkinsfile.echo(props = {PROP_1=VAL_1}) 10 | Jenkinsfile.stage(Two, groovy.lang.Closure) 11 | Jenkinsfile.steps(groovy.lang.Closure) 12 | Jenkinsfile.script(groovy.lang.Closure) 13 | Jenkinsfile.doWithProperties({PROP_2=VAL_2, PROP_1=VAL_1}) 14 | Jenkinsfile.echo(props = {PROP_2=VAL_2, PROP_1=VAL_1}) 15 | -------------------------------------------------------------------------------- /pipelineTests/groovy/tests/callstacks/JenkinsfileTestSpec_Jenkinsfile_Should_Run_Gradle_validate_false_gradle_build test.txt: -------------------------------------------------------------------------------- 1 | Jenkinsfile.run() 2 | Jenkinsfile.pipeline(groovy.lang.Closure) 3 | Jenkinsfile.agent(groovy.lang.Closure) 4 | Jenkinsfile.parameters(groovy.lang.Closure) 5 | Jenkinsfile.booleanParam({name=VALIDATE, defaultValue=true, description=Whether to run validation stage}) 6 | Jenkinsfile.string({name=GRADLE_TASKS_OPTIONS, defaultValue=clean build test -i, description=Tasks and options for the gradle command}) 7 | Jenkinsfile.options(groovy.lang.Closure) 8 | Jenkinsfile.logRotator({numToKeepStr=10}) 9 | Jenkinsfile.buildDiscarder(null) 10 | Jenkinsfile.timestamps() 11 | Jenkinsfile.triggers(groovy.lang.Closure) 12 | Jenkinsfile.pollSCM(*/5 * * * *) 13 | Jenkinsfile.stages(groovy.lang.Closure) 14 | Jenkinsfile.stage(Checkout, groovy.lang.Closure) 15 | Jenkinsfile.steps(groovy.lang.Closure) 16 | Jenkinsfile.deleteDir() 17 | Jenkinsfile.checkout(groovy.lang.Closure) 18 | Jenkinsfile.stage(validate, groovy.lang.Closure) 19 | Jenkinsfile.when(groovy.lang.Closure) 20 | Jenkinsfile.expression(groovy.lang.Closure) 21 | Jenkinsfile.stage(build, groovy.lang.Closure) 22 | Jenkinsfile.steps(groovy.lang.Closure) 23 | Jenkinsfile.tool({name=GRADLE_3, type=hudson.plugins.gradle.GradleInstallation}) 24 | Jenkinsfile.withEnv([GRADLE_HOME=GRADLE_3_HOME], groovy.lang.Closure) 25 | Jenkinsfile.withEnv([PATH=/some/path:GRADLE_3_HOME/bin], groovy.lang.Closure) 26 | Jenkinsfile.echo(GRADLE_HOME=GRADLE_3_HOME) 27 | Jenkinsfile.echo(PATH=/some/path:GRADLE_3_HOME/bin) 28 | Jenkinsfile.sh(gradle build test) 29 | Jenkinsfile.post(groovy.lang.Closure) 30 | Jenkinsfile.always(groovy.lang.Closure) 31 | Jenkinsfile.echo(pipeline unit tests completed - recording JUnit results) 32 | Jenkinsfile.junit(build/test-results/**/*.xml) 33 | Jenkinsfile.success(groovy.lang.Closure) 34 | Jenkinsfile.echo(pipeline unit tests PASSED) 35 | Jenkinsfile.failure(groovy.lang.Closure) 36 | Jenkinsfile.changed(groovy.lang.Closure) 37 | Jenkinsfile.echo(pipeline unit tests results have CHANGED) 38 | Jenkinsfile.unstable(groovy.lang.Closure) 39 | -------------------------------------------------------------------------------- /pipelineTests/groovy/tests/callstacks/JenkinsfileTestSpec_Jenkinsfile_Should_Run_Gradle_validate_null_gradle_null.txt: -------------------------------------------------------------------------------- 1 | Jenkinsfile.run() 2 | Jenkinsfile.pipeline(groovy.lang.Closure) 3 | Jenkinsfile.agent(groovy.lang.Closure) 4 | Jenkinsfile.parameters(groovy.lang.Closure) 5 | Jenkinsfile.booleanParam({name=VALIDATE, defaultValue=true, description=Whether to run validation stage}) 6 | Jenkinsfile.string({name=GRADLE_TASKS_OPTIONS, defaultValue=clean build test -i, description=Tasks and options for the gradle command}) 7 | Jenkinsfile.options(groovy.lang.Closure) 8 | Jenkinsfile.logRotator({numToKeepStr=10}) 9 | Jenkinsfile.buildDiscarder(null) 10 | Jenkinsfile.timestamps() 11 | Jenkinsfile.triggers(groovy.lang.Closure) 12 | Jenkinsfile.pollSCM(*/5 * * * *) 13 | Jenkinsfile.stages(groovy.lang.Closure) 14 | Jenkinsfile.stage(Checkout, groovy.lang.Closure) 15 | Jenkinsfile.steps(groovy.lang.Closure) 16 | Jenkinsfile.deleteDir() 17 | Jenkinsfile.checkout(groovy.lang.Closure) 18 | Jenkinsfile.stage(validate, groovy.lang.Closure) 19 | Jenkinsfile.when(groovy.lang.Closure) 20 | Jenkinsfile.expression(groovy.lang.Closure) 21 | Jenkinsfile.steps(groovy.lang.Closure) 22 | Jenkinsfile.script(groovy.lang.Closure) 23 | Jenkinsfile.validateDeclarativePipeline(exampleJobs/parallel/Jenkinsfile) 24 | Jenkinsfile.validateDeclarativePipeline(exampleJobs/globalVariable/Jenkinsfile) 25 | Jenkinsfile.validateDeclarativePipeline(Jenkinsfile) 26 | Jenkinsfile.stage(build, groovy.lang.Closure) 27 | Jenkinsfile.steps(groovy.lang.Closure) 28 | Jenkinsfile.tool({name=GRADLE_3, type=hudson.plugins.gradle.GradleInstallation}) 29 | Jenkinsfile.withEnv([GRADLE_HOME=GRADLE_3_HOME], groovy.lang.Closure) 30 | Jenkinsfile.withEnv([PATH=/some/path:GRADLE_3_HOME/bin], groovy.lang.Closure) 31 | Jenkinsfile.echo(GRADLE_HOME=GRADLE_3_HOME) 32 | Jenkinsfile.echo(PATH=/some/path:GRADLE_3_HOME/bin) 33 | Jenkinsfile.sh(gradle clean build test -i) 34 | Jenkinsfile.post(groovy.lang.Closure) 35 | Jenkinsfile.always(groovy.lang.Closure) 36 | Jenkinsfile.echo(pipeline unit tests completed - recording JUnit results) 37 | Jenkinsfile.junit(build/test-results/**/*.xml) 38 | Jenkinsfile.success(groovy.lang.Closure) 39 | Jenkinsfile.echo(pipeline unit tests PASSED) 40 | Jenkinsfile.failure(groovy.lang.Closure) 41 | Jenkinsfile.changed(groovy.lang.Closure) 42 | Jenkinsfile.echo(pipeline unit tests results have CHANGED) 43 | Jenkinsfile.unstable(groovy.lang.Closure) 44 | -------------------------------------------------------------------------------- /pipelineTests/groovy/tests/callstacks/JenkinsfileTestSpec_Jenkinsfile_Should_Run_Gradle_validate_true_gradle_test.txt: -------------------------------------------------------------------------------- 1 | Jenkinsfile.run() 2 | Jenkinsfile.pipeline(groovy.lang.Closure) 3 | Jenkinsfile.agent(groovy.lang.Closure) 4 | Jenkinsfile.parameters(groovy.lang.Closure) 5 | Jenkinsfile.booleanParam({name=VALIDATE, defaultValue=true, description=Whether to run validation stage}) 6 | Jenkinsfile.string({name=GRADLE_TASKS_OPTIONS, defaultValue=clean build test -i, description=Tasks and options for the gradle command}) 7 | Jenkinsfile.options(groovy.lang.Closure) 8 | Jenkinsfile.logRotator({numToKeepStr=10}) 9 | Jenkinsfile.buildDiscarder(null) 10 | Jenkinsfile.timestamps() 11 | Jenkinsfile.triggers(groovy.lang.Closure) 12 | Jenkinsfile.pollSCM(*/5 * * * *) 13 | Jenkinsfile.stages(groovy.lang.Closure) 14 | Jenkinsfile.stage(Checkout, groovy.lang.Closure) 15 | Jenkinsfile.steps(groovy.lang.Closure) 16 | Jenkinsfile.deleteDir() 17 | Jenkinsfile.checkout(groovy.lang.Closure) 18 | Jenkinsfile.stage(validate, groovy.lang.Closure) 19 | Jenkinsfile.when(groovy.lang.Closure) 20 | Jenkinsfile.expression(groovy.lang.Closure) 21 | Jenkinsfile.steps(groovy.lang.Closure) 22 | Jenkinsfile.script(groovy.lang.Closure) 23 | Jenkinsfile.validateDeclarativePipeline(exampleJobs/parallel/Jenkinsfile) 24 | Jenkinsfile.validateDeclarativePipeline(exampleJobs/globalVariable/Jenkinsfile) 25 | Jenkinsfile.validateDeclarativePipeline(Jenkinsfile) 26 | Jenkinsfile.stage(build, groovy.lang.Closure) 27 | Jenkinsfile.steps(groovy.lang.Closure) 28 | Jenkinsfile.tool({name=GRADLE_3, type=hudson.plugins.gradle.GradleInstallation}) 29 | Jenkinsfile.withEnv([GRADLE_HOME=GRADLE_3_HOME], groovy.lang.Closure) 30 | Jenkinsfile.withEnv([PATH=/some/path:GRADLE_3_HOME/bin], groovy.lang.Closure) 31 | Jenkinsfile.echo(GRADLE_HOME=GRADLE_3_HOME) 32 | Jenkinsfile.echo(PATH=/some/path:GRADLE_3_HOME/bin) 33 | Jenkinsfile.sh(gradle test) 34 | Jenkinsfile.post(groovy.lang.Closure) 35 | Jenkinsfile.always(groovy.lang.Closure) 36 | Jenkinsfile.echo(pipeline unit tests completed - recording JUnit results) 37 | Jenkinsfile.junit(build/test-results/**/*.xml) 38 | Jenkinsfile.success(groovy.lang.Closure) 39 | Jenkinsfile.echo(pipeline unit tests PASSED) 40 | Jenkinsfile.failure(groovy.lang.Closure) 41 | Jenkinsfile.changed(groovy.lang.Closure) 42 | Jenkinsfile.echo(pipeline unit tests results have CHANGED) 43 | Jenkinsfile.unstable(groovy.lang.Closure) 44 | -------------------------------------------------------------------------------- /pipelineTests/groovy/tests/callstacks/ParallelJobTestSpec_Parallel_Jenkinsfile_should_complete_with_success.txt: -------------------------------------------------------------------------------- 1 | Jenkinsfile.run() 2 | Jenkinsfile.pipeline(groovy.lang.Closure) 3 | Jenkinsfile.agent(groovy.lang.Closure) 4 | Jenkinsfile.stages(groovy.lang.Closure) 5 | Jenkinsfile.stage(Setup, groovy.lang.Closure) 6 | Jenkinsfile.steps(groovy.lang.Closure) 7 | Jenkinsfile.script(groovy.lang.Closure) 8 | Jenkinsfile.stage(Dynamic, groovy.lang.Closure) 9 | Jenkinsfile.steps(groovy.lang.Closure) 10 | Jenkinsfile.script(groovy.lang.Closure) 11 | Jenkinsfile.parallel({foo=groovy.lang.Closure, bar=groovy.lang.Closure}) 12 | Jenkinsfile.echo(Running foo branch..) 13 | Jenkinsfile.echo(Running bar branch...) 14 | Jenkinsfile.stage(Static Old Way, groovy.lang.Closure) 15 | Jenkinsfile.steps(groovy.lang.Closure) 16 | Jenkinsfile.parallel({branch_1=groovy.lang.Closure, branch_2=groovy.lang.Closure}) 17 | Jenkinsfile.echo(Running static branch 1) 18 | Jenkinsfile.echo(Running static branch 2) 19 | Jenkinsfile.stage(Static New Way, groovy.lang.Closure) 20 | Jenkinsfile.parallel(groovy.lang.Closure) 21 | Jenkinsfile.stage(Stage 1, groovy.lang.Closure) 22 | Jenkinsfile.steps(groovy.lang.Closure) 23 | Jenkinsfile.echo(Running pipeline v1.2 static stage 1) 24 | Jenkinsfile.stage(Stage 2, groovy.lang.Closure) 25 | Jenkinsfile.steps(groovy.lang.Closure) 26 | Jenkinsfile.echo(Running pipeline v1.2 static stage 2) 27 | Jenkinsfile.stage(Stage Skipped, groovy.lang.Closure) 28 | Jenkinsfile.when(groovy.lang.Closure) 29 | Jenkinsfile.expression(groovy.lang.Closure) 30 | -------------------------------------------------------------------------------- /pipelineTests/groovy/tests/callstacks/stepWithParamsTestSpec_should_echo_values.txt: -------------------------------------------------------------------------------- 1 | stepWithParams.call(param1 value, param2 value, 12345) 2 | stepWithParams.echo(param1 = param1 value) 3 | stepWithParams.echo(param2 = param2 value) 4 | stepWithParams.echo(param3 = 12345) 5 | -------------------------------------------------------------------------------- /pipelineTests/groovy/tests/job/JenkinsfileTestSpec.groovy: -------------------------------------------------------------------------------- 1 | package tests.job 2 | 3 | import spock.lang.Unroll 4 | import testSupport.PipelineSpockTestBase 5 | 6 | /** 7 | * A spock test to test the Jenkinsfile that runs the gradle to run these Spock tests 8 | */ 9 | class JenkinsfileTestSpec extends PipelineSpockTestBase { 10 | 11 | @Unroll 12 | def "Jenkinsfile should run gradle tests with expected command line validate:#P_VALIDATE gradle: #P_GRADLE_TASKS_OPTIONS"() { 13 | 14 | given: 15 | addParam('VALIDATE', P_VALIDATE) 16 | addParam('GRADLE_TASKS_OPTIONS', P_GRADLE_TASKS_OPTIONS) 17 | 18 | and: 19 | helper.registerAllowedMethod('validateDeclarativePipeline', [String.class], { true } ) 20 | 21 | and: 22 | def shellMock = Mock(Closure) 23 | helper.registerAllowedMethod('sh', [String.class], shellMock) 24 | 25 | when: 26 | runScript('Jenkinsfile') 27 | 28 | then: 29 | 1 * shellMock.call(_) >> { List args -> 30 | 31 | // Shell command string comes back as a single element array with JenkinsPipelineUnit 1.1 32 | // See issue discussion: https://github.com/lesfurets/JenkinsPipelineUnit/issues/59 33 | println "shellMock args : ${args.toString()}" 34 | def shellCmd = args[0][0] 35 | assert shellCmd == GRADLE_EXPECTED_CMD 36 | } 37 | 38 | then: 39 | printCallStack() 40 | assertJobStatusSuccess() 41 | 42 | then: 43 | testNonRegression("Jenkinsfile_Should_Run_Gradle_validate_${P_VALIDATE}_gradle_${P_GRADLE_TASKS_OPTIONS}") 44 | 45 | where: 46 | P_VALIDATE | P_GRADLE_TASKS_OPTIONS | GRADLE_EXPECTED_CMD 47 | null | null | 'gradle clean build test -i' 48 | true | 'test' | 'gradle test' 49 | false | 'build test' | 'gradle build test' 50 | } 51 | 52 | def "Jenkinsfile gradle failure should fail job"() { 53 | 54 | given: 55 | helper.registerAllowedMethod('validateDeclarativePipeline', [String.class], { true } ) 56 | 57 | and: 58 | def shellMock = Mock(Closure) 59 | helper.registerAllowedMethod('sh', [String.class], shellMock) 60 | 61 | when: 62 | runScript('Jenkinsfile') 63 | 64 | then: 65 | 1 * shellMock.call(_) >> { args -> 66 | println "shellMock args : ${args.toString()}" 67 | binding.getVariable('currentBuild').result = 'FAILURE' 68 | } 69 | 70 | then: 71 | printCallStack() 72 | assertJobStatusFailure() 73 | } 74 | 75 | def "Jenkinsfile validation errors should fail the job"() { 76 | 77 | given: 78 | helper.registerAllowedMethod('validateDeclarativePipeline', [String.class], { false } ) 79 | 80 | when: 81 | runScript('Jenkinsfile') 82 | 83 | then: 84 | printCallStack() 85 | assertJobStatusFailure() 86 | } 87 | 88 | @Unroll 89 | def "Jenkinsfile cover all build results for post sections - #RESULT"() { 90 | 91 | given: 92 | helper.registerAllowedMethod('validateDeclarativePipeline', [String.class], { true } ) 93 | 94 | and: 95 | def shellMock = Mock(Closure) 96 | helper.registerAllowedMethod('sh', [String.class], shellMock) 97 | 98 | and: 99 | binding.getVariable('currentBuild').result = RESULT 100 | 101 | when: 102 | runScript('Jenkinsfile') 103 | 104 | then: 105 | printCallStack() 106 | 107 | where: 108 | RESULT | NONE 109 | 'SUCCESS' | _ 110 | 'FAILURE' | _ 111 | 'ABORTED' | _ 112 | 'UNSTABLE' | _ 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /pipelineTests/groovy/tests/job/exampleJobs/globalVariable/GlobalVariableJobTestSpec.groovy: -------------------------------------------------------------------------------- 1 | package tests.job.exampleJobs.globalVariable 2 | 3 | import testSupport.PipelineSpockTestBase 4 | 5 | class GlobalVariableJobTestSpec extends PipelineSpockTestBase { 6 | 7 | def "gobal variable job Jenkinsfile test"() { 8 | 9 | given: 10 | helper.registerAllowedMethod('doWithProperties', [Properties.class], null) 11 | 12 | when: 13 | runScript('exampleJobs/globalVariable/Jenkinsfile') 14 | 15 | then: 16 | printCallStack() 17 | assertJobStatusSuccess() 18 | 19 | then: 20 | testNonRegression("Jenkinsfile_should_complete_with_success") 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /pipelineTests/groovy/tests/job/exampleJobs/parallel/ParallelJobTestSpec.groovy: -------------------------------------------------------------------------------- 1 | package tests.job.exampleJobs.parallel 2 | 3 | import testSupport.PipelineSpockTestBase 4 | 5 | class ParallelJobTestSpec extends PipelineSpockTestBase { 6 | 7 | def "parallel Jenkinsfile test"() { 8 | 9 | 10 | when: 11 | runScript('exampleJobs/parallel/Jenkinsfile') 12 | 13 | then: 14 | printCallStack() 15 | assertJobStatusSuccess() 16 | 17 | then: 18 | testNonRegression("Parallel_Jenkinsfile_should_complete_with_success") 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /pipelineTests/groovy/tests/library/helloMessageTestSpec.groovy: -------------------------------------------------------------------------------- 1 | package tests.library 2 | 3 | import testSupport.PipelineSpockTestBase 4 | 5 | /** 6 | * How to unit test some vars DSL like shared code 7 | */ 8 | class helloMessageTestSpec extends PipelineSpockTestBase { 9 | 10 | def "test shared library code"() { 11 | 12 | given: 13 | def helloMessageBody = { 14 | message = 'This is a test message' 15 | } 16 | 17 | when: 18 | def script = loadScript('pipelineLibrary/vars/helloMessage.groovy') 19 | script.call(helloMessageBody) 20 | 21 | then: 22 | printCallStack() 23 | assertJobStatusSuccess() 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /pipelineTests/groovy/tests/library/stepWithParamsTestSpec.groovy: -------------------------------------------------------------------------------- 1 | package tests.library 2 | 3 | import testSupport.PipelineSpockTestBase 4 | 5 | class stepWithParamsTestSpec extends PipelineSpockTestBase { 6 | 7 | def "stepWithParams should echo param values"() { 8 | 9 | given: 10 | def param1 = 'param1 value' 11 | def param2 = 'param2 value' 12 | def param3 = 12345 13 | 14 | 15 | when: 16 | def script = loadScript('pipelineLibrary/vars/stepWithParams.groovy') 17 | script.call(param1, param2, param3) 18 | 19 | then: 20 | printCallStack() 21 | assertJobStatusSuccess() 22 | 23 | then: 24 | testNonRegression("should_echo_values") 25 | 26 | } 27 | } 28 | --------------------------------------------------------------------------------