1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2025-01-18 05:18:24 +02:00
sap-jenkins-library/test/groovy/util/JenkinsReadYamlRule.groovy

53 lines
1.6 KiB
Groovy
Raw Normal View History

2018-01-16 16:42:11 +02:00
package util
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import org.yaml.snakeyaml.Yaml
import com.lesfurets.jenkins.unit.BasePipelineTest
class JenkinsReadYamlRule implements TestRule {
2018-01-16 16:42:11 +02:00
final BasePipelineTest testInstance
// Empty project configuration file registered by default
// since almost every test needs it.
def ymls = ['.pipeline/config.yml': {''}]
JenkinsReadYamlRule(BasePipelineTest testInstance) {
2018-01-16 16:42:11 +02:00
this.testInstance = testInstance
}
JenkinsReadYamlRule registerYaml(fileName, yaml) {
ymls.put(fileName, yaml)
return this
}
2018-01-16 16:42:11 +02:00
@Override
Statement apply(Statement base, Description description) {
return statement(base)
}
private Statement statement(final Statement base) {
return new Statement() {
@Override
void evaluate() throws Throwable {
testInstance.helper.registerAllowedMethod("readYaml", [Map], { Map m ->
def yml
if(m.text) {
yml = m.text
} else if(m.file) {
yml = ymls.get(m.file)
if(yml == null) throw new NullPointerException("yaml file '${m.file}' not registered.")
if(yml instanceof Closure) yml = yml()
} else {
throw new IllegalArgumentException("Key 'text' and 'file' are both missing in map ${m}.")
}
return new Yaml().load(yml)
2018-01-16 16:42:11 +02:00
})
base.evaluate()
}
}
}
}