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"
def test_schema_singledispatch(): import os assert type(b.schema(int)) == b.Pipe assert type(b.schema(lambda: 3 < 2)) == b.Predicate assert type(b.schema(os.path.exists)) == b.Predicate assert type(b.schema({"age": b.Pipe("int")})) == b.Map
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_as_map_required_fields(): assert b.Map({ "name": b.Pipe(str), "age": b.Pipe(int) }).required == {"name", "age"} assert b.Map({ "name": b.Pipe(str), b.Optional("age"): b.Pipe(int) }).required == {"name"} with pytest.raises(SchemaErrors): b.Map({ "name": b.Pipe(str), "age": b.Pipe(int) }).validate({"name": "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")
def test_schema_as_pipe(): assert b.Pipe(int).validate("123") == 123 assert b.Pipe(int, str).validate(123.0) == "123" assert b.Pipe(int, str, lambda _: (42, )).validate(123.0) == (42, ) with pytest.raises(SchemaError): b.Pipe(int).validate(None)