我想对Elasticsearch中使用的Groovy脚本进行单元测试。
脚本本身根据3个参数和给定的公式计算_score。 我想为该脚本编写一个自动单元测试程序,以验证其正确性。
是否有可用的工具,提供此类功能?
答案 0 :(得分:2)
我通过使用Groovy“magic”在TestNG测试中模拟/模拟Elasticsearch环境来解决问题。
给出以下Groovy脚本,该脚本应根据参数和文档高度计算自定义分数值。
<强> es_compute_custom_score.groovy 强>
h = doc['height']
if (h <= 50) {
// complex logic here ;-)
} else if (h < 1000) {
// more complex logic here ;-)
} else {
// even more complex logic here ;-)
}
_score = a * b + h
然后,这个单元测试可以让你走red/green/refactor TDD路......
es_compute_custom_scoreTest.groovy (假设默认为Maven project layout)
import org.codehaus.groovy.control.CompilerConfiguration
import org.testng.annotations.BeforeMethod
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
class es_compute_custom_scoreTest{
private static final String SCRIPT_UNDER_TEST = 'src/main/groovy/es_compute_custom_score.groovy'
private CompilerConfiguration compilerConfiguration
private Binding binding
@BeforeMethod
public void setUp() throws Exception {
compilerConfiguration = new CompilerConfiguration()
this.compilerConfiguration.scriptBaseClass = DocumentBaseClassMock.class.name
binding = new Binding()
}
@DataProvider
public Object[][] createTestData() {
List<Object[]> refdata = new ArrayList<>()
refdata.add([100, 50, 5042L])
refdata.add([200, 50, 10042L])
refdata.add([300, 50, 15042L])
return refdata
}
@Test(dataProvider = 'createTestData')
void 'calculate a custom document score, based on parameters a and b, and documents height'(Integer a, Integer b, Long expected_score) {
// given
binding.setVariable("a", a)
binding.setVariable("b", b)
binding.setVariable("doc", new MockDocument(42))
// when
evaluateScriptUnderTest(this.binding)
// then
long score = (long) this.binding.getVariable("_score")
assert score == expected_score
}
private void evaluateScriptUnderTest(Binding binding) {
GroovyShell gs = new GroovyShell(binding, compilerConfiguration)
gs.evaluate(new File(SCRIPT_UNDER_TEST));
}
}
class MockDocument {
long height;
MockDocument(long height) {
this.height = height
}
}