from flask import Flask, request
from flask.views import MethodView
from flask.ext.introspect import blueprint as rest, TreeView, ObjectViewMixin, DictViewMixin
from unittest import TestCase

class Config():
    SERVER_NAME = 'localhost'
    DEBUG = True
    TESTING = True

class O(object):
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

class OView(ObjectViewMixin, TreeView):
    __type__ = O
    '''
    view class methods will always recieve suitable item
    and can incapsulate web related functionality (including permissions)
    '''
    class view(MethodView):
        def get(self, item):
            return item.obj.a

class DictView(DictViewMixin, OView):
    class view(MethodView):
        def get(self, item):
            return item.obj['c']

        def post(self, item):
            return request.values['a'] + request.values['b']

class TestRESTBlueprint(TestCase):
    def setUp(self):
        app = Flask(__name__)
        app.config.from_object(Config)
        self.app = app.test_client()

    def test_get(self):
        '''
        another way to limit access is to arrange setup_tree function that
        will determine tree parameters (roots and leafs) according to user permissions
        '''

        api = rest('api', __name__, {'o': O(a='a name', b={'c':'d'})}, roots=OView)
        self.app.application.register_blueprint(api, url_prefix='/api')
        self.assertTrue('\n'.join(self.app.get('/api/o').response) == 'a name')
        self.assertTrue('\n'.join(self.app.get('/api/o/b').response) == 'd')

    def test_post(self):
        api = rest('api', __name__, {'o': O(a='a name', b={'c':'d'})}, roots=OView)
        self.app.application.register_blueprint(api, url_prefix='/api')
        self.assertTrue('\n'.join(self.app.post('/api/o/b', data={'a':1, 'b':2}).response) == '12')


if __name__ == '__main__':
    from unittest import main
    main()