Skip to content

Instantly share code, notes, and snippets.

@demoth
Last active October 15, 2015 21:08
Show Gist options
  • Save demoth/4c9ccb14c4f44ff378a4 to your computer and use it in GitHub Desktop.
Save demoth/4c9ccb14c4f44ff378a4 to your computer and use it in GitHub Desktop.
JsonValidator
class JsonValidator extends BuilderSupport {
def root = null
void setParent(Object parent, Object child) {
if (!root) root = parent
parent.children << child
}
void createNode(Object name, Map attributes, Object value) {
return [name: name, value: value, children: []]
}
String validate(Object value) {
return validate(root, value, '')
}
private String validate(Object schema, Object value, String prefix) {
if (!value) return "$prefix.$schema.name is null"
def result = new StringBuilder()
schema.children.each {
def propertyType = it.value
def propertyName = it.name
def propertyValue = value[propertyName]
if (propertyType) {
if (!propertyValue)
result.append("\n$prefix.").append "$propertyName not found"
else if (propertyValue.class != propertyType)
result.append("\n$prefix.").append "$propertyName has wrong type: $propertyValue, should be $propertyType"
} else
result.append(validate(it, propertyValue, "$prefix.$propertyName"))
}
return result.toString()
}
}
class JsonValidatorTest {
def schema
@Before
void setup() {
schema = new JsonValidator()
schema.build() {
password String
url String
props {
age Integer
nonsence Boolean
}
}
}
@Test
void testPositive() {
assert schema.validate('''
{"password":"123","url":"http:lalla", "props":{"age":13, "nonsence":true}}
''').isEmpty()
}
@Test
void testTypeMismatch() {
assert schema.validate('''
{"password":"123","url":"http:lalla", "props":{"age":13, "nonsence":"true"}}
''') == '.props.nonsence has wrong type class java.lang.String: should be class java.lang.Boolean'
}
@Test
void testPropertyMissing() {
assert schema.validate('''
{"password":"123","url":"http:lalla", "props":{"age":13}}
''') == '.props.nonsence not found'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment