예제 #1
0
 def __init__(self, args):
     self.args = args
     self.tmpfile = 'pylintout.txt'
     builder = pjs.ObjectBuilder(
         os.path.join(os.path.dirname(os.path.abspath(__file__)),
                      'sarif-schema.json'))
     self.sarif = builder.build_classes()
def test_build_classes_is_idempotent():
    schema = {
        "$schema": "http://json-schema.org/schema#",
        "title": "test",
        "type": "object",
        "properties": {
            "name": {
                "$ref": "#/definitions/foo"
            },
            "email": {
                "oneOf": [{
                    "type": "string"
                }, {
                    "type": "integer"
                }]
            },
        },
        "required": ["email"],
        "definitions": {
            "reffed": {
                "type": "string"
            },
            "foo": {
                "type": "array",
                "items": {
                    "$ref": "#/definitions/reffed"
                }
            },
        },
    }
    builder = pjs.ObjectBuilder(schema)
    x = builder.build_classes()
    builder.build_classes()
def test_underscore_properties():
    schema = {
        "$schema": "http://json-schema.org/schema#",
        "title": "AggregateQuery",
        "type": "object",
        "properties": {
            "group": {
                "type": "object",
                "properties": {}
            }
        },
    }

    builder = pjs.ObjectBuilder(schema)
    ns = builder.build_classes()
    my_obj_type = ns.Aggregatequery
    request_object = my_obj_type(
        group={
            "_id": {
                "foo_id": "$foo_id",
                "foo_type": "$foo_type"
            },
            "foo": {
                "$sum": 1
            },
        })

    assert request_object.group._id == {
        "foo_id": "$foo_id",
        "foo_type": "$foo_type"
    }
예제 #4
0
    def test_simple_person(self):
        schema = {
            'definitions': {
                'Person': {
                    'type': 'object',
                    'additionalProperties': False,
                    'properties': {
                        'name': {
                            'type': 'string'
                        },
                        'employee_id': {
                            'type': 'string'
                        },
                    },
                    'required': ['name', 'employee_id'],
                },
            },
            'title': 'definitions',
            'type': 'object',
        }

        builder = pjs.ObjectBuilder(schema)
        ns = builder.build_classes()
        Person = ns.Person
        martin = Person(name='Martin Ertsås', employee_id='385254')
        self.assertEqual('Martin Ertsås', martin.name)
        self.assertEqual('385254', martin.employee_id)
예제 #5
0
def test_null_type_one_of():

    schema = {
        "$schema": "http://json-schema.org/draft-04/schema",
        "title": "Example1",
        "type": "object",
        "properties": {
            "foo": {
                "oneOf": [
                    {
                        "type": "string"
                    },
                    {
                        "type": "null"
                    }
                ]
            }
        },
        "required": [
            "foo"
        ]
    }

    ns1 = pjs.ObjectBuilder(schema).build_classes(strict=True)
    ns1.Example1(foo='bar')
    ns1.Example1(foo=None)
예제 #6
0
def test_array_wrapper(complex_schema):
    instance = {
        "scenario_config": {
            "location_master": "MOCK"
        },
        "status":
        "pending",
        "boundary": [{
            "lat": 38.8821,
            "lng": -77.11461
        }, {
            "lat": 38.882403,
            "lng": -77.107867
        }, {
            "lat": 38.876293,
            "lng": -77.1083
        }, {
            "lat": 38.880834,
            "lng": -77.115043
        }],
        "name":
        "Test1",
        "members": ["Frobnaz", "MOCK"]
    }

    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger().setLevel(logging.DEBUG)
    builder = pjo.ObjectBuilder(complex_schema)
    ns = builder.build_classes()
    m = ns.Mission(**instance)
    m.validate()
def test_additional_props_permitted_explicitly(markdown_examples):
    builder = pjs.ObjectBuilder(markdown_examples['AddlPropsAllowed'], resolved=markdown_examples)
    assert builder

    test = builder.classes['Addlpropsallowed']()
    test.randomAttribute = 40
    assert int(test.randomAttribute) == 40
예제 #8
0
 def __init__(self, args):
     self.args = args
     self.tmpfile = 'pylintout.txt'
     builder = pjs.ObjectBuilder(
         '../sarif-spec/Documents/CommitteeSpecificationDrafts/CSD.1/sarif-schema.json'
     )
     self.sarif = builder.build_classes()
def test_array_regressions():
    schema = {
        "$schema": "http://json-schema.org/schema#",
        "$id": "test",
        "type": "object",
        "properties": {
                "name": {"type": "string"},
                "email_aliases": {
                    "type": "object",
                    "additionalProperties": {
                        "type": "array",
                        "items": {"$ref": "#/definitions/foo"}
                    }
                }
        },
        "definitions": {
            "foo": {
                "type": "string"
            }
        }
    }
    builder = pjs.ObjectBuilder(schema)

    ns = builder.build_classes()

    x = ns.Test.from_json('''{"email_aliases": {
            "Freddie": ["james", "bond"]
            }}''')
    x.validate()

    y = ns.Test(email_aliases={
        "Freddie": ["james", "bond"]
    })
    y.validate()
def test_arrays_can_have_reffed_items_of_mixed_type():
    schema = {
            "$schema": "http://json-schema.org/schema#",
            "$id": "test",
            "type": "object",
            "properties": {
                "list": {
                    "type": "array",
                    "items": {"oneOf": [
                        {"$ref": "#/definitions/foo"},
                        {
                            "type": "object",
                            "properties": {
                                "bar": {"type":"string"}
                                },
                            "required": ["bar"]
                        }
                        ]},
                    }
                },
            "definitions": {
                "foo": {
                    "type": "string"
                    }
                }
            }
    builder = pjs.ObjectBuilder(schema)
    ns = builder.build_classes()

    ns.Test(list=["foo", "bar"])
    ns.Test(list=[{"bar": "nice"}, "bar"])
    with pytest.raises(pjs.ValidationError):
        ns.Test(list=[100])
def test_nested_arrays_work_fine():
    schema = {
        "title": "Example Schema",
        "type": "object",
        "properties": {
            "a": {
                "type": "array",
                "items": {
                    "type": "string"
                },
                "default": []
            }
        },
    }

    ns1 = pjs.ObjectBuilder(schema).build_classes()

    foo = ns1.ExampleSchema()
    foo.a.append("foo")
    print(foo.for_json())

    assert foo.a == ["foo"]

    bar = ns1.ExampleSchema()
    bar.a.append("bar")
    print(bar.for_json())

    assert bar.a == ["bar"]
예제 #12
0
def sample(source):
    if not source or ('properties' not in source) or len(
            source['properties']) == 0:
        return {}

    schema = {
        'title': 'Example',
        'properties': {},
        'type': 'object',
        'required': [],
    }

    definitions = {}

    if source.get('definitions'):
        schema['definitions'] = source['definitions']

        for key, defin in source['definitions'].items():
            definitions['#/definitions/' + key] = defin

    defaults = default_for_object(source, definitions)

    for key, prop in source['properties'].items():
        prop = copy.copy(prop)
        schema['properties'][key] = prop
        schema['required'].append(key)

    builder = pjs.ObjectBuilder(schema)
    ns = builder.build_classes(strict=True)
    clazz = ns.Example
    o = clazz(**defaults)
    return o.as_dict()
def test_114():
    schema = {
        "title": "Example",
        "type": "object",
        "properties": {
            "test_regression_114_anon_array": {
                "type":
                "array",
                "items": [{
                    "oneOf": [
                        {
                            "type":
                            "string",
                            "pattern":
                            "^(?:(?:\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(?:\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])$",
                        },
                        {
                            "type":
                            "string",
                            "pattern":
                            "^((([0-9A-Fa-f]{1,4}:){1,6}:)|(([0-9A-Fa-f]{1,4}:){7}))([0-9A-Fa-f]{1,4})$",
                        },
                    ]
                }],
            }
        },
    }

    builder = pjo.ObjectBuilder(schema)
    test = builder.build_classes()
    assert test
def test_nested_arrays_work_fine():
    schema = {
        "$schema": "http://json-schema.org/draft-04/schema",
        "title": "Example1",
        "type": "object",
        "properties": {
            "name": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "name": {
                            "type": "string"
                        }
                    }
                }
            }
        }
    }

    ns1 = pjs.ObjectBuilder(schema).build_classes()
    j1 = ns1.Example1.from_json(
        json.dumps({'name': [{
            'value': 'foo'
        }, {
            'value': 'bar'
        }]}))
    assert j1.name[0].value == 'foo'
    assert j1.name[1].value == 'bar'
예제 #15
0
def test_justareference_example(markdown_examples):

    builder = pjs.ObjectBuilder(
        markdown_examples["Just a Reference"], resolved=markdown_examples
    )
    ns = builder.build_classes()
    ns.JustAReference("Hello")
예제 #16
0
def _add_enums_from_oneof_types(target_object, param, method):
    """
    Create a type for each oneOf type in param and add it to target_object.

    :param object target_object: The target object where to add the oneOf types to
    :param list param: the oneOf array
    :param str method: name of RPC
    """
    for o in param:
        classes = pjs.ObjectBuilder(o).build_classes()
        class_names = dir(classes)

        # find the generated class name that matches our schema root title
        class_name = None
        for c in class_names:
            if c.lower() == inflection.camelize(o['title'].replace(' ', '_')).lower():
                class_name = c
                break

        # create class name <Type><Method w/o set->, e.g. Perspective+CameraParams
        pretty_class_name = underscorize(method[4:])
        pretty_class_name = inflection.camelize(pretty_class_name)
        pretty_class_name = class_name + pretty_class_name

        # add type to target_object
        class_type = getattr(classes, class_name)
        setattr(target_object, pretty_class_name, class_type)

        # create and add potential enums to type
        _add_enums(class_type(), class_type)
def test_strict_mode():
    schema = {
        "$schema": "http://json-schema.org/schema#",
        "type": "object",
        "properties": {
            "firstName": {
                "type": "string"
            },
            "lastName": {
                "type": "string"
            }
        },
        "$id": "test",
        "title": "Name Data",
        "required": ["firstName"],
    }
    builder = pjs.ObjectBuilder(schema)
    ns = builder.build_classes()  # by defualt strict = False
    NameData = ns.NameData
    # no strict flag - so should pass even no firstName
    NameData(lastName="hello")
    with pytest.raises(pjs.ValidationError):
        ns = builder.build_classes(strict=True)
        NameData = ns.NameData
        NameData(lastName="hello")
예제 #18
0
    def __init__(self, document: JSDocument, schema: JSSchema):
        validate_model(document, schema)
        self._document = document

        builder = pjs.ObjectBuilder(schema)
        self._namespace = builder.build_classes(strict=True,
                                                named_only=False,
                                                standardize_names=False)
예제 #19
0
def test_object_builder_loads_memory_references(markdown_examples):
    builder = pjs.ObjectBuilder(markdown_examples["Other"], resolved=markdown_examples)
    assert builder

    with pytest.raises(pjs.ValidationError):
        builder.validate({"MyAddress": 1234})

    builder.validate({"MyAddress": "1234"})
예제 #20
0
 def __init__(self, schema):
     self.schema = schema
     builder = pjs.ObjectBuilder(self.schema)
     classes = builder.build_classes()
     name = inflection.camelize(self.name())
     if name not in classes:
         raise MissingResourceSchemaError(name)
     self._schema = classes[name]
def test_multiple_objects_are_defined(markdown_examples):
    builder = pjs.ObjectBuilder(markdown_examples['MultipleObjects'],
                                resolved=markdown_examples)

    assert builder
    classes = builder.build_classes()
    assert 'ErrorResponse' in classes
    assert 'VersionGetResponse' in classes
    print(dir(classes))
예제 #22
0
파일: run.py 프로젝트: johnsonyue/schema
  def __get_class_from_schema__(self):
    # schema namespace
    builder = pjs.ObjectBuilder( self.schema )
    ns = builder.build_classes()
    # classes in namespace
    TaskGraph = ns.TaskGraph
    Step = ns.Step; Task = ns.Task;

    return TaskGraph, Step, Task
예제 #23
0
    def _get_ns(cls):
        if not cls._ns:
            # Suppress logging inside of python_jsonschema_objects module
            logger = logging.getLogger(
                "python_jsonschema_objects.classbuilder")
            logger.disabled = True

            builder = pjs.ObjectBuilder(BIOMIO_protocol_json_schema)
            cls._ns = builder.build_classes()
        return cls._ns
예제 #24
0
def arrayClass():
    schema = {
        "title": "ArrayVal",
        "type": "object",
        "properties": {
            "min": {
                "type": "array",
                "items": {
                    "type": "string"
                },
                "default": [],
                "minItems": 1,
            },
            "max": {
                "type": "array",
                "items": {
                    "type": "string"
                },
                "default": [],
                "maxItems": 1,
            },
            "both": {
                "type": "array",
                "items": {
                    "type": "string"
                },
                "default": [],
                "maxItems": 2,
                "minItems": 1,
            },
            "unique": {
                "type": "array",
                "items": {
                    "type": "string"
                },
                "default": [],
                "uniqueItems": True,
            },
            "reffed": {
                "type": "array",
                "items": {
                    "$ref": "#/definitions/myref"
                },
                "minItems": 1,
            },
        },
        "definitions": {
            "myref": {
                "type": "string"
            }
        },
    }

    ns = pjo.ObjectBuilder(schema).build_classes()
    return ns["Arrayval"](min=["1"], both=["1"])
예제 #25
0
def test_warnings_on_schema_version(version, warn):
    schema = {"$schema": version, "$id": "test", "type": "object", "properties": {}}

    with warnings.catch_warnings(record=True) as w:
        pjs.ObjectBuilder(schema)

        if warn:
            assert len(w) == 1
            assert "Schema version %s not recognized" % version in str(w[-1].message)
        else:
            assert len(w) == 0, w[-1].message
예제 #26
0
def test_boolean_in_child_object():
    schema = {
        "$schema": "http://json-schema.org/schema#",
        "$id": "test",
        "type": "object",
        "properties": {"data": {"type": "object", "additionalProperties": True}},
    }
    builder = pjs.ObjectBuilder(schema)
    ns = builder.build_classes()

    ns.Test(data={"my_bool": True})
예제 #27
0
def test_nested_array_regression(nested_arrays, instance):
    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger().setLevel(logging.DEBUG)
    builder = pjo.ObjectBuilder(nested_arrays)
    ns = builder.build_classes()

    q = ns.Example.from_json(json.dumps(instance))

    assert q.serialize() == '{"foo": [[42, 44]]}'

    assert q.as_dict() == {"foo": [[42, 44]]}
def test_nested_oneofs_still_work(schema_json):
    builder = pjo.ObjectBuilder(schema_json)
    ns = builder.build_classes()

    obj1 = ns.MainObject(**{"location": {"type": "Location1"}})
    obj2 = ns.MainObject(**{"location": {"type": "Location2"}})
    obj3 = ns.MainObject(**{"location": "unique:12"})

    assert obj1.location.type == "Location1"
    assert obj2.location.type == "Location2"
    assert obj3.location == "unique:12"
예제 #29
0
def test_array_length_validates(markdown_examples):

    builder = pjo.ObjectBuilder(markdown_examples["Example Schema"],
                                resolved=markdown_examples)
    ns = builder.build_classes()

    with pytest.raises(pjo.ValidationError):
        ns.ExampleSchema(
            firstName="Fred",
            lastName="Huckstable",
            dogs=["Fido", "Spot", "Jasper", "Lady", "Tramp"],
        )
예제 #30
0
    def test_multiple_classes(self):
        schema = {
            'definitions': {
                'Person': {
                    'type': 'object',
                    'additionalProperties': False,
                    'properties': {
                        'name': {
                            'type': 'string'
                        },
                        'employee_id': {
                            'type': 'string'
                        },
                    },
                    'required': ['name', 'employee_id'],
                },
            },
            'title': 'definitions',
            'type': 'object',
            'properties': {
                'NotAttending': {
                    'allOf': [
                        {
                            '$ref': '#/definitions/Person',
                        },
                        {
                            'properties': {
                                'info': {
                                    'type': 'string'
                                },
                            },
                            'required': ['info'],
                        },
                    ],
                },
            },
        }

        builder = pjs.ObjectBuilder(schema)
        ns = builder.build_classes()
        Person = ns.Person
        martin = Person(name='Martin Ertsås', employee_id='385254')
        self.assertEqual('Martin Ertsås', martin.name)
        self.assertEqual('385254', martin.employee_id)

        NotAttending = ns.NotAttending
        olve = NotAttending(name='Olve Maudal',
                            employee_id='123456',
                            info='foo')
        self.assertEqual('Olve Maudal', olve.name)
        self.assertEqual('123456', olve.employee_id)
        self.assertEqual('foo', olve.info)