def test_multi_type(self): s = Schema() s.add_object("string") s.add_object(1.1) s.add_object(True) s.add_object(None) self.assertEqual(s.to_dict(), {"type": ["boolean", "null", "number", "string"]})
class SchemaTestCase(unittest.TestCase): def setUp(self): self._schema = Schema() self._objects = [] self._schemas = [] def set_schema_options(self, **options): self._schema = Schema(**options) def add_object(self, obj): self._schema.add_object(obj) self._objects.append(obj) def add_schema(self, schema): self._schema.add_schema(schema) self._schemas.append(schema) def assertObjectValidates(self, obj): jsonschema.Draft4Validator(self._schema.to_dict()).validate(obj) def assertObjectDoesNotValidate(self, obj): with self.assertRaises(jsonschema.exceptions.ValidationError): jsonschema.Draft4Validator(self._schema.to_dict()).validate(obj) def assertResult(self, expected): self.assertEqual(self._schema.to_dict(), expected) self.assertUserContract() def assertUserContract(self): self._assertSchemaIsValid() self._assertComponentObjectsValidate() def _assertSchemaIsValid(self): jsonschema.Draft4Validator.check_schema(self._schema.to_dict()) def _assertComponentObjectsValidate(self): compiled_schema = self._schema.to_dict() for obj in self._objects: jsonschema.Draft4Validator(compiled_schema).validate(obj)
def test_multi_type(self): s = Schema() s.add_object('string') s.add_object(1.1) s.add_object(True) s.add_object(None) self.assertSchema(s.to_dict(), {'type': ['boolean', 'null', 'number', 'string']})
def test_multi_type(self): s = Schema() s.add_object('string') s.add_object(1.1) s.add_object(True) s.add_object(None) self.assertEqual(s.to_dict(), {'type': ['boolean', 'null', 'number', 'string']})
def test_redundant_integer_type(self): s = Schema() s.add_object(1) s.add_object(1.1) self.assertSchema(s.to_dict(), {'type': 'number'})
def test_single_type(self): s = Schema() s.add_object('bacon') s.add_object('egg') s.add_object('spam') self.assertSchema(s.to_dict(), {'type': 'string'})
def test_recurse_deprecation_warning(self): with self.assertWarns(DeprecationWarning): builder = Schema() builder.add_object('Go away or I shall taunt you a second time!') builder.to_dict(recurse=True)
def test_to_dict_pending_deprecation_warning(self): with self.assertWarns(PendingDeprecationWarning): builder = Schema() with self.assertWarns(PendingDeprecationWarning): builder.add_object('I fart in your general direction!') builder.to_dict()
class Yaml2JsonSchema: schemas = list() stack = list() cur = str() def __init__(self, filename=None): self.__yaml = "" self.__json = "" self.__genson = Schema() if filename: self.open(filename) def is_valid(self, value): try: validate(value, Json.loads(self.yaml_to_jsonschema())) sys.stdout.write("OK\n") except ValidationError as ve: sys.stderr.write("Validation Error\n") sys.stderr.write(str(ve) + "\n") return False return True def to_jsonschema(self): return self.__genson.to_json(indent=2) def to_jsonloads(self): return Json.loads(self.json) def yaml_to_jsonschema(self): return self.ex_yaml(self.yaml.split('\n')) @property def json(self): return self.__json @property def yaml(self): return self.__yaml @yaml.setter def yaml(self, yaml): self.__yaml = yaml json = Yaml.load(self.yaml) self.__json = Json.dumps(json, indent=2) self.__genson.add_object(json) def open(self, filename): with open(filename, 'r') as f: data = f.read() self.yaml = data def ex_yaml(self, v): schema_list = Yaml2JsonSchema.yaml_extention_parser(v) for s in schema_list: self.__genson.add_schema(s) return self.to_jsonschema() @staticmethod def make_json_schema(v, value, buf=None): if buf is None: buf = dict() if not v: buf.update({"properties": value}) return buf name = v.pop(0) buf.update({"properties": {name: dict()}}) return Yaml2JsonSchema.make_json_schema( v, value, buf["properties"][name]) @staticmethod def yaml_extention_parser(v, depth=0): # 데이터 아님 while True: if not v: return Yaml2JsonSchema.schemas d = v.pop(0) if -1 == d.find(":"): continue break # 하위 아이템 존재 if ":" == d[-1]: len_current = len(d) - len(d.lstrip()) # 하위 아이템 if depth <= len_current: depth = len_current name = d[:-1].strip() Yaml2JsonSchema.stack.append(name) # 상위로 돌아감 elif depth > len_current: depth = len_current Yaml2JsonSchema.stack.pop() # 같은 레벨 else: pass # 확장 코드 elif -1 < d.find("#! "): info = d.strip()[3:] name = info[:info.find(":")] value = info[info.find(":") + 2:] if value.isdigit(): value = int(value) if value.isdecimal() else float(value) value = {Yaml2JsonSchema.cur: {name: value}} buf = dict() cs = copy.deepcopy(Yaml2JsonSchema.stack) temp = buf Yaml2JsonSchema.make_json_schema(cs, value, temp) Yaml2JsonSchema.schemas.append(buf) else: d = d.strip() name = d[:d.find(":")] Yaml2JsonSchema.cur = name return Yaml2JsonSchema.yaml_extention_parser(v, depth)
def test_redundant_integer_type(self): s = Schema() s.add_object(1) s.add_object(1.1) self.assertEqual(s.to_dict(), {"type": "number"})
def test_single_type(self): s = Schema() s.add_object("bacon") s.add_object("egg") s.add_object("spam") self.assertEqual(s.to_dict(), {"type": "string"})
def test_single_type(self): s = Schema() s.add_object('bacon') s.add_object('egg') s.add_object('spam') self.assertEqual(s.to_dict(), {'type': 'string'})
def test_redundant_integer_type(self): s = Schema() s.add_object(1) s.add_object(1.1) self.assertEqual(s.to_dict(), {'type': 'number'})