crazy4groovy
3/16/2016 - 6:12 PM

Regex parser tester

Regex parser tester

import groovy.transform.Immutable

@Immutable
class Action {
    String service
    String method
}

@Immutable
class Resource {
    String service
    String accountOwner
    String path
}

def makeClass = { List matches ->
    if (matches[0] == 'fra')
        return new Action (*matches[1, 2])
    if (matches[0] == 'frn')
        return new Resource(*matches[1..-1])
}

String regex = /^([^:]+):([^:]+):([^:]*):?([^:]*)?$/
Map tests = [
        'fra:data:createData': Action,
        'frn:data:001:001/path/to/leaf': Resource,
        'frn:data::/profile': Resource,
        'frn:data::': Resource,
        'frn:::': null,
        ':::': null,
]

tests.each { String test, Class expectClass ->
    def matched = (test =~ regex)
    if (matched.size() == 0) {
        return expectClass == null
    }
    Object inst = makeClass(matched[0][1..-1])
    assert expectClass == inst.getClass()
}