github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/test/groovy/util/JenkinsReadYamlRule.groovy (about) 1 package util 2 3 import org.junit.rules.TestRule 4 import org.junit.runner.Description 5 import org.junit.runners.model.Statement 6 import org.yaml.snakeyaml.Yaml 7 8 import com.lesfurets.jenkins.unit.BasePipelineTest 9 10 class JenkinsReadYamlRule implements TestRule { 11 final BasePipelineTest testInstance 12 13 // Empty project configuration file registered by default 14 // since almost every test needs it. 15 def ymls = ['.pipeline/config.yml': {''}] 16 17 JenkinsReadYamlRule(BasePipelineTest testInstance) { 18 this.testInstance = testInstance 19 } 20 21 JenkinsReadYamlRule registerYaml(fileName, yaml) { 22 ymls.put(fileName, yaml) 23 return this 24 } 25 @Override 26 Statement apply(Statement base, Description description) { 27 return statement(base) 28 } 29 30 private Statement statement(final Statement base) { 31 return new Statement() { 32 @Override 33 void evaluate() throws Throwable { 34 testInstance.helper.registerAllowedMethod("readYaml", [Map], { Map m -> 35 def yml 36 if(m.text) { 37 yml = m.text 38 } else if(m.file) { 39 yml = ymls.get(m.file) 40 if(yml == null) throw new NullPointerException("yaml file '${m.file}' not registered.") 41 if(yml instanceof Closure) yml = yml() 42 } else { 43 throw new IllegalArgumentException("Key 'text' and 'file' are both missing in map ${m}.") 44 } 45 46 47 return readYaml(yml) 48 }) 49 50 base.evaluate() 51 } 52 } 53 } 54 55 /** 56 * Mimicking code of the original library (link below). 57 * <p> 58 * Yaml files may contain several YAML sections, separated by ---. 59 * This loads them all and returns a {@code List} of entries in case multiple sections were found or just 60 * a single {@code Object}, if only one section was read. 61 * @see https://github.com/jenkinsci/pipeline-utility-steps-plugin/blob/master/src/main/java/org/jenkinsci/plugins/pipeline/utility/steps/conf/ReadYamlStep.java 62 */ 63 private def readYaml(def yml) { 64 Iterable<Object> yaml = new Yaml().loadAll(yml) 65 66 List<Object> result = new LinkedList<Object>() 67 for (Object data : yaml) { 68 result.add(data) 69 } 70 71 // If only one YAML document, return it directly 72 if (result.size() == 1) { 73 return result.get(0); 74 } 75 76 return result; 77 } 78 }