Python flask.Flask() Examples

The following are code examples for showing how to use flask.Flask(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 8 votes vote down vote up
def test_dotted_names(self):
        frontend = flask.Blueprint('myapp.frontend', __name__)
        backend = flask.Blueprint('myapp.backend', __name__)

        @frontend.route('/fe')
        def frontend_index():
            return flask.url_for('myapp.backend.backend_index')

        @frontend.route('/fe2')
        def frontend_page2():
            return flask.url_for('.frontend_index')

        @backend.route('/be')
        def backend_index():
            return flask.url_for('myapp.frontend.frontend_index')

        app = flask.Flask(__name__)
        app.register_blueprint(frontend)
        app.register_blueprint(backend)

        c = app.test_client()
        self.assert_equal(c.get('/fe').data.strip(), b'/be')
        self.assert_equal(c.get('/fe2').data.strip(), b'/fe')
        self.assert_equal(c.get('/be').data.strip(), b'/fe') 
Example 2
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: views.py    Apache License 2.0 7 votes vote down vote up
def test_implicit_head(self):
        app = flask.Flask(__name__)

        class Index(flask.views.MethodView):
            def get(self):
                return flask.Response('Blub', headers={
                    'X-Method': flask.request.method
                })

        app.add_url_rule('/', view_func=Index.as_view('index'))
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.data, b'Blub')
        self.assert_equal(rv.headers['X-Method'], 'GET')
        rv = c.head('/')
        self.assert_equal(rv.data, b'')
        self.assert_equal(rv.headers['X-Method'], 'HEAD') 
Example 3
Project: hydrus   Author: HTTP-APIs   File: socketio_factory.py    MIT License 6 votes vote down vote up
def create_socket(app: Flask, session: scoped_session) -> SocketIO:
    socketio.init_app(app, logger=True)
    socketio.on_namespace(SyncNamespace(namespace='/sync', db_session=session))
    return socketio 
Example 4
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: signals.py    Apache License 2.0 6 votes vote down vote up
def test_template_rendered(self):
        app = flask.Flask(__name__)

        @app.route('/')
        def index():
            return flask.render_template('simple_template.html', whiskey=42)

        recorded = []
        def record(sender, template, context):
            recorded.append((template, context))

        flask.template_rendered.connect(record, app)
        try:
            app.test_client().get('/')
            self.assert_equal(len(recorded), 1)
            template, context = recorded[0]
            self.assert_equal(template.name, 'simple_template.html')
            self.assert_equal(context['whiskey'], 42)
        finally:
            flask.template_rendered.disconnect(record, app) 
Example 5
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: signals.py    Apache License 2.0 6 votes vote down vote up
def test_request_exception_signal(self):
        app = flask.Flask(__name__)
        recorded = []

        @app.route('/')
        def index():
            1 // 0

        def record(sender, exception):
            recorded.append(exception)

        flask.got_request_exception.connect(record, app)
        try:
            self.assert_equal(app.test_client().get('/').status_code, 500)
            self.assert_equal(len(recorded), 1)
            self.assert_true(isinstance(recorded[0], ZeroDivisionError))
        finally:
            flask.got_request_exception.disconnect(record, app) 
Example 6
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: signals.py    Apache License 2.0 6 votes vote down vote up
def test_appcontext_signals(self):
        app = flask.Flask(__name__)
        recorded = []
        def record_push(sender, **kwargs):
            recorded.append('push')
        def record_pop(sender, **kwargs):
            recorded.append('push')

        @app.route('/')
        def index():
            return 'Hello'

        flask.appcontext_pushed.connect(record_push, app)
        flask.appcontext_popped.connect(record_pop, app)
        try:
            with app.test_client() as c:
                rv = c.get('/')
                self.assert_equal(rv.data, b'Hello')
                self.assert_equal(recorded, ['push'])
            self.assert_equal(recorded, ['push', 'pop'])
        finally:
            flask.appcontext_pushed.disconnect(record_push, app)
            flask.appcontext_popped.disconnect(record_pop, app) 
Example 7
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: signals.py    Apache License 2.0 6 votes vote down vote up
def test_flash_signal(self):
        app = flask.Flask(__name__)
        app.config['SECRET_KEY'] = 'secret'

        @app.route('/')
        def index():
            flask.flash('This is a flash message', category='notice')
            return flask.redirect('/other')

        recorded = []
        def record(sender, message, category):
            recorded.append((message, category))

        flask.message_flashed.connect(record, app)
        try:
            client = app.test_client()
            with client.session_transaction():
                client.get('/')
                self.assert_equal(len(recorded), 1)
                message, category = recorded[0]
                self.assert_equal(message, 'This is a flash message')
                self.assert_equal(category, 'notice')
        finally:
            flask.message_flashed.disconnect(record, app) 
Example 8
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 6 votes vote down vote up
def test_basic_module(self):
        app = flask.Flask(__name__)
        admin = flask.Module(__name__, 'admin', url_prefix='/admin')
        @admin.route('/')
        def admin_index():
            return 'admin index'
        @admin.route('/login')
        def admin_login():
            return 'admin login'
        @admin.route('/logout')
        def admin_logout():
            return 'admin logout'
        @app.route('/')
        def index():
            return 'the index'
        app.register_module(admin)
        c = app.test_client()
        self.assert_equal(c.get('/').data, b'the index')
        self.assert_equal(c.get('/admin/').data, b'admin index')
        self.assert_equal(c.get('/admin/login').data, b'admin login')
        self.assert_equal(c.get('/admin/logout').data, b'admin logout') 
Example 9
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 6 votes vote down vote up
def test_context_processors(self):
        app = flask.Flask(__name__)
        admin = flask.Module(__name__, 'admin', url_prefix='/admin')
        @app.context_processor
        def inject_all_regular():
            return {'a': 1}
        @admin.context_processor
        def inject_admin():
            return {'b': 2}
        @admin.app_context_processor
        def inject_all_module():
            return {'c': 3}
        @app.route('/')
        def index():
            return flask.render_template_string('{{ a }}{{ b }}{{ c }}')
        @admin.route('/')
        def admin_index():
            return flask.render_template_string('{{ a }}{{ b }}{{ c }}')
        app.register_module(admin)
        c = app.test_client()
        self.assert_equal(c.get('/').data, b'13')
        self.assert_equal(c.get('/admin/').data, b'123') 
Example 10
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 6 votes vote down vote up
def test_endpoint_decorator(self):
        from werkzeug.routing import Submount, Rule
        from flask import Module

        app = flask.Flask(__name__)
        app.testing = True
        app.url_map.add(Submount('/foo', [
            Rule('/bar', endpoint='bar'),
            Rule('/', endpoint='index')
        ]))
        module = Module(__name__, __name__)

        @module.endpoint('bar')
        def bar():
            return 'bar'

        @module.endpoint('index')
        def index():
            return 'index'

        app.register_module(module)

        c = app.test_client()
        self.assert_equal(c.get('/foo/').data, b'index')
        self.assert_equal(c.get('/foo/bar').data, b'bar') 
Example 11
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 6 votes vote down vote up
def test_blueprint_url_definitions(self):
        bp = flask.Blueprint('test', __name__)

        @bp.route('/foo', defaults={'baz': 42})
        def foo(bar, baz):
            return '%s/%d' % (bar, baz)

        @bp.route('/bar')
        def bar(bar):
            return text_type(bar)

        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23})
        app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19})

        c = app.test_client()
        self.assert_equal(c.get('/1/foo').data, b'23/42')
        self.assert_equal(c.get('/2/foo').data, b'19/42')
        self.assert_equal(c.get('/1/bar').data, b'23')
        self.assert_equal(c.get('/2/bar').data, b'19') 
Example 12
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 6 votes vote down vote up
def test_default_static_cache_timeout(self):
        app = flask.Flask(__name__)
        class MyBlueprint(flask.Blueprint):
            def get_send_file_max_age(self, filename):
                return 100

        blueprint = MyBlueprint('blueprint', __name__, static_folder='static')
        app.register_blueprint(blueprint)

        # try/finally, in case other tests use this app for Blueprint tests.
        max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
        try:
            with app.test_request_context():
                unexpected_max_age = 3600
                if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age:
                    unexpected_max_age = 7200
                app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age
                rv = blueprint.send_static_file('index.html')
                cc = parse_cache_control_header(rv.headers['Cache-Control'])
                self.assert_equal(cc.max_age, 100)
                rv.close()
        finally:
            app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default 
Example 13
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 6 votes vote down vote up
def test_dotted_names_from_app(self):
        app = flask.Flask(__name__)
        app.testing = True
        test = flask.Blueprint('test', __name__)

        @app.route('/')
        def app_index():
            return flask.url_for('test.index')

        @test.route('/test/')
        def index():
            return flask.url_for('app_index')

        app.register_blueprint(test)

        with app.test_client() as c:
            rv = c.get('/')
            self.assert_equal(rv.data, b'/test/') 
Example 14
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 6 votes vote down vote up
def test_escaping(self):
        text = '<p>Hello World!'
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            return flask.render_template('escaping_template.html', text=text,
                                         html=flask.Markup(text))
        lines = app.test_client().get('/').data.splitlines()
        self.assert_equal(lines, [
            b'&lt;p&gt;Hello World!',
            b'<p>Hello World!',
            b'<p>Hello World!',
            b'<p>Hello World!',
            b'&lt;p&gt;Hello World!',
            b'<p>Hello World!'
        ]) 
Example 15
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: views.py    Apache License 2.0 6 votes vote down vote up
def test_view_patching(self):
        app = flask.Flask(__name__)

        class Index(flask.views.MethodView):
            def get(self):
                1 // 0
            def post(self):
                1 // 0

        class Other(Index):
            def get(self):
                return 'GET'
            def post(self):
                return 'POST'

        view = Index.as_view('index')
        view.view_class = Other
        app.add_url_rule('/', view_func=view)
        self.common_test(app) 
Example 16
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: views.py    Apache License 2.0 6 votes vote down vote up
def test_view_decorators(self):
        app = flask.Flask(__name__)

        def add_x_parachute(f):
            def new_function(*args, **kwargs):
                resp = flask.make_response(f(*args, **kwargs))
                resp.headers['X-Parachute'] = 'awesome'
                return resp
            return new_function

        class Index(flask.views.View):
            decorators = [add_x_parachute]
            def dispatch_request(self):
                return 'Awesome'

        app.add_url_rule('/', view_func=Index.as_view('index'))
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.headers['X-Parachute'], 'awesome')
        self.assert_equal(rv.data, b'Awesome') 
Example 17
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: views.py    Apache License 2.0 6 votes vote down vote up
def test_explicit_head(self):
        app = flask.Flask(__name__)

        class Index(flask.views.MethodView):
            def get(self):
                return 'GET'
            def head(self):
                return flask.Response('', headers={'X-Method': 'HEAD'})

        app.add_url_rule('/', view_func=Index.as_view('index'))
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.data, b'GET')
        rv = c.head('/')
        self.assert_equal(rv.data, b'')
        self.assert_equal(rv.headers['X-Method'], 'HEAD') 
Example 18
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: views.py    Apache License 2.0 6 votes vote down vote up
def test_endpoint_override(self):
        app = flask.Flask(__name__)
        app.debug = True

        class Index(flask.views.View):
            methods = ['GET', 'POST']
            def dispatch_request(self):
                return flask.request.method

        app.add_url_rule('/', view_func=Index.as_view('index'))

        with self.assert_raises(AssertionError):
            app.add_url_rule('/', view_func=Index.as_view('index'))

        # But these tests should still pass. We just log a warning.
        self.common_test(app) 
Example 19
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 6 votes vote down vote up
def test_send_file_regular(self):
        app = flask.Flask(__name__)
        with app.test_request_context():
            rv = flask.send_file('static/index.html')
            self.assert_true(rv.direct_passthrough)
            self.assert_equal(rv.mimetype, 'text/html')
            with app.open_resource('static/index.html') as f:
                rv.direct_passthrough = False
                self.assert_equal(rv.data, f.read())
            rv.close() 
Example 20
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 6 votes vote down vote up
def test_send_file_xsendfile(self):
        app = flask.Flask(__name__)
        app.use_x_sendfile = True
        with app.test_request_context():
            rv = flask.send_file('static/index.html')
            self.assert_true(rv.direct_passthrough)
            self.assert_in('x-sendfile', rv.headers)
            self.assert_equal(rv.headers['x-sendfile'],
                os.path.join(app.root_path, 'static/index.html'))
            self.assert_equal(rv.mimetype, 'text/html')
            rv.close() 
Example 21
Project: invenio-openaire   Author: inveniosoftware   File: conftest.py    MIT License 5 votes vote down vote up
def app(request):
    """Flask application fixture."""
    # Set temporary instance path for sqlite
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        SQLALCHEMY_DATABASE_URI=os.environ.get(
            'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'),
        INDEXER_REPLACE_REFS=True,
        CELERY_ALWAYS_EAGER=True,
        CELERY_RESULT_BACKEND="cache",
        CELERY_CACHE_BACKEND="memory",
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        JSONSCHEMAS_HOST='inveniosoftware.org',
        OPENAIRE_OAI_LOCAL_SOURCE='invenio_openaire/data/oaire_local.sqlite',
        TESTING=True,
    )

    app.url_map.converters['pid'] = PIDConverter
    app.url_map.converters['pidpath'] = PIDPathConverter

    LoginManager(app)
    InvenioDB(app)
    InvenioIndexer(app)
    InvenioRecords(app)
    InvenioCelery(app)
    InvenioPIDStore(app)
    InvenioOpenAIRE(app)
    InvenioSearch(app)
    InvenioJSONSchemas(app)

    with app.app_context():
        yield app

    shutil.rmtree(instance_path) 
Example 22
Project: invenio-openaire   Author: inveniosoftware   File: test_invenio_openaire.py    MIT License 5 votes vote down vote up
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    ext = InvenioOpenAIRE(app)
    assert 'invenio-openaire' in app.extensions

    app = Flask('testapp')
    ext = InvenioOpenAIRE()
    assert 'invenio-openaire' not in app.extensions
    ext.init_app(app)
    assert 'invenio-openaire' in app.extensions 
Example 23
Project: hydrus   Author: HTTP-APIs   File: app_factory.py    MIT License 5 votes vote down vote up
def app_factory(api_name: str = "api") -> Flask:
    """Create an app object."""

    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret key'
    CORS(app)
    app.url_map.strict_slashes = False
    api = Api(app)

    api.add_resource(Index, "/{}/".format(api_name), endpoint="api")
    api.add_resource(Vocab, "/{}/vocab".format(api_name), endpoint="vocab")
    api.add_resource(
        Contexts,
        "/{}/contexts/<string:category>.jsonld".format(api_name),
        endpoint="contexts")
    api.add_resource(
        Entrypoint,
        "/{}/contexts/EntryPoint.jsonld".format(api_name),
        endpoint="main_entrypoint")
    api.add_resource(
        ItemCollection,
        "/{}/<string:path>".format(api_name),
        endpoint="item_collection")
    api.add_resource(
        Item,
        "/{}/<string:path>/<uuid:id_>".format(api_name),
        endpoint="item")
    api.add_resource(
        Items,
        "/{}/<string:path>/add/<int_list>".format(api_name),
        "/{}/<string:path>/add".format(api_name),
        "/{}/<string:path>/delete/<int_list>".format(api_name))

    return app 
Example 24
Project: flask-ci   Author: vicenteneto   File: app.py    MIT License 5 votes vote down vote up
def create_app():
    flask_sample = Flask('flask_ci_test')

    flask_sample.register_blueprint(users_views.blueprint)

    return flask_sample 
Example 25
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: signals.py    Apache License 2.0 5 votes vote down vote up
def test_request_signals(self):
        app = flask.Flask(__name__)
        calls = []

        def before_request_signal(sender):
            calls.append('before-signal')

        def after_request_signal(sender, response):
            self.assert_equal(response.data, b'stuff')
            calls.append('after-signal')

        @app.before_request
        def before_request_handler():
            calls.append('before-handler')

        @app.after_request
        def after_request_handler(response):
            calls.append('after-handler')
            response.data = 'stuff'
            return response

        @app.route('/')
        def index():
            calls.append('handler')
            return 'ignored anyway'

        flask.request_started.connect(before_request_signal, app)
        flask.request_finished.connect(after_request_signal, app)

        try:
            rv = app.test_client().get('/')
            self.assert_equal(rv.data, b'stuff')

            self.assert_equal(calls, ['before-signal', 'before-handler',
                             'handler', 'after-handler',
                             'after-signal'])
        finally:
            flask.request_started.disconnect(before_request_signal, app)
            flask.request_finished.disconnect(after_request_signal, app) 
Example 26
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_default_endpoint_name(self):
        app = flask.Flask(__name__)
        mod = flask.Module(__name__, 'frontend')
        def index():
            return 'Awesome'
        mod.add_url_rule('/', view_func=index)
        app.register_module(mod)
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, b'Awesome')
        with app.test_request_context():
            self.assert_equal(flask.url_for('frontend.index'), '/') 
Example 27
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_request_processing(self):
        catched = []
        app = flask.Flask(__name__)
        admin = flask.Module(__name__, 'admin', url_prefix='/admin')
        @admin.before_request
        def before_admin_request():
            catched.append('before-admin')
        @admin.after_request
        def after_admin_request(response):
            catched.append('after-admin')
            return response
        @admin.route('/')
        def admin_index():
            return 'the admin'
        @app.before_request
        def before_request():
            catched.append('before-app')
        @app.after_request
        def after_request(response):
            catched.append('after-app')
            return response
        @app.route('/')
        def index():
            return 'the index'
        app.register_module(admin)
        c = app.test_client()

        self.assert_equal(c.get('/').data, b'the index')
        self.assert_equal(catched, ['before-app', 'after-app'])
        del catched[:]

        self.assert_equal(c.get('/admin/').data, b'the admin')
        self.assert_equal(catched, ['before-app', 'before-admin',
                           'after-admin', 'after-app']) 
Example 28
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_late_binding(self):
        app = flask.Flask(__name__)
        admin = flask.Module(__name__, 'admin')
        @admin.route('/')
        def index():
            return '42'
        app.register_module(admin, url_prefix='/admin')
        self.assert_equal(app.test_client().get('/admin/').data, b'42') 
Example 29
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_templates_and_static(self):
        app = moduleapp
        app.testing = True
        c = app.test_client()

        rv = c.get('/')
        self.assert_equal(rv.data, b'Hello from the Frontend')
        rv = c.get('/admin/')
        self.assert_equal(rv.data, b'Hello from the Admin')
        rv = c.get('/admin/index2')
        self.assert_equal(rv.data, b'Hello from the Admin')
        rv = c.get('/admin/static/test.txt')
        self.assert_equal(rv.data.strip(), b'Admin File')
        rv.close()
        rv = c.get('/admin/static/css/test.css')
        self.assert_equal(rv.data.strip(), b'/* nested file */')
        rv.close()

        with app.test_request_context():
            self.assert_equal(flask.url_for('admin.static', filename='test.txt'),
                              '/admin/static/test.txt')

        with app.test_request_context():
            try:
                flask.render_template('missing.html')
            except TemplateNotFound as e:
                self.assert_equal(e.name, 'missing.html')
            else:
                self.assert_true(0, 'expected exception')

        with flask.Flask(__name__).test_request_context():
            self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested') 
Example 30
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_blueprint_specific_error_handling(self):
        frontend = flask.Blueprint('frontend', __name__)
        backend = flask.Blueprint('backend', __name__)
        sideend = flask.Blueprint('sideend', __name__)

        @frontend.errorhandler(403)
        def frontend_forbidden(e):
            return 'frontend says no', 403

        @frontend.route('/frontend-no')
        def frontend_no():
            flask.abort(403)

        @backend.errorhandler(403)
        def backend_forbidden(e):
            return 'backend says no', 403

        @backend.route('/backend-no')
        def backend_no():
            flask.abort(403)

        @sideend.route('/what-is-a-sideend')
        def sideend_no():
            flask.abort(403)

        app = flask.Flask(__name__)
        app.register_blueprint(frontend)
        app.register_blueprint(backend)
        app.register_blueprint(sideend)

        @app.errorhandler(403)
        def app_forbidden(e):
            return 'application itself says no', 403

        c = app.test_client()

        self.assert_equal(c.get('/frontend-no').data, b'frontend says no')
        self.assert_equal(c.get('/backend-no').data, b'backend says no')
        self.assert_equal(c.get('/what-is-a-sideend').data, b'application itself says no') 
Example 31
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_blueprint_url_processors(self):
        bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>')

        @bp.url_defaults
        def add_language_code(endpoint, values):
            values.setdefault('lang_code', flask.g.lang_code)

        @bp.url_value_preprocessor
        def pull_lang_code(endpoint, values):
            flask.g.lang_code = values.pop('lang_code')

        @bp.route('/')
        def index():
            return flask.url_for('.about')

        @bp.route('/about')
        def about():
            return flask.url_for('.index')

        app = flask.Flask(__name__)
        app.register_blueprint(bp)

        c = app.test_client()

        self.assert_equal(c.get('/de/').data, b'/de/about')
        self.assert_equal(c.get('/de/about').data, b'/de/') 
Example 32
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_empty_url_defaults(self):
        bp = flask.Blueprint('bp', __name__)

        @bp.route('/', defaults={'page': 1})
        @bp.route('/page/<int:page>')
        def something(page):
            return str(page)

        app = flask.Flask(__name__)
        app.register_blueprint(bp)

        c = app.test_client()
        self.assert_equal(c.get('/').data, b'1')
        self.assert_equal(c.get('/page/2').data, b'2') 
Example 33
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_route_decorator_custom_endpoint(self):

        bp = flask.Blueprint('bp', __name__)

        @bp.route('/foo')
        def foo():
            return flask.request.endpoint

        @bp.route('/bar', endpoint='bar')
        def foo_bar():
            return flask.request.endpoint

        @bp.route('/bar/123', endpoint='123')
        def foo_bar_foo():
            return flask.request.endpoint

        @bp.route('/bar/foo')
        def bar_foo():
            return flask.request.endpoint

        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')

        @app.route('/')
        def index():
            return flask.request.endpoint

        c = app.test_client()
        self.assertEqual(c.get('/').data, b'index')
        self.assertEqual(c.get('/py/foo').data, b'bp.foo')
        self.assertEqual(c.get('/py/bar').data, b'bp.bar')
        self.assertEqual(c.get('/py/bar/123').data, b'bp.123')
        self.assertEqual(c.get('/py/bar/foo').data, b'bp.bar_foo') 
Example 34
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_template_filter(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_filter()
        def my_reverse(s):
            return s[::-1]
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_in('my_reverse', app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
        self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') 
Example 35
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_filter(self):
        bp = flask.Blueprint('bp', __name__)
        def my_reverse(s):
            return s[::-1]
        bp.add_app_template_filter(my_reverse)
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_in('my_reverse', app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
        self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') 
Example 36
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_template_filter_with_name(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_filter('strrev')
        def my_reverse(s):
            return s[::-1]
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_in('strrev', app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
        self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') 
Example 37
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_filter_with_name(self):
        bp = flask.Blueprint('bp', __name__)
        def my_reverse(s):
            return s[::-1]
        bp.add_app_template_filter(my_reverse, 'strrev')
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_in('strrev', app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
        self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') 
Example 38
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_template_filter_with_template(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_filter()
        def super_reverse(s):
            return s[::-1]
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, b'dcba') 
Example 39
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_filter_with_template(self):
        bp = flask.Blueprint('bp', __name__)
        def super_reverse(s):
            return s[::-1]
        bp.add_app_template_filter(super_reverse)
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, b'dcba') 
Example 40
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_template_filter_with_name_and_template(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_filter('super_reverse')
        def my_reverse(s):
            return s[::-1]
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, b'dcba') 
Example 41
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_filter_with_name_and_template(self):
        bp = flask.Blueprint('bp', __name__)
        def my_reverse(s):
            return s[::-1]
        bp.add_app_template_filter(my_reverse, 'super_reverse')
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, b'dcba') 
Example 42
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_template_test(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_test()
        def is_boolean(value):
            return isinstance(value, bool)
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_in('is_boolean', app.jinja_env.tests.keys())
        self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean)
        self.assert_true(app.jinja_env.tests['is_boolean'](False)) 
Example 43
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_test(self):
        bp = flask.Blueprint('bp', __name__)
        def is_boolean(value):
            return isinstance(value, bool)
        bp.add_app_template_test(is_boolean)
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_in('is_boolean', app.jinja_env.tests.keys())
        self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean)
        self.assert_true(app.jinja_env.tests['is_boolean'](False)) 
Example 44
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_test_with_name(self):
        bp = flask.Blueprint('bp', __name__)
        def is_boolean(value):
            return isinstance(value, bool)
        bp.add_app_template_test(is_boolean, 'boolean')
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        self.assert_in('boolean', app.jinja_env.tests.keys())
        self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)
        self.assert_true(app.jinja_env.tests['boolean'](False)) 
Example 45
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_template_test_with_template(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_test()
        def boolean(value):
            return isinstance(value, bool)
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_test.html', value=False)
        rv = app.test_client().get('/')
        self.assert_in(b'Success!', rv.data) 
Example 46
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_template_test_after_route_with_template(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            return flask.render_template('template_test.html', value=False)
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_test()
        def boolean(value):
            return isinstance(value, bool)
        app.register_blueprint(bp, url_prefix='/py')
        rv = app.test_client().get('/')
        self.assert_in(b'Success!', rv.data) 
Example 47
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_test_with_template(self):
        bp = flask.Blueprint('bp', __name__)
        def boolean(value):
            return isinstance(value, bool)
        bp.add_app_template_test(boolean)
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_test.html', value=False)
        rv = app.test_client().get('/')
        self.assert_in(b'Success!', rv.data) 
Example 48
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def test_template_test_with_name_and_template(self):
        bp = flask.Blueprint('bp', __name__)
        @bp.app_template_test('boolean')
        def is_boolean(value):
            return isinstance(value, bool)
        app = flask.Flask(__name__)
        app.register_blueprint(bp, url_prefix='/py')
        @app.route('/')
        def index():
            return flask.render_template('template_test.html', value=False)
        rv = app.test_client().get('/')
        self.assert_in(b'Success!', rv.data) 
Example 49
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_context_processing(self):
        app = flask.Flask(__name__)
        @app.context_processor
        def context_processor():
            return {'injected_value': 42}
        @app.route('/')
        def index():
            return flask.render_template('context_template.html', value=23)
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, b'<p>23|42') 
Example 50
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_original_win(self):
        app = flask.Flask(__name__)
        @app.route('/')
        def index():
            return flask.render_template_string('{{ config }}', config=42)
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, b'42') 
Example 51
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_request_less_rendering(self):
        app = flask.Flask(__name__)
        app.config['WORLD_NAME'] = 'Special World'
        @app.context_processor
        def context_processor():
            return dict(foo=42)

        with app.app_context():
            rv = flask.render_template_string('Hello {{ config.WORLD_NAME }} '
                                              '{{ foo }}')
            self.assert_equal(rv, 'Hello Special World 42') 
Example 52
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_standard_context(self):
        app = flask.Flask(__name__)
        app.secret_key = 'development key'
        @app.route('/')
        def index():
            flask.g.foo = 23
            flask.session['test'] = 'aha'
            return flask.render_template_string('''
                {{ request.args.foo }}
                {{ g.foo }}
                {{ config.DEBUG }}
                {{ session.test }}
            ''')
        rv = app.test_client().get('/?foo=42')
        self.assert_equal(rv.data.split(), [b'42', b'23', b'False', b'aha']) 
Example 53
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_macros(self):
        app = flask.Flask(__name__)
        with app.test_request_context():
            macro = flask.get_template_attribute('_macro.html', 'hello')
            self.assert_equal(macro('World'), 'Hello World!') 
Example 54
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_template_filter(self):
        app = flask.Flask(__name__)
        @app.template_filter()
        def my_reverse(s):
            return s[::-1]
        self.assert_in('my_reverse', app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
        self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') 
Example 55
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_filter(self):
        app = flask.Flask(__name__)
        def my_reverse(s):
            return s[::-1]
        app.add_template_filter(my_reverse)
        self.assert_in('my_reverse', app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
        self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') 
Example 56
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_template_filter_with_name(self):
        app = flask.Flask(__name__)
        @app.template_filter('strrev')
        def my_reverse(s):
            return s[::-1]
        self.assert_in('strrev', app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
        self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') 
Example 57
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_filter_with_name(self):
        app = flask.Flask(__name__)
        def my_reverse(s):
            return s[::-1]
        app.add_template_filter(my_reverse, 'strrev')
        self.assert_in('strrev', app.jinja_env.filters.keys())
        self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
        self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') 
Example 58
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_filter_with_template(self):
        app = flask.Flask(__name__)
        def super_reverse(s):
            return s[::-1]
        app.add_template_filter(super_reverse)
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, b'dcba') 
Example 59
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_template_filter_with_name_and_template(self):
        app = flask.Flask(__name__)
        @app.template_filter('super_reverse')
        def my_reverse(s):
            return s[::-1]
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, b'dcba') 
Example 60
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_filter_with_name_and_template(self):
        app = flask.Flask(__name__)
        def my_reverse(s):
            return s[::-1]
        app.add_template_filter(my_reverse, 'super_reverse')
        @app.route('/')
        def index():
            return flask.render_template('template_filter.html', value='abcd')
        rv = app.test_client().get('/')
        self.assert_equal(rv.data, b'dcba') 
Example 61
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_template_test(self):
        app = flask.Flask(__name__)
        @app.template_test()
        def boolean(value):
            return isinstance(value, bool)
        self.assert_in('boolean', app.jinja_env.tests.keys())
        self.assert_equal(app.jinja_env.tests['boolean'], boolean)
        self.assert_true(app.jinja_env.tests['boolean'](False)) 
Example 62
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_test(self):
        app = flask.Flask(__name__)
        def boolean(value):
            return isinstance(value, bool)
        app.add_template_test(boolean)
        self.assert_in('boolean', app.jinja_env.tests.keys())
        self.assert_equal(app.jinja_env.tests['boolean'], boolean)
        self.assert_true(app.jinja_env.tests['boolean'](False)) 
Example 63
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_test_with_name(self):
        app = flask.Flask(__name__)
        def is_boolean(value):
            return isinstance(value, bool)
        app.add_template_test(is_boolean, 'boolean')
        self.assert_in('boolean', app.jinja_env.tests.keys())
        self.assert_equal(app.jinja_env.tests['boolean'], is_boolean)
        self.assert_true(app.jinja_env.tests['boolean'](False)) 
Example 64
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_template_test_with_template(self):
        app = flask.Flask(__name__)
        @app.template_test()
        def boolean(value):
            return isinstance(value, bool)
        @app.route('/')
        def index():
            return flask.render_template('template_test.html', value=False)
        rv = app.test_client().get('/')
        self.assert_in(b'Success!', rv.data) 
Example 65
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_test_with_template(self):
        app = flask.Flask(__name__)
        def boolean(value):
            return isinstance(value, bool)
        app.add_template_test(boolean)
        @app.route('/')
        def index():
            return flask.render_template('template_test.html', value=False)
        rv = app.test_client().get('/')
        self.assert_in(b'Success!', rv.data) 
Example 66
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_template_test_with_name_and_template(self):
        app = flask.Flask(__name__)
        @app.template_test('boolean')
        def is_boolean(value):
            return isinstance(value, bool)
        @app.route('/')
        def index():
            return flask.render_template('template_test.html', value=False)
        rv = app.test_client().get('/')
        self.assert_in(b'Success!', rv.data) 
Example 67
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_add_template_test_with_name_and_template(self):
        app = flask.Flask(__name__)
        def is_boolean(value):
            return isinstance(value, bool)
        app.add_template_test(is_boolean, 'boolean')
        @app.route('/')
        def index():
            return flask.render_template('template_test.html', value=False)
        rv = app.test_client().get('/')
        self.assert_in(b'Success!', rv.data) 
Example 68
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_custom_template_loader(self):
        class MyFlask(flask.Flask):
            def create_global_jinja_loader(self):
                from jinja2 import DictLoader
                return DictLoader({'index.html': 'Hello Custom World!'})
        app = MyFlask(__name__)
        @app.route('/')
        def index():
            return flask.render_template('index.html')
        c = app.test_client()
        rv = c.get('/')
        self.assert_equal(rv.data, b'Hello Custom World!') 
Example 69
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: templating.py    Apache License 2.0 5 votes vote down vote up
def test_iterable_loader(self):
        app = flask.Flask(__name__)
        @app.context_processor
        def context_processor():
            return {'whiskey': 'Jameson'}
        @app.route('/')
        def index():
            return flask.render_template(
                ['no_template.xml', # should skip this one
                'simple_template.html', # should render this
                'context_template.html'],
                value=23)

        rv = app.test_client().get('/')
        self.assert_equal(rv.data, b'<h1>Jameson</h1>') 
Example 70
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: views.py    Apache License 2.0 5 votes vote down vote up
def test_basic_view(self):
        app = flask.Flask(__name__)

        class Index(flask.views.View):
            methods = ['GET', 'POST']
            def dispatch_request(self):
                return flask.request.method

        app.add_url_rule('/', view_func=Index.as_view('index'))
        self.common_test(app) 
Example 71
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: views.py    Apache License 2.0 5 votes vote down vote up
def test_method_based_view(self):
        app = flask.Flask(__name__)

        class Index(flask.views.MethodView):
            def get(self):
                return 'GET'
            def post(self):
                return 'POST'

        app.add_url_rule('/', view_func=Index.as_view('index'))

        self.common_test(app) 
Example 72
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 5 votes vote down vote up
def test_json_bad_requests(self):
        app = flask.Flask(__name__)
        @app.route('/json', methods=['POST'])
        def return_json():
            return flask.jsonify(foo=text_type(flask.request.get_json()))
        c = app.test_client()
        rv = c.post('/json', data='malformed', content_type='application/json')
        self.assert_equal(rv.status_code, 400) 
Example 73
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 5 votes vote down vote up
def test_jsonify(self):
        d = dict(a=23, b=42, c=[1, 2, 3])
        app = flask.Flask(__name__)
        @app.route('/kw')
        def return_kwargs():
            return flask.jsonify(**d)
        @app.route('/dict')
        def return_dict():
            return flask.jsonify(d)
        c = app.test_client()
        for url in '/kw', '/dict':
            rv = c.get(url)
            self.assert_equal(rv.mimetype, 'application/json')
            self.assert_equal(flask.json.loads(rv.data), d) 
Example 74
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 5 votes vote down vote up
def test_json_as_unicode(self):
        app = flask.Flask(__name__)

        app.config['JSON_AS_ASCII'] = True
        with app.app_context():
            rv = flask.json.dumps(u'\N{SNOWMAN}')
            self.assert_equal(rv, '"\\u2603"')

        app.config['JSON_AS_ASCII'] = False
        with app.app_context():
            rv = flask.json.dumps(u'\N{SNOWMAN}')
            self.assert_equal(rv, u'"\u2603"') 
Example 75
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 5 votes vote down vote up
def test_json_attr(self):
        app = flask.Flask(__name__)
        @app.route('/add', methods=['POST'])
        def add():
            json = flask.request.get_json()
            return text_type(json['a'] + json['b'])
        c = app.test_client()
        rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),
                            content_type='application/json')
        self.assert_equal(rv.data, b'3') 
Example 76
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 5 votes vote down vote up
def test_template_escaping(self):
        app = flask.Flask(__name__)
        render = flask.render_template_string
        with app.test_request_context():
            rv = flask.json.htmlsafe_dumps('</script>')
            self.assert_equal(rv, u'"\\u003c/script\\u003e"')
            self.assert_equal(type(rv), text_type)
            rv = render('{{ "</script>"|tojson }}')
            self.assert_equal(rv, '"\\u003c/script\\u003e"')
            rv = render('{{ "<\0/script>"|tojson }}')
            self.assert_equal(rv, '"\\u003c\\u0000/script\\u003e"')
            rv = render('{{ "<!--<script>"|tojson }}')
            self.assert_equal(rv, '"\\u003c!--\\u003cscript\\u003e"')
            rv = render('{{ "&"|tojson }}')
            self.assert_equal(rv, '"\\u0026"') 
Example 77
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 5 votes vote down vote up
def test_json_customization(self):
        class X(object):
            def __init__(self, val):
                self.val = val
        class MyEncoder(flask.json.JSONEncoder):
            def default(self, o):
                if isinstance(o, X):
                    return '<%d>' % o.val
                return flask.json.JSONEncoder.default(self, o)
        class MyDecoder(flask.json.JSONDecoder):
            def __init__(self, *args, **kwargs):
                kwargs.setdefault('object_hook', self.object_hook)
                flask.json.JSONDecoder.__init__(self, *args, **kwargs)
            def object_hook(self, obj):
                if len(obj) == 1 and '_foo' in obj:
                    return X(obj['_foo'])
                return obj
        app = flask.Flask(__name__)
        app.testing = True
        app.json_encoder = MyEncoder
        app.json_decoder = MyDecoder
        @app.route('/', methods=['POST'])
        def index():
            return flask.json.dumps(flask.request.get_json()['x'])
        c = app.test_client()
        rv = c.post('/', data=flask.json.dumps({
            'x': {'_foo': 42}
        }), content_type='application/json')
        self.assertEqual(rv.data, b'"<42>"') 
Example 78
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 5 votes vote down vote up
def test_json_key_sorting(self):
        app = flask.Flask(__name__)
        app.testing = True
        self.assert_equal(app.config['JSON_SORT_KEYS'], True)
        d = dict.fromkeys(range(20), 'foo')

        @app.route('/')
        def index():
            return flask.jsonify(values=d)

        c = app.test_client()
        rv = c.get('/')
        lines = [x.strip() for x in rv.data.strip().decode('utf-8').splitlines()]
        self.assert_equal(lines, [
            '{',
            '"values": {',
            '"0": "foo",',
            '"1": "foo",',
            '"2": "foo",',
            '"3": "foo",',
            '"4": "foo",',
            '"5": "foo",',
            '"6": "foo",',
            '"7": "foo",',
            '"8": "foo",',
            '"9": "foo",',
            '"10": "foo",',
            '"11": "foo",',
            '"12": "foo",',
            '"13": "foo",',
            '"14": "foo",',
            '"15": "foo",',
            '"16": "foo",',
            '"17": "foo",',
            '"18": "foo",',
            '"19": "foo"',
            '}',
            '}'
        ]) 
Example 79
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 5 votes vote down vote up
def test_attachment(self):
        app = flask.Flask(__name__)
        with catch_warnings() as captured:
            with app.test_request_context():
                f = open(os.path.join(app.root_path, 'static/index.html'))
                rv = flask.send_file(f, as_attachment=True)
                value, options = parse_options_header(rv.headers['Content-Disposition'])
                self.assert_equal(value, 'attachment')
                rv.close()
            # mimetypes + etag
            self.assert_equal(len(captured), 2)

        with app.test_request_context():
            self.assert_equal(options['filename'], 'index.html')
            rv = flask.send_file('static/index.html', as_attachment=True)
            value, options = parse_options_header(rv.headers['Content-Disposition'])
            self.assert_equal(value, 'attachment')
            self.assert_equal(options['filename'], 'index.html')
            rv.close()

        with app.test_request_context():
            rv = flask.send_file(StringIO('Test'), as_attachment=True,
                                 attachment_filename='index.txt',
                                 add_etags=False)
            self.assert_equal(rv.mimetype, 'text/plain')
            value, options = parse_options_header(rv.headers['Content-Disposition'])
            self.assert_equal(value, 'attachment')
            self.assert_equal(options['filename'], 'index.txt')
            rv.close() 
Example 80
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 4 votes vote down vote up
def test_send_file_object(self):
        app = flask.Flask(__name__)
        with catch_warnings() as captured:
            with app.test_request_context():
                f = open(os.path.join(app.root_path, 'static/index.html'))
                rv = flask.send_file(f)
                rv.direct_passthrough = False
                with app.open_resource('static/index.html') as f:
                    self.assert_equal(rv.data, f.read())
                self.assert_equal(rv.mimetype, 'text/html')
                rv.close()
            # mimetypes + etag
            self.assert_equal(len(captured), 2)

        app.use_x_sendfile = True
        with catch_warnings() as captured:
            with app.test_request_context():
                f = open(os.path.join(app.root_path, 'static/index.html'))
                rv = flask.send_file(f)
                self.assert_equal(rv.mimetype, 'text/html')
                self.assert_in('x-sendfile', rv.headers)
                self.assert_equal(rv.headers['x-sendfile'],
                    os.path.join(app.root_path, 'static/index.html'))
                rv.close()
            # mimetypes + etag
            self.assert_equal(len(captured), 2)

        app.use_x_sendfile = False
        with app.test_request_context():
            with catch_warnings() as captured:
                f = StringIO('Test')
                rv = flask.send_file(f)
                rv.direct_passthrough = False
                self.assert_equal(rv.data, b'Test')
                self.assert_equal(rv.mimetype, 'application/octet-stream')
                rv.close()
            # etags
            self.assert_equal(len(captured), 1)
            with catch_warnings() as captured:
                f = StringIO('Test')
                rv = flask.send_file(f, mimetype='text/plain')
                rv.direct_passthrough = False
                self.assert_equal(rv.data, b'Test')
                self.assert_equal(rv.mimetype, 'text/plain')
                rv.close()
            # etags
            self.assert_equal(len(captured), 1)

        app.use_x_sendfile = True
        with catch_warnings() as captured:
            with app.test_request_context():
                f = StringIO('Test')
                rv = flask.send_file(f)
                self.assert_not_in('x-sendfile', rv.headers)
                rv.close()
            # etags
            self.assert_equal(len(captured), 1)