如何为数据集描述创建spock风格的DSL?

我想在spock数据驱动的规范格式中有一个数据集描述:

'Key'   |    'Value'    |    'Comments'
1       |    'foo'      |    'something'
2       |    'bar'      |    'something else'

这必须转换为像2D数组(或任何可能实现的).

有任何想法如何实现这种数据描述?

附:最大的问题是换行检测,其余的可以通过重载或在Object的metaClass上实现.

解决方法:

| operator是左关联的,因此该表中的一行将被解析为:

('Key' | 'Value') | 'Comments'

然后你可以做什么来检测每行开始和结束的位置是使opeator返回一个包含其操作数的列表,然后返回每个|询问左侧操作数(即此)是否为列表.如果是,则意味着它是一行的延续;如果它不是列表,则意味着它是一个新行.

以下是使用Category解析这些数据集的DSL的完整示例,以避免覆盖Object元类的内容:

@Category(Object)
class DatasetCategory {
    // A static property for holding the results of the DSL.
    static results

    def or(other) {
        if (this instanceof List) {
            // Already in a row. Add the value to the row.
            return this << other
        } else {
            // A new row.
            def row = [this, other]
            results << row
            return row
        }
    }
}

// This is the method that receives a closure with the DSL and returns the 
// parsed result.
def dataset(Closure cl) {
    // Initialize results and execute closure using the DatasetCategory.
    DatasetCategory.results = []
    use (DatasetCategory) { cl() }

    // Convert the 2D results array into a list of objects:
    def table = DatasetCategory.results
    def header = table.head()
    def rows = table.tail()
    rows.collect { row -> 
        [header, row].transpose().collectEntries { it } 
    }
}

// Example usage.
def data = dataset {
    'Key'   |    'Value'    |    'Comments'
    1       |    'foo'      |    'something'
    2       |    'bar'      |    'something else'
}

// Correcness test :)
assert data == [
    [Key: 1, Value: 'foo', Comments: 'something'],
    [Key: 2, Value: 'bar', Comments: 'something else']
]

在这个例子中,我将表解析为一个映射列表,但是在DSL闭包运行之后,您应该可以使用DatasetCategory的结果执行任何操作.

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...