mirror of
https://github.com/SAP/jenkins-library.git
synced 2024-12-14 11:03:09 +02:00
dd456f0d00
Comparism on plain string level gets complicated for complex commands and means an implict check for an exact version of a command line. There are cases where such an exact check is not desired, e.g. there is nothing wrong with having the order of arguments variable.
84 lines
2.3 KiB
Groovy
84 lines
2.3 KiB
Groovy
package util
|
|
|
|
import com.lesfurets.jenkins.unit.BasePipelineTest
|
|
|
|
import util.JenkinsShellCallRule.Type
|
|
|
|
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
|
|
}
|
|
}
|
|
|
|
final BasePipelineTest testInstance
|
|
|
|
List shell = []
|
|
|
|
Map<Key, String> returnValues = [:]
|
|
|
|
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
|
|
}
|
|
|
|
@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))
|
|
})
|
|
|
|
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
|
|
}
|
|
})
|
|
|
|
base.evaluate()
|
|
}
|
|
}
|
|
}
|
|
|
|
private static String unify(String s) {
|
|
s.replaceAll(/\s+/," ").trim()
|
|
}
|
|
}
|