2015-06-08 45 views
1

我想为Groovy脚本,在Elasticsearch用做单元测试。如何单元测试Groovy脚本,在Elasticsearch用于_score计算

脚本本身计算_score,基于3个参数和给定的公式。 我想为该脚本编写一个自动单元测试程序,以验证其正确性。

是否有任何可用的工具,它提供了这样的功能?

+0

会像这样的帮助你https: //github.com/elastic/elasticsearch/blob/master/core/src/test/java/org/elasticsearch/script/GroovyScriptTests.java? (我知道这是不是一个单元测试,而是集成测试) –

+0

@AndreiStefan有趣的方法 - 感谢..我脑子里想的)东西,这更去到一个方向,我想测试用的eval(测试脚本和一个给定的数据提供器(testng),以便我可以测试两个少数参数和一个公式。 – nitram509

+0

对我来说,这听起来像Groovy测试是诚实的,没有任何Elasticsearch的参与。但是,如果你需要一些特殊的字段/值,这些值可以在脚本中使用,那么你需要类似前面引用的类。 –

回答

2

我的嘲笑/在TestNG的测试模拟Elasticsearch环境,使用Groovy“神奇”解决了这个问题。

考虑下面的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 
    } 
}