可以测试作业 DSL 脚本吗

Can a Job DSL script be tested

理想情况下,我希望能够在 Jenkins 上执行脚本之前通过某种单元测试调用脚本。

除了使用 jenkins 运行 之外,还有什么方法可以测试 Job DSL 脚本吗?

查看 DSL 脚本的 job-dsl-gradle-example. The repo contains a test

除了job-dsl-gradle-example中的示例之外,您还可以更进一步,为单个文件或作业编写测试。例如,假设您有一个作业配置文件位于 jobs/deployJob.groovy

import javaposse.jobdsl.dsl.DslScriptLoader
import javaposse.jobdsl.dsl.MemoryJobManagement
import javaposse.jobdsl.dsl.ScriptRequest
import spock.lang.Specification

class TestDeployJobs extends Specification {

    def 'test basic job configuration'() {
        given:
        URL scriptURL = new File('jobs').toURI().toURL()
        ScriptRequest scriptRequest = new ScriptRequest('deployJob.groovy', null, scriptURL)
        MemoryJobManagement jobManagement = new MemoryJobManagement()

        when:
        DslScriptLoader.runDslEngine(scriptRequest, jobManagement)

        then:
        jobManagement.savedConfigs.each { String name, String xml ->
            with(new XmlParser().parse(new StringReader(xml))) {
                // Make sure jobs only run manually
                triggers.'hudson.triggers.TimerTrigger'.spec.text().isEmpty()
                // only deploy every environment once at a time
                concurrentBuild.text().equals('false')
                // do a workspace cleanup
                buildWrappers.'hudson.plugins.ws__cleanup.PreBuildCleanup'
                // make sure masked passwords are active
                !buildWrappers.'com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsBuildWrapper'.isEmpty()
            }
        }
    }
}

这样您就可以遍历每个 XML 节点以确保设置了所有正确的值。

按照与crasp but using Jenkins test harness as explained in Jenkins Unit Test page, which is slower but would work with auto-generated DSL giving syntax errors as explained here相同的方式进行操作。

按照说明设置代码后here,您可以像这样进行测试:

@Unroll
void 'check descriptions #file.name'(File file) {
    given:
    JobManagement jobManagement = new JenkinsJobManagement(System.out, [:], new File('.'))
    Jenkins jenkins = jenkinsRule.jenkins

    when:
    GeneratedItems items = new DslScriptLoader(jobManagement).runScript(file.text)

    then:
    if (!items.jobs.isEmpty()) {
        items.jobs.each { GeneratedJob generatedJob ->
            String text = getItemXml(generatedJob, jenkins)
            with(new XmlParser().parse(new StringReader(text))) {
                // Has some description
                !description.text().isEmpty()
            }
        }
    }

    where:
    file << TestUtil.getJobFiles()
}