def test_arr_partial(self): s = S.Array(validator=S.Integer()) val = [1, 2, 3, 'foo'] with self.assertRaises(S.Invalid) as err: s.validate(val) self.assertEqual(len(err.exception.array), len(val)) self.assertEqual(err.exception.array[:3], [None] * 3)
def compile_schema(metadata, s, **options): from barin import schema as S if s is None: return S.Anything() if isinstance(s, S.Validator): return s elif isinstance(s, six.string_types): return metadata[s].__barin__ elif hasattr(s, '__barin__'): return compile_schema(metadata, s.__barin__, **options) elif isinstance(s, list): if len(s) == 1: schema = compile_schema(metadata, s[0]) return S.Array(validator=schema, **options) elif len(s) == 0: return S.Array(**options) else: raise S.Invalid('Invalid schema {}'.format(s)) elif isinstance(s, dict): fields = dict((name, compile_schema(metadata, value)) for name, value in s.items()) extra_validator = fields.pop(str, S.Missing) return S.Document(fields=fields, extra_validator=extra_validator, **options) elif not isinstance(s, type): if hasattr(s, 'make_schema'): return s.make_schema(**options) elif hasattr(s, 'schema'): return s.schema else: raise S.Invalid('Invalid schema {}'.format(s), s) elif issubclass(s, S.Validator): return s(**options) elif issubclass(s, six.integer_types): return S.Integer(**options) elif issubclass(s, datetime): return S.DateTime(**options) elif issubclass(s, float): return S.Float(**options) elif issubclass(s, six.string_types): return S.Unicode(**options) else: raise S.Invalid('Invalid schema {}'.format(s), s)
def test_int_fail(self): s = S.Integer() with self.assertRaises(S.Invalid): s.validate('5')
def test_int_ok(self): s = S.Integer() v = s.validate(5) self.assertEqual(v, 5)
def test_arr_only_begin(self): s = S.Array(validator=S.Integer(), only_validate=slice(None, 2)) val = [1, 2, 3, 'foo'] res = s.validate(val) self.assertEqual(val, res)
def test_arr_notarr_fail(self): s = S.Array(validator=S.Integer()) val = '5' with self.assertRaises(S.Invalid): s.validate(val)
def test_arr_ok(self): s = S.Array(validator=S.Integer()) val = [5] res = s.validate(val) self.assertEqual(res, val)
def test_doc_partial(self): s = S.Document(fields=dict(x=S.Integer(), y=S.Integer())) val = {'x': 1, 'y': 'foo'} with self.assertRaises(S.Invalid) as err: s.validate(val) self.assertEqual(list(err.exception.document), ['y'])
def test_doc_missing_default(self): s = S.Document(fields=dict(x=S.Integer(default=None))) val = {} res = s.validate(val) self.assertEqual(res, {'x': None})
def test_doc_missing_fail(self): s = S.Document(fields=dict(x=S.Integer())) val = {} with self.assertRaises(S.Invalid) as err: s.validate(val) self.assertIsInstance(err.exception.document['x'], S.Invalid)
def test_doc_notdoc_fail(self): s = S.Document(fields=dict(x=S.Integer())) val = 5 with self.assertRaises(S.Invalid): s.validate(val)
def test_doc_ok(self): s = S.Document(fields=dict(x=S.Integer())) val = {'x': 5} res = s.validate(val) self.assertEqual(res, val)