Ejemplo n.º 1
1
 def test_multiple_schemas(self):
     s1 = {
         "required": [
             "a",
             "c"
         ],
         "type": "object",
         "properties": {
             "a": {
                 "type": "string"
             },
             "c": {
                 "items": [
                     {
                         "type": "integer"
                     }
                 ],
                 "type": "array"
             }
         }
     }
     s2 = {
         "required": [
             "c"
         ],
         "type": "object",
         "properties": {
             "a": {
                 "type": "string"
             },
             "c": {
                 "items": [
                     {
                         "type": "integer"
                     }
                 ],
                 "type": "array"
             }
         }
     }
     s = Schema()
     s.add_schema(s1)
     s.add_schema(s2)
     self.assertEqual(s.to_dict(), s2)
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
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)
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
 def test_preserves_existing_keys(self):
     schema = {'type': 'number', 'value': 5}
     s = Schema()
     s.add_schema(schema)
     self.assertSchema(s.to_dict(), schema)
Ejemplo n.º 6
0
 def test_multi_type(self):
     schema = {'type': ['boolean', 'null', 'number', 'string']}
     s = Schema()
     s.add_schema(schema)
     self.assertSchema(s.to_dict(), schema)
Ejemplo n.º 7
0
 def test_single_type_unicode(self):
     schema = {u'type': u'string'}
     s = Schema()
     s.add_schema(schema)
     self.assertSchema(s.to_dict(), schema)
Ejemplo n.º 8
0
 def test_no_schema(self):
     schema = {}
     s = Schema()
     s.add_schema(schema)
     self.assertSchema(s.to_dict(), schema)
Ejemplo n.º 9
0
 def test_preserves_existing_keys(self):
     schema = {'type': 'number', 'value': 5}
     s = Schema()
     s.add_schema(schema)
     self.assertEqual(s.to_dict(), schema)
Ejemplo n.º 10
0
 def test_multi_type(self):
     schema = {'type': ['boolean', 'null', 'number', 'string']}
     s = Schema()
     s.add_schema(schema)
     self.assertEqual(s.to_dict(), schema)
Ejemplo n.º 11
0
 def test_single_type_unicode(self):
     schema = {u'type': u'string'}
     s = Schema()
     s.add_schema(schema)
     self.assertEqual(s.to_dict(), schema)
Ejemplo n.º 12
0
 def test_no_schema(self):
     schema = {}
     s = Schema()
     s.add_schema(schema)
     self.assertEqual(s.to_dict(), schema)
Ejemplo n.º 13
0
 def test_single_type(self):
     schema = {'type': 'string'}
     s = Schema()
     s.add_schema(schema)
     self.assertSchema(s.to_dict(), schema)
Ejemplo n.º 14
0
 def test_single_type(self):
     schema = {'type': 'string'}
     s = Schema()
     s.add_schema(schema)
     self.assertEqual(s.to_dict(), schema)