Reputation: 4865
I would like to validate a dict
, where a field may contain either an int
or a List[int]
. Also, all int
must be positive.
I need some help with setting up the schema. The schema below are not working properly. They are not checking for negative numbers. That is, negative numbers are passing the validation, which is incorrect.
import cerberus
v = cerberus.Validator()
schema1 = {
"int_or_list_of_int": {
"type": ["integer", "list"],
"schema": {"type": "integer", "min": 0},
},
}
schema2 = {
"int_or_list_of_int": {
"type": ["integer", "list"],
"valuesrules": {"type": "integer", "min": 0},
},
}
num1 = {"int_or_list_of_int": 5}
num2 = {"int_or_list_of_int": [5, 10]}
num3 = {"int_or_list_of_int": -5}
num4 = {"int_or_list_of_int": [5, -10]}
# schema 1
assert v.validate(num1, schema1)
assert v.validate(num2, schema1)
assert not v.validate(num3, schema1) # Evaluates to True
assert not v.validate(num3, schema1) # Evaluates to True
# schema 2
assert v.validate(num1, schema2)
assert v.validate(num2, schema2)to True
assert not v.validate(num3, schema2) # Evaluates to True
assert not v.validate(num4, schema2) # Evaluates to True
Upvotes: 2
Views: 517
Reputation: 370
First of all, schema
for int_or_list_of_int
should be inside int_or_list_of_int
dict. Secondly, min
should be applied for both integer (inside int_or_list_of_int
) and list (inside schema
).
schema = {
"int_or_list_of_int": {
"type": ["integer", "list"],
"min": 0,
"schema": {"type": "integer", "min": 0}
}
}
Upvotes: 4