class OrganizationForCreateValidator(v.Validator): schema = b.schema({ "name": b.And( t.String(), s.NotEmpty(), ) })
class TestValidate: schema = b.schema({ "name": b.Predicate(lambda name: len(name) > 0), "age": b.And( b.Pipe(int, message="User age must be an integer"), b.Predicate(lambda age: 18 <= age < 99, message="User has to be an adult")) }) def test_valid(self): data = {"name": "skame", "age": "28"} assert validate(self.schema, data) == ({ "name": "skame", "age": 28 }, None) def test_not_valid(self): assert validate(self.schema, {}) == (None, { 'name': 'Field `name` is required.', 'age': 'Field `age` is required.' }) def test_custom_validation_error(self): data = {"name": "skame", "age": "1"} assert validate(self.schema, data) == (None, { "age": "User has to be an adult" }) data = {"name": "skame", "age": ""} assert validate(self.schema, data) == (None, { "age": "User age must be an integer" })
class TestCleanDataOrRaise: schema = b.schema({ "name": b.Predicate(lambda name: len(name) > 0), "age": b.And( b.Pipe(int, message="User age must be an integer"), b.Predicate(lambda age: 18 <= age < 99, message="User has to be an adult")) }) def test_valid(self): data = {"name": "skame", "age": "28"} assert clean_data_or_raise(self.schema, data) == { "name": "skame", "age": 28 } def test_not_valid(self): with pytest.raises(SchemaErrors): clean_data_or_raise(self.schema, {}) def test_custom_validation_error(self): try: clean_data_or_raise(self.schema, {"name": "skame", "age": "1"}) except SchemaErrors as e: assert e.errors["age"] == "User has to be an adult" try: clean_data_or_raise(self.schema, {"name": "skame", "age": "skame"}) except SchemaErrors as e: assert e.errors["age"] == "User age must be an integer"
class OrganizationForUpdateValidator(v.Validator): schema = b.schema({ b.Optional("address"): b.And( t.String(), s.NotEmpty(), ), b.Optional("state"): b.And( t.String(), s.NotEmpty(), ), b.Optional("country"): b.And( t.String(), s.NotEmpty(), ), b.Optional("sector"): b.And( t.String(), s.NotEmpty(), ), b.Optional("web"): b.And( t.String(), s.NotEmpty(), s.URL(), ), b.Optional("description"): b.And( t.String(), s.NotEmpty(), ), })
def test_schema_as_map(): schema = b.Map({"name": b.Predicate(lambda name: 0 < len(name) < 25)}) assert schema.validate({ "name": "First name", "age": "28" }) == { "name": "First name" } schema = b.Map({ "name": b.And(b.Predicate(lambda name: 0 < len(name) < 25), b.Pipe(len)) }) assert schema.validate({"name": "First name", "age": "28"}) == {"name": 10} with pytest.raises(SchemaErrors): schema.validate({"name": ""})
def test_schema_logic_and(): assert b.And(b.Pipe(int), b.Predicate(lambda n: n == 42)).validate("42") == 42 with pytest.raises(SchemaError): b.And(b.Pipe(str), b.Predicate(lambda n: n == 42)).validate("20")