2018-01-16 14:39:42 +01:00
|
|
|
package util
|
|
|
|
|
|
|
|
import com.lesfurets.jenkins.unit.BasePipelineTest
|
2018-06-22 09:32:04 +02:00
|
|
|
|
|
|
|
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 {
|
|
|
|
|
2018-06-22 09:32:04 +02:00
|
|
|
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
|
|
|
|
2018-06-22 09:32:04 +02:00
|
|
|
Map<Key, String> returnValues = [:]
|
2018-02-07 13:17:33 +01:00
|
|
|
|
2018-01-16 14:39:42 +01:00
|
|
|
JenkinsShellCallRule(BasePipelineTest testInstance) {
|
|
|
|
this.testInstance = testInstance
|
|
|
|
}
|
|
|
|
|
2018-02-07 13:17:33 +01:00
|
|
|
def setReturnValue(script, value) {
|
2018-06-22 09:32:04 +02:00
|
|
|
setReturnValue(Type.PLAIN, script, value)
|
|
|
|
}
|
|
|
|
|
|
|
|
def setReturnValue(type, script, value) {
|
|
|
|
returnValues[new Key(type, script)] = value
|
2018-02-07 13:17:33 +01:00
|
|
|
}
|
|
|
|
|
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], {
|
2018-02-07 13:17:33 +01:00
|
|
|
command ->
|
2018-05-11 14:09:12 +02:00
|
|
|
shell.add(unify(command))
|
2018-01-16 14:39:42 +01:00
|
|
|
})
|
|
|
|
|
2018-02-07 13:17:33 +01:00
|
|
|
testInstance.helper.registerAllowedMethod("sh", [Map.class], {
|
|
|
|
m ->
|
|
|
|
shell.add(m.script.replaceAll(/\s+/," ").trim())
|
2018-06-22 09:32:04 +02:00
|
|
|
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-02-07 13:17:33 +01:00
|
|
|
})
|
|
|
|
|
2018-01-16 14:39:42 +01:00
|
|
|
base.evaluate()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-05-11 14:09:12 +02:00
|
|
|
|
|
|
|
private static String unify(String s) {
|
|
|
|
s.replaceAll(/\s+/," ").trim()
|
|
|
|
}
|
2018-01-16 14:39:42 +01:00
|
|
|
}
|