unit-testing - 如何对 Groovy 脚本进行单元测试,在 Elasticsearch 中用于 _score 计算

标签 unit-testing testing groovy elasticsearch

我想对 Elasticsearch 中使用的 Groovy 脚本进行单元测试。

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

是否有提供此类功能的可用工具?

最佳答案

我已经通过在 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
    }
}

关于unit-testing - 如何对 Groovy 脚本进行单元测试,在 Elasticsearch 中用于 _score 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30707892/

相关文章:

python - 将 __init__.py 导入到unittest包中

c++ - 测试类

groovy - 使用 "Scriptrunner for Jira"自定义监听器更新自定义字段值

grails - Grails 1.2.4:更改ProxySettings.groovy的位置

python - 在单元测试中使用 django.template 上下文时遇到问题

unit-testing - 在 ScalaTest 中 `should` 、 `can` 、 `must` 之间有什么区别

c++ - 运行网络测试的方法

android - Espresso 安卓测试

python - 测试后清理文件的最有效方法?

google-app-engine - 驱动程序:com.mysql.jdbc.Driver@75b3ef1a对于URL:jdbc返回null,表示应用程序引擎上的grails应用程序