我正在尝试自动测试Jenkins groovy dsl脚本,例如:
https://github.com/sheehan/job-dsl-gradle-example
我认为这个想法很直接,我遇到的问题是为虚拟Jenkins设置环境变量。我按照这里的说明进行操作:
https://wiki.jenkins-ci.org/display/JENKINS/Unit+Test
具体而言#34;如何设置env变量"部分并将以下内容添加到我的测试执行程序中:
import hudson.slaves.EnvironmentVariablesNodeProperty
import hudson.EnvVars
/**
* Tests that all dsl scripts in the jobs directory will compile.
*/
class JobScriptsSpec extends Specification {
@Shared
@ClassRule
JenkinsRule jenkinsRule = new JenkinsRule()
EnvironmentVariablesNodeProperty prop = new EnvironmentVariablesNodeProperty();
EnvVars envVars = prop.getEnvVars();
@Unroll
void 'test script #file.name'(File file) {
given:
envVars.put("ENVS", "dev19");
jenkinsRule.jenkins.getGlobalNodeProperties().add(prop);
JobManagement jm = new JenkinsJobManagement(System.out, [:], new File('.'))
when:
new DslScriptLoader(jm).runScript(file.text)
then:
noExceptionThrown()
where:
file << jobFiles
}
但是当我为其中一个脚本运行实际测试时,我仍然会看到以下内容:
Failed tests
test script Build.groovy
Expected no exception to be thrown, but got 'javaposse.jobdsl.dsl.DslScriptException'
at spock.lang.Specification.noExceptionThrown(Specification.java:118)
at com.dslexample.JobScriptsSpec.test script #file.name(JobScriptsSpec.groovy:40)
Caused by: javaposse.jobdsl.dsl.DslScriptException: (script, line 3) No such property: ENVS for class: script
脚本Build.groovy使用变量&#34; $ {ENVS}&#34; (好像它是由Jenkins的种子作业中的参数提供的),它在Jenkins实际运行时按预期工作...所以任何方式来设置这些&#34;参数&#34;或测试jenkins上下文中的env变量?
我如何在Build.groovy中使用ENVS变量的示例:
def envs = '-'
"${ENVS}".eachLine{
def env = it
envs+=env+'-'
}
envs.substring(0,envs.length()-1)
job('Build'+envs) {
...
}
答案 0 :(得分:2)
JenkinsJobManagement
构造函数的第二个参数是环境变量的映射,它将在DSL脚本中提供。
Map<String, String> envVars = [
FOO: 'BAR'
]
JobManagement jm = new JenkinsJobManagement(System.out, envVars, new File('.'))