Esempio n. 1
0
    def test_model_as_nested_dict(self):
        address = Model("Address", {"road": fields.String,})

        person = Model(
            "Person",
            {
                "name": fields.String,
                "age": fields.Integer,
                "birthdate": fields.DateTime,
                "address": fields.Nested(address),
            },
        )

        assert person.__schema__ == {
            # 'required': ['address'],
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer"},
                "birthdate": {"type": "string", "format": "date-time"},
                "address": {"$ref": "#/definitions/Address",},
            },
            "type": "object",
        }

        assert address.__schema__ == {
            "properties": {"road": {"type": "string"},},
            "type": "object",
        }
Esempio n. 2
0
    def test_polymorph_inherit_common_ancestor(self):
        class Child1:
            pass

        class Child2:
            pass

        parent = Model("Person", {"name": fields.String, "age": fields.Integer,})

        child1 = parent.inherit("Child1", {"extra1": fields.String,})

        child2 = parent.inherit("Child2", {"extra2": fields.String,})

        mapping = {
            Child1: child1,
            Child2: child2,
        }

        output = Model("Output", {"child": fields.Polymorph(mapping)})

        # Should use the common ancestor
        assert output.__schema__ == {
            "properties": {"child": {"$ref": "#/definitions/Person"},},
            "type": "object",
        }
Esempio n. 3
0
    def test_model_deepcopy(self):
        parent = Model('Person', {
            'name': fields.String,
            'age': fields.Integer(description="foo"),
        })

        child = parent.inherit('Child', {
            'extra': fields.String,
        })

        parent_copy = copy.deepcopy(parent)

        assert parent_copy["age"].description == "foo"

        parent_copy["age"].description = "bar"

        assert parent["age"].description == "foo"
        assert parent_copy["age"].description == "bar"

        child = parent.inherit('Child', {
            'extra': fields.String,
        })

        child_copy = copy.deepcopy(child)
        assert child_copy.__parents__[0] == parent
Esempio n. 4
0
    def test_inherit_from_class(self):
        parent = Model('Parent', {
            'name': fields.String,
            'age': fields.Integer,
        })

        child = Model.inherit('Child', parent, {
            'extra': fields.String,
        })

        assert parent.__schema__ == {
            'properties': {
                'name': {'type': 'string'},
                'age': {'type': 'integer'},
            },
            'type': 'object'
        }
        assert child.__schema__ == {
            'allOf': [
                {'$ref': '#/definitions/Parent'},
                {
                    'properties': {
                        'extra': {'type': 'string'}
                    },
                    'type': 'object'
                }
            ]
        }
Esempio n. 5
0
    def test_clone_from_class(self):
        parent = Model('Parent', {
            'name': fields.String,
            'age': fields.Integer,
            'birthdate': fields.DateTime,
        })

        child = Model.clone('Child', parent, {
            'extra': fields.String,
        })

        assert child.__schema__ == {
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                },
                'extra': {
                    'type': 'string'
                }
            },
            'type': 'object'
        }
Esempio n. 6
0
    def test_inherit_from_instance_from_multiple_parents(self):
        grand_parent = Model('GrandParent', {
            'grand_parent': fields.String,
        })

        parent = Model('Parent', {
            'name': fields.String,
            'age': fields.Integer,
        })

        child = grand_parent.inherit('Child', parent, {
            'extra': fields.String,
        })

        assert child.__schema__ == {
            'allOf': [
                {'$ref': '#/definitions/GrandParent'},
                {'$ref': '#/definitions/Parent'},
                {
                    'properties': {
                        'extra': {'type': 'string'}
                    },
                    'type': 'object'
                }
            ]
        }
Esempio n. 7
0
    def test_extend_is_deprecated(self):
        parent = Model('Parent', {
            'name': fields.String,
            'age': fields.Integer,
            'birthdate': fields.DateTime,
        })

        with pytest.warns(DeprecationWarning):
            child = parent.extend('Child', {
                'extra': fields.String,
            })

        assert child.__schema__ == {
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                },
                'extra': {
                    'type': 'string'
                }
            },
            'type': 'object'
        }
Esempio n. 8
0
def _make_response_data_model(
    name: str, fields: Dict[str, Raw], skip_none: Optional[bool] = False
) -> Tuple[Model, Model]:
    model = Model(f"{name}Data", fields)
    return model, Model(
        f"{name}Response", {"message": String(), "data": Nested(model, skip_none=skip_none)}
    )
Esempio n. 9
0
    def test_inherit_from_instance_from_multiple_parents(self):
        grand_parent = Model("GrandParent", {"grand_parent": fields.String,})

        parent = Model("Parent", {"name": fields.String, "age": fields.Integer,})

        child = grand_parent.inherit("Child", parent, {"extra": fields.String,})

        assert child.__schema__ == {
            "allOf": [
                {"$ref": "#/definitions/GrandParent"},
                {"$ref": "#/definitions/Parent"},
                {"properties": {"extra": {"type": "string"}}, "type": "object"},
            ]
        }
Esempio n. 10
0
    def test_inherit_from_class(self):
        parent = Model("Parent", {"name": fields.String, "age": fields.Integer,})

        child = Model.inherit("Child", parent, {"extra": fields.String,})

        assert parent.__schema__ == {
            "properties": {"name": {"type": "string"}, "age": {"type": "integer"},},
            "type": "object",
        }
        assert child.__schema__ == {
            "allOf": [
                {"$ref": "#/definitions/Parent"},
                {"properties": {"extra": {"type": "string"}}, "type": "object"},
            ]
        }
Esempio n. 11
0
    def test_model_as_dict_with_list(self):
        model = Model(
            'Person', {
                'name': fields.String,
                'age': fields.Integer,
                'tags': fields.List(fields.String),
            })

        assert model.__schema__ == {
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'tags': {
                    'type': 'array',
                    'items': {
                        'type': 'string'
                    }
                }
            },
            'type': 'object'
        }
Esempio n. 12
0
 def get_restx_model() -> Model:
     return Model(
         "recipe_model",
         {
             "id": restxFields.Integer(readonly=True),
             "time_created": restxFields.DateTime(readonly=True),
             "time_updated": restxFields.DateTime(readonly=True),
             "name": restxFields.String(),
             "macros": restxFields.Raw(readonly=True),
             "directions": restxFields.List(restxFields.String),
             "image_url": restxFields.String(),
             "recipe_url": restxFields.String(),
             "thumbnail_url": restxFields.String(),
             "author": restxFields.String(),
             "servings": restxFields.Integer(),
             "rating": restxFields.Integer(),
             "prep_time": restxFields.Integer(),
             "cook_time": restxFields.Integer(),
             "source_name": restxFields.String(),
             "diets": restxFields.List(restxFields.String),
             "dish_types": restxFields.List(restxFields.String),
             "tags": restxFields.List(restxFields.String),
             "cuisines": restxFields.List(restxFields.String),
             "ingredients": restxFields.List(restxFields.Raw),
         },
     )
Esempio n. 13
0
    def test_model_as_flat_dict(self):
        model = Model('Person', {
            'name': fields.String,
            'age': fields.Integer,
            'birthdate': fields.DateTime,
        })

        assert isinstance(model, dict)
        assert not isinstance(model, OrderedDict)

        assert model.__schema__ == {
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                }
            },
            'type': 'object'
        }
Esempio n. 14
0
 def test_models(self):
     todo_fields = Model(
         "Todo",
         {"task": fields.String(required=True, description="The task details")},
     )
     parser = RequestParser()
     parser.add_argument("todo", type=todo_fields)
     assert parser.__schema__ == [{"name": "todo", "type": "Todo", "in": "body",}]
Esempio n. 15
0
 def test_model_as_flat_dict(self):
     model = Model(
         'Store', {
             'product_name': fields.String,
             'description': fields.String,
             'list_price': fields.Float
         })
     self.assertIsInstance(model, dict)
     self.assertNotIsInstance(model, OrderedDict)
Esempio n. 16
0
    def test_model_as_nested_dict_with_list(self):
        address = Model('Address', {
            'road': fields.String,
        })

        person = Model(
            'Person', {
                'name': fields.String,
                'age': fields.Integer,
                'birthdate': fields.DateTime,
                'addresses': fields.List(fields.Nested(address))
            })

        assert person.__schema__ == {
            # 'required': ['address'],
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                },
                'addresses': {
                    'type': 'array',
                    'items': {
                        '$ref': '#/definitions/Address',
                    }
                }
            },
            'type': 'object'
        }

        assert address.__schema__ == {
            'properties': {
                'road': {
                    'type': 'string'
                },
            },
            'type': 'object'
        }
Esempio n. 17
0
 def get_restx_model() -> Model:
     return Model(
         "Cuisine Model",
         {
             "id": fields.Integer(readonly=True),
             "time_created": fields.DateTime(readonly=True),
             "time_updated": fields.DateTime(readonly=True),
             "name": fields.String(required=True),
         },
     )
Esempio n. 18
0
    def test_validate(self):
        from jsonschema import FormatChecker
        from werkzeug.exceptions import BadRequest

        class IPAddress(fields.Raw):
            __schema_type__ = 'string'
            __schema_format__ = 'ipv4'

        data = {'ip': '192.168.1'}
        model = Model('MyModel', {'ip': IPAddress()})

        # Test that validate without a FormatChecker does not check if a
        # primitive type conforms to the defined format property
        assert model.validate(data) is None

        # Test that validate with a FormatChecker enforces the check of the
        # format property and throws an error if invalid
        with pytest.raises(BadRequest):
            model.validate(data, format_checker=FormatChecker())
Esempio n. 19
0
    def test_model_deepcopy(self):
        parent = Model(
            "Person", {"name": fields.String, "age": fields.Integer(description="foo"),}
        )

        child = parent.inherit("Child", {"extra": fields.String,})

        parent_copy = copy.deepcopy(parent)

        assert parent_copy["age"].description == "foo"

        parent_copy["age"].description = "bar"

        assert parent["age"].description == "foo"
        assert parent_copy["age"].description == "bar"

        child = parent.inherit("Child", {"extra": fields.String,})

        child_copy = copy.deepcopy(child)
        assert child_copy.__parents__[0] == parent
Esempio n. 20
0
 def test_model_as_flat_dict(self):
     model = Model(
         'Store', {
             'store_name': fields.String,
             'phone': fields.String,
             'email': fields.String,
             'street': fields.String,
             'city': fields.String,
             'state': fields.String
         })
     self.assertIsInstance(model, dict)
     self.assertNotIsInstance(model, OrderedDict)
Esempio n. 21
0
 def test_models(self):
     todo_fields = Model('Todo', {
         'task':
         fields.String(required=True, description='The task details')
     })
     parser = RequestParser()
     parser.add_argument('todo', type=todo_fields)
     assert parser.__schema__ == [{
         'name': 'todo',
         'type': 'Todo',
         'in': 'body',
     }]
Esempio n. 22
0
    def test_model_with_discriminator(self):
        model = Model(
            "Person",
            {"name": fields.String(discriminator=True), "age": fields.Integer,},
        )

        assert model.__schema__ == {
            "properties": {"name": {"type": "string"}, "age": {"type": "integer"},},
            "discriminator": "name",
            "required": ["name"],
            "type": "object",
        }
Esempio n. 23
0
    def test_clone_from_class(self):
        parent = Model(
            "Parent",
            {
                "name": fields.String,
                "age": fields.Integer,
                "birthdate": fields.DateTime,
            },
        )

        child = Model.clone("Child", parent, {"extra": fields.String,})

        assert child.__schema__ == {
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer"},
                "birthdate": {"type": "string", "format": "date-time"},
                "extra": {"type": "string"},
            },
            "type": "object",
        }
Esempio n. 24
0
    def test_extend_is_deprecated(self):
        parent = Model(
            "Parent",
            {
                "name": fields.String,
                "age": fields.Integer,
                "birthdate": fields.DateTime,
            },
        )

        with pytest.warns(DeprecationWarning):
            child = parent.extend("Child", {"extra": fields.String,})

        assert child.__schema__ == {
            "properties": {
                "name": {"type": "string"},
                "age": {"type": "integer"},
                "birthdate": {"type": "string", "format": "date-time"},
                "extra": {"type": "string"},
            },
            "type": "object",
        }
Esempio n. 25
0
    def test_parse_model(self, app):
        model = Model("Todo", {"task": fields.String(required=True)})

        parser = RequestParser()
        parser.add_argument("todo", type=model, required=True)

        data = {"todo": {"task": "aaa"}}

        with app.test_request_context(
            "/", method="post", data=json.dumps(data), content_type="application/json"
        ):
            args = parser.parse_args()
            assert args["todo"] == {"task": "aaa"}
Esempio n. 26
0
    def test_parse_model(self, app):
        model = Model('Todo', {'task': fields.String(required=True)})

        parser = RequestParser()
        parser.add_argument('todo', type=model, required=True)

        data = {'todo': {'task': 'aaa'}}

        with app.test_request_context('/',
                                      method='post',
                                      data=json.dumps(data),
                                      content_type='application/json'):
            args = parser.parse_args()
            assert args['todo'] == {'task': 'aaa'}
Esempio n. 27
0
    def test_clone_from_instance_with_multiple_parents(self):
        grand_parent = Model('GrandParent', {
            'grand_parent': fields.String,
        })

        parent = Model(
            'Parent', {
                'name': fields.String,
                'age': fields.Integer,
                'birthdate': fields.DateTime,
            })

        child = grand_parent.clone('Child', parent, {
            'extra': fields.String,
        })

        assert child.__schema__ == {
            'properties': {
                'grand_parent': {
                    'type': 'string'
                },
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                },
                'extra': {
                    'type': 'string'
                }
            },
            'type': 'object'
        }
Esempio n. 28
0
class CommonUserDto:
    user_model: Model = Model("User", {
        "username":
        fields.String(required=True, description='user name', example='admin'),
        "alias":
        fields.String(description='user alias'),
        "avatar":
        fields.String(description='user avatar'),
        "joined_date":
        fields.Integer(description='user joined time', attribute='created'),
        "update_date":
        fields.Integer(description='user info updated time',
                       attribute='updated'),
    },
                              mask="{*}")
Esempio n. 29
0
    def test_polymorph_inherit_common_ancestor(self):
        class Child1:
            pass

        class Child2:
            pass

        parent = Model('Person', {
            'name': fields.String,
            'age': fields.Integer,
        })

        child1 = parent.inherit('Child1', {
            'extra1': fields.String,
        })

        child2 = parent.inherit('Child2', {
            'extra2': fields.String,
        })

        mapping = {
            Child1: child1,
            Child2: child2,
        }

        output = Model('Output', {
            'child': fields.Polymorph(mapping)
        })

        # Should use the common ancestor
        assert output.__schema__ == {
            'properties': {
                'child': {'$ref': '#/definitions/Person'},
            },
            'type': 'object'
        }
Esempio n. 30
0
    def test_model_with_discriminator_override_require(self):
        model = Model('Person', {
            'name': fields.String(discriminator=True, required=False),
            'age': fields.Integer,
        })

        assert model.__schema__ == {
            'properties': {
                'name': {'type': 'string'},
                'age': {'type': 'integer'},
            },
            'discriminator': 'name',
            'required': ['name'],
            'type': 'object'
        }