1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2025-03-05 15:15:44 +02:00
sap-jenkins-library/test/groovy/util/JenkinsShellCallRule.groovy

84 lines
2.3 KiB
Groovy
Raw Normal View History

2018-01-16 14:39:42 +01:00
package util
import com.lesfurets.jenkins.unit.BasePipelineTest
import util.JenkinsShellCallRule.Type
2018-01-16 14:39:42 +01:00
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
class JenkinsShellCallRule implements TestRule {
enum Type { PLAIN, REGEX }
class Key{
final Type type
final String script
Key(Type type, String script) {
this.type = type
this.script = script
}
}
2018-01-16 14:39:42 +01:00
final BasePipelineTest testInstance
2018-01-16 15:03:00 +01:00
List shell = []
2018-01-16 14:39:42 +01:00
Map<Key, String> returnValues = [:]
2018-01-16 14:39:42 +01:00
JenkinsShellCallRule(BasePipelineTest testInstance) {
this.testInstance = testInstance
}
def setReturnValue(script, value) {
setReturnValue(Type.PLAIN, script, value)
}
def setReturnValue(type, script, value) {
returnValues[new Key(type, script)] = value
}
2018-01-16 14:39:42 +01: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("sh", [String.class], {
command ->
shell.add(unify(command))
2018-01-16 14:39:42 +01:00
})
testInstance.helper.registerAllowedMethod("sh", [Map.class], {
m ->
shell.add(m.script.replaceAll(/\s+/," ").trim())
if (m.returnStdout || m.returnStatus) {
def unifiedScript = unify(m.script)
for(def e : returnValues.entrySet()) {
if(e.key.type == Type.REGEX && unifiedScript =~ e.key.script) {
return e.value
} else if(e.key.type == Type.PLAIN && unifiedScript.equals(e.key.script)) {
return e.value
}
}
return null
}
})
2018-01-16 14:39:42 +01:00
base.evaluate()
}
}
}
private static String unify(String s) {
s.replaceAll(/\s+/," ").trim()
}
2018-01-16 14:39:42 +01:00
}