def test_multiple_discriminator_field(self, api):
        model = api.model('Test', {
            'name': fields.String(discriminator=True),
            'name2': fields.String(discriminator=True),
        })

        with pytest.raises(ValueError):
            api.marshal(object(), model)
Exemple #2
0
    def test_discriminator_output(self, api):
        model = api.model('Test', {
            'name': fields.String(discriminator=True),
        })

        data = api.marshal({}, model)
        assert data == {'name': 'Test'}
    def test_api_payload(self, app, client):
        api = Api(app, validate=True)
        ns = Namespace('apples')
        api.add_namespace(ns)

        f = ns.model(
            'Person', {
                'name': fields.String(required=True),
                'age': fields.Integer,
                'birthdate': fields.DateTime,
            })

        @ns.route('/validation/')
        class Payload(Resource):
            payload = None

            @ns.expect(f)
            async def post(self, request):
                Payload.payload = ns.payload
                return {}

        data = {
            'name': 'John Doe',
            'age': 15,
        }

        client.post_json('/apples/validation/', data)

        assert Payload.payload == data
Exemple #4
0
 def test_with_callable_enum(self):
     enum = lambda: ['A', 'B', 'C']  # noqa
     field = fields.String(enum=enum)
     assert not field.required
     assert field.__schema__ == {
         'type': 'string',
         'enum': ['A', 'B', 'C'],
         'example': 'A'
     }
Exemple #5
0
 def test_with_enum(self):
     enum = ['A', 'B', 'C']
     field = fields.String(enum=enum)
     assert not field.required
     assert field.__schema__ == {
         'type': 'string',
         'enum': enum,
         'example': enum[0]
     }
Exemple #6
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',
     }]
Exemple #7
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'}
Exemple #8
0
    def test_with_scoped_attribute_on_dict_or_obj(self):
        class Test(object):
            def __init__(self, data):
                self.data = data

        class Nested(object):
            def __init__(self, value):
                self.value = value

        nesteds = [Nested(i) for i in ['a', 'b', 'c']]
        test_obj = Test(nesteds)
        test_dict = {'data': [{'value': 'a'}, {'value': 'b'}, {'value': 'c'}]}

        field = fields.List(fields.String(attribute='value'), attribute='data')
        assert ['a' == 'b', 'c'], field.output('whatever', test_obj)
        assert ['a' == 'b', 'c'], field.output('whatever', test_dict)
Exemple #9
0
    def test_polymorph_with_discriminator(self, api):
        parent = api.model('Person', {
            'name': fields.String,
            'model': fields.String(discriminator=True),
        })

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

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

        class Child1(object):
            name = 'child1'
            extra1 = 'extra1'

        class Child2(object):
            name = 'child2'
            extra2 = 'extra2'

        mapping = {Child1: child1, Child2: child2}

        thing = api.model('Thing', {
            'owner': fields.Polymorph(mapping),
        })

        def data(cls):
            return api.marshal({'owner': cls()}, thing)

        assert data(Child1) == {
            'owner': {
                'name': 'child1',
                'model': 'Child1',
                'extra1': 'extra1'
            }
        }

        assert data(Child2) == {
            'owner': {
                'name': 'child2',
                'model': 'Child2',
                'extra2': 'extra2'
            }
        }
Exemple #10
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'
        }
Exemple #11
0
    def test_model_with_required(self):
        model = Model(
            'Person', {
                'name': fields.String(required=True),
                'age': fields.Integer,
                'birthdate': fields.DateTime(required=True),
            })

        assert model.__schema__ == {
            'properties': {
                'name': {
                    'type': 'string'
                },
                'age': {
                    'type': 'integer'
                },
                'birthdate': {
                    'type': 'string',
                    'format': 'date-time'
                }
            },
            'required': ['birthdate', 'name'],
            'type': 'object'
        }
Exemple #12
0
 def test_with_default(self):
     field = fields.String(default='aaa')
     assert field.__schema__ == {'type': 'string', 'default': 'aaa'}
Exemple #13
0
 def test_defaults(self):
     field = fields.String()
     assert not field.required
     assert not field.discriminator
     assert field.__schema__ == {'type': 'string'}
Exemple #14
0
    def test_wildcard(self, api):
        wild1 = fields.Wildcard(fields.String)
        wild2 = fields.Wildcard(fields.Integer)
        wild3 = fields.Wildcard(fields.String)
        wild4 = fields.Wildcard(fields.String, default='x')
        wild5 = fields.Wildcard(fields.String)
        wild6 = fields.Wildcard(fields.Integer)
        wild7 = fields.Wildcard(fields.String)
        wild8 = fields.Wildcard(fields.String)

        mod5 = OrderedDict()
        mod5['toto'] = fields.Integer
        mod5['bob'] = fields.Integer
        mod5['*'] = wild5

        wild_fields1 = api.model('WildcardModel1', {'*': wild1})
        wild_fields2 = api.model('WildcardModel2', {'j*': wild2})
        wild_fields3 = api.model('WildcardModel3', {'*': wild3})
        wild_fields4 = api.model('WildcardModel4', {'*': wild4})
        wild_fields5 = api.model('WildcardModel5', mod5)
        wild_fields6 = api.model(
            'WildcardModel6', {
                'nested': {
                    'f1': fields.String(default='12'),
                    'f2': fields.Integer(default=13)
                },
                'a*': wild6
            })
        wild_fields7 = api.model('WildcardModel7', {'*': wild7})
        wild_fields8 = api.model('WildcardModel8', {'*': wild8})

        class Dummy(object):
            john = 12
            bob = '42'
            alice = None

        class Dummy2(object):
            pass

        class Dummy3(object):
            a = None
            b = None

        data = {'John': 12, 'bob': 42, 'Jane': '68'}
        data3 = Dummy()
        data4 = Dummy2()
        data5 = {'John': 12, 'bob': 42, 'Jane': '68', 'toto': '72'}
        data6 = {'nested': {'f1': 12, 'f2': 13}, 'alice': '14'}
        data7 = Dummy3()
        data8 = None
        expected1 = {'John': '12', 'bob': '42', 'Jane': '68'}
        expected2 = {'John': 12, 'Jane': 68}
        expected3 = {'john': '12', 'bob': '42'}
        expected4 = {'*': 'x'}
        expected5 = {'John': '12', 'bob': 42, 'Jane': '68', 'toto': 72}
        expected6 = {'nested': {'f1': '12', 'f2': 13}, 'alice': 14}
        expected7 = {}
        expected8 = {}

        result1 = api.marshal(data, wild_fields1)
        result2 = api.marshal(data, wild_fields2)
        result3 = api.marshal(data3, wild_fields3, skip_none=True)
        result4 = api.marshal(data4, wild_fields4)
        result5 = api.marshal(data5, wild_fields5)
        result6 = api.marshal(data6, wild_fields6)
        result7 = api.marshal(data7, wild_fields7, skip_none=True)
        result8 = api.marshal(data8, wild_fields8, skip_none=True)

        assert expected1 == result1
        assert expected2 == result2
        assert expected3 == result3
        assert expected4 == result4
        assert expected5 == result5
        assert expected6 == result6
        assert expected7 == result7
        assert expected8 == result8
Exemple #15
0
spf = SanicPluginsFramework(app)
rest_assoc = spf.register_plugin(restplus)

api = Api(version='1.0',
          title='TodoMVC API',
          description='A simple TodoMVC API')

ns = api.namespace('todos', description='TODO operations')

todo = api.model(
    'Todo', {
        'id':
        fields.Integer(readOnly=True,
                       description='The task unique identifier'),
        'task':
        fields.String(required=True, description='The task details')
    })


class TodoDAO(object):
    def __init__(self):
        self.counter = 0
        self.todos = []

    def get(self, id):
        for todo in self.todos:
            if todo['id'] == id:
                return todo
        api.abort(404, "Todo {} doesn't exist".format(id))

    def create(self, data):
Exemple #16
0
TODOS = {
    'todo1': {
        'task': 'build an API'
    },
    'todo2': {
        'task': '?????'
    },
    'todo3': {
        'task': 'profit!'
    },
}

todo = api.model(
    'Todo',
    {'task': fields.String(required=True, description='The task details')})

listed_todo = api.model(
    'ListedTodo', {
        'id': fields.String(required=True, description='The todo ID'),
        'todo': fields.Nested(todo, description='The Todo')
    })


def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        api.abort(404, "Todo {} doesn't exist".format(todo_id))


parser = api.parser()
parser.add_argument('task',
Exemple #17
0
 def test_with_empty_enum(self):
     field = fields.String(enum=[])
     assert not field.required
     assert field.__schema__ == {'type': 'string'}
Exemple #18
0
 def test_value(self, value, expected):
     self.assert_field(fields.List(fields.String()), value, expected)
Exemple #19
0
 def test_with_empty_callable_enum(self):
     enum = lambda: []  # noqa
     field = fields.String(enum=enum)
     assert not field.required
     assert field.__schema__ == {'type': 'string'}
Exemple #20
0
from sanic_restplus import Namespace, Resource, fields
from sanic.exceptions import SanicException, InvalidUsage

api = Namespace('cats', description='Cats related operations')

cat = api.model('Cat', {
    'id': fields.String(required=True, description='The cat identifier'),
    'name': fields.String(required=True, description='The cat name'),
})

CATS = [
    {'id': 'felix', 'name': 'Felix'},
]


@api.route('/')
class CatList(Resource):
    @api.doc('list_cats')
    @api.marshal_list_with(cat)
    def get(self, request):
        '''List all cats'''
        return CATS


@api.route('/<id>')
@api.param('id', 'The cat identifier')
@api.response(404, 'Cat not found')
class Cat(Resource):
    @api.doc('get_cat')
    @api.marshal_with(cat)
    def get(self, request, id):
Exemple #21
0
 def test_string_field_with_discriminator_override_require(self):
     field = fields.String(discriminator=True, required=False)
     assert field.discriminator
     assert field.required
     assert field.__schema__ == {'type': 'string'}