1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2024-12-14 11:03:09 +02:00
sap-jenkins-library/test/groovy/util/JenkinsReadYamlRule.groovy
Marcus Holl 6b7dc48c44 Be more flexible with JenkinsReadYaml rule
When we register a closure as file, the closure will be exectutd.
Otherwise we return what is registered.

This gives us a maximum level of flexibility. We can throw exceptions (e.g. FileNotFound) as
as test setup requires this, in simple cases we provide the yaml as a string.
2018-09-04 09:46:59 +02:00

53 lines
1.6 KiB
Groovy

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 {
final BasePipelineTest testInstance
// Empty project configuration file registered by default
// since almost every test needs it.
def ymls = ['.pipeline/config.yml': {''}]
JenkinsReadYamlRule(BasePipelineTest testInstance) {
this.testInstance = testInstance
}
JenkinsReadYamlRule registerYaml(fileName, yaml) {
ymls.put(fileName, yaml)
return this
}
@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)
})
base.evaluate()
}
}
}
}