2018-01-10 11:27:55 +02:00
|
|
|
package util
|
|
|
|
|
|
|
|
import com.lesfurets.jenkins.unit.BasePipelineTest
|
2018-07-10 17:34:36 +02:00
|
|
|
|
|
|
|
import org.junit.Assert
|
2018-01-10 11:27:55 +02:00
|
|
|
import org.junit.rules.TestRule
|
|
|
|
import org.junit.runner.Description
|
|
|
|
import org.junit.runners.model.Statement
|
|
|
|
|
2018-07-10 17:34:36 +02:00
|
|
|
import static org.hamcrest.Matchers.containsString
|
2019-05-22 16:56:50 +02:00
|
|
|
import static org.junit.Assert.assertThat
|
2018-07-10 17:34:36 +02:00
|
|
|
|
|
|
|
import org.hamcrest.Matchers
|
|
|
|
|
2018-01-10 11:27:55 +02:00
|
|
|
class JenkinsLoggingRule implements TestRule {
|
|
|
|
|
|
|
|
final BasePipelineTest testInstance
|
|
|
|
|
2018-07-10 17:34:36 +02:00
|
|
|
def expected = []
|
|
|
|
|
2018-01-10 11:27:55 +02:00
|
|
|
String log = ""
|
|
|
|
|
|
|
|
JenkinsLoggingRule(BasePipelineTest testInstance) {
|
|
|
|
this.testInstance = testInstance
|
|
|
|
}
|
|
|
|
|
2018-07-10 17:34:36 +02:00
|
|
|
public void expect(String substring) {
|
|
|
|
expected.add(substring)
|
|
|
|
}
|
|
|
|
|
2018-01-10 11:27:55 +02: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("echo", [String.class], {
|
|
|
|
echoInput ->
|
|
|
|
log += "$echoInput \n"
|
|
|
|
})
|
|
|
|
|
2018-07-10 17:34:36 +02:00
|
|
|
Throwable caught
|
|
|
|
|
|
|
|
try {
|
|
|
|
base.evaluate()
|
|
|
|
} catch(Throwable thr) {
|
|
|
|
caught = thr
|
|
|
|
} finally {
|
|
|
|
if(caught instanceof AssertionError) {
|
|
|
|
// Be polite, give other rules the advantage.
|
|
|
|
// We expect other rules located closer to the test case
|
|
|
|
// to throw an AssertionError in case of a violation.
|
|
|
|
throw caught
|
|
|
|
}
|
|
|
|
|
2018-07-12 08:11:42 +02:00
|
|
|
expected.each { substring -> assertThat("Substring '${substring}' not contained in log.",
|
2018-07-10 17:34:36 +02:00
|
|
|
log,
|
|
|
|
containsString(substring)) }
|
|
|
|
|
|
|
|
if(caught != null) {
|
|
|
|
// do not swallow, so that other rules located farer away
|
|
|
|
// to the test case can react
|
|
|
|
throw caught
|
|
|
|
}
|
|
|
|
}
|
2018-01-10 11:27:55 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|