Nik Nik - 1 year ago 444
Groovy Question

How to set environment variables when testing DSL scripts against dummy jenkins?

I am trying to automate testing Jenkins groovy dsl scripts, like here:

The idea I think is very straight forward, what I'm having issues with is setting environment variables for the dummy Jenkins. I followed the instructions here:

Specifically "How to set env variables" section and added the following to my test executor:

import hudson.slaves.EnvironmentVariablesNodeProperty
import hudson.EnvVars

* Tests that all dsl scripts in the jobs directory will compile.
class JobScriptsSpec extends Specification {
JenkinsRule jenkinsRule = new JenkinsRule()

EnvironmentVariablesNodeProperty prop = new EnvironmentVariablesNodeProperty();
EnvVars envVars = prop.getEnvVars();

void 'test script'(File file) {
envVars.put("ENVS", "dev19");
JobManagement jm = new JenkinsJobManagement(System.out, [:], new File('.'))

new DslScriptLoader(jm).runScript(file.text)


file << jobFiles

However when I run the actual tests for one of the scripts, I still see the following:

Failed tests

test script Build.groovy
Expected no exception to be thrown, but got 'javaposse.jobdsl.dsl.DslScriptException'
at spock.lang.Specification.noExceptionThrown(
at com.dslexample.JobScriptsSpec.test script
Caused by: javaposse.jobdsl.dsl.DslScriptException: (script, line 3) No such property: ENVS for class: script

The script Build.groovy uses the variable "${ENVS}" (as if it were provided by parameter in seed job of Jenkins), which works as expected when actually running in Jenkins... So any way to set these "parameters" or env variables in the test jenkins context?

Example of how I use the ENVS variable in the Build.groovy:

def envs = '-'
def env = it

job('Build'+envs) {

Answer Source

The second argument of the JenkinsJobManagement constructor is a map of environment variables which will be available in the DSL scripts.

Map<String, String> envVars = [
    FOO: 'BAR'
JobManagement jm = new JenkinsJobManagement(System.out, envVars, new File('.'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download