github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/test/groovy/util/JenkinsMavenExecuteRule.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 JenkinsMavenExecuteRule implements TestRule { 9 10 static class Execution { 11 12 final String pomPath 13 final List goals 14 final List defines 15 final List flags 16 17 Execution(Map parameters) { 18 this.pomPath = parameters.pomPath ?: 'pom.xml' 19 this.goals = asList(parameters.goals) 20 this.defines = asList(parameters.defines) 21 this.flags = asList(parameters.flags) 22 } 23 24 String toString() { 25 return "--file ${pomPath} : ${goals} : ${defines} : ${flags}" 26 } 27 28 @Override 29 int hashCode() { 30 return pomPath.hashCode() * goals.hashCode() * defines.hashCode() * flags.hashCode() 31 } 32 33 @Override 34 boolean equals(Object obj) { 35 if (obj == null || !obj instanceof Execution) { 36 return false 37 } 38 Execution other = (Execution) obj 39 return goals == other.goals && defines == other.defines && flags == other.flags 40 } 41 42 private List asList(def value) { 43 if (value instanceof List) { 44 return value as List 45 } 46 if (value instanceof CharSequence) { 47 return [ value ] 48 } 49 return [] 50 } 51 } 52 53 final BasePipelineTest testInstance 54 55 List<Execution> executions = [] 56 57 Map<String, String> returnValues = [:] 58 59 JenkinsMavenExecuteRule(BasePipelineTest testInstance) { 60 this.testInstance = testInstance 61 } 62 63 def setReturnValue(Map params, String value) { 64 returnValues.put(stringify(params), value) 65 } 66 67 def handleExecution(Map parameters) { 68 69 String params = stringify(parameters) 70 executions.add(new Execution(parameters)) 71 72 def result = returnValues.get(params) 73 if (!result && parameters.returnStatus) { 74 result = 0 75 } 76 if (!parameters.returnStdout && !parameters.returnStatus) { 77 return 78 } 79 return result 80 } 81 82 @Override 83 Statement apply(Statement base, Description description) { 84 return statement(base) 85 } 86 87 private Statement statement(final Statement base) { 88 return new Statement() { 89 @Override 90 void evaluate() throws Throwable { 91 92 testInstance.helper.registerAllowedMethod("mavenExecute", [Map.class], { 93 map -> handleExecution(map) 94 }) 95 96 base.evaluate() 97 } 98 } 99 } 100 101 private static String stringify(Map map) { 102 String params = '' 103 List keys = ['pomPath', 'goals', 'defines', 'flags'] 104 for (String key : keys) { 105 if (params.length() > 0) 106 params += ' ' 107 params += map.get(key) 108 } 109 return params.replaceAll(/\s+/," ").trim() 110 } 111 }