github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/test/groovy/util/JenkinsReadFileRule.groovy (about) 1 package util 2 3 import com.lesfurets.jenkins.unit.BasePipelineTest 4 import org.junit.rules.TestRule 5 import org.junit.runner.Description 6 import org.junit.runners.model.Statement 7 8 class JenkinsReadFileRule implements TestRule { 9 10 final BasePipelineTest testInstance 11 final String testRoot 12 final Map files = [:] 13 14 JenkinsReadFileRule(BasePipelineTest testInstance, String testRoot) { 15 this.testInstance = testInstance 16 this.testRoot = testRoot 17 } 18 19 @Override 20 Statement apply(Statement base, Description description) { 21 return statement(base) 22 } 23 24 private Statement statement(final Statement base) { 25 return new Statement() { 26 @Override 27 void evaluate() throws Throwable { 28 29 testInstance.helper.registerAllowedMethod( 'readFile', [String.class], {s -> return load(s, 'UTF-8')} ) 30 31 testInstance.helper.registerAllowedMethod( 'readFile', [Map.class], {m -> return load(m.file, m.encoding?m.encoding:'UTF-8')} ) 32 33 base.evaluate() 34 } 35 } 36 } 37 38 String load(String path, String encoding) { 39 40 if(files[path]) { 41 return files[path] 42 } 43 44 if(testRoot == null) { 45 throw new IllegalStateException("Test root not set. Resolving: \"${path}\".") 46 } 47 loadFile(testRoot + '/' + path).getText(encoding) 48 } 49 50 File loadFile(String path){ 51 return new File(path) 52 } 53 }