Example #1
0
    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, "index")
        self.assertEqual(c.get("/py/foo").data, "bp.foo")
        self.assertEqual(c.get("/py/bar").data, "bp.bar")
        self.assertEqual(c.get("/py/bar/123").data, "bp.123")
        self.assertEqual(c.get("/py/bar/foo").data, "bp.bar_foo")
Example #2
0
def test_route_decorator_custom_endpoint():

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

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

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

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

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

    app = keyes.Keyes(__name__)
    app.register_blueprint(bp, url_prefix='/py')

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

    c = app.test_client()
    assert c.get('/').data == b'index'
    assert c.get('/py/foo').data == b'bp.foo'
    assert c.get('/py/bar').data == b'bp.bar'
    assert c.get('/py/bar/123').data == b'bp.123'
    assert c.get('/py/bar/foo').data == b'bp.bar_foo'
Example #3
0
def test_template_loader_debugging(test_apps):
    from blueprintapp import app

    called = []

    class _TestHandler(logging.Handler):
        def handle(x, record):
            called.append(True)
            text = str(record.msg)
            assert '1: trying loader of application "blueprintapp"' in text
            assert ('2: trying loader of blueprint "admin" '
                    '(blueprintapp.apps.admin)') in text
            assert ('trying loader of blueprint "frontend" '
                    '(blueprintapp.apps.frontend)') in text
            assert 'Error: the template could not be found' in text
            assert ('looked up from an endpoint that belongs to '
                    'the blueprint "frontend"') in text
            assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text

    with app.test_client() as c:
        try:
            old_load_setting = app.config['EXPLAIN_TEMPLATE_LOADING']
            old_handlers = app.logger.handlers[:]
            app.logger.handlers = [_TestHandler()]
            app.config['EXPLAIN_TEMPLATE_LOADING'] = True

            with pytest.raises(TemplateNotFound) as excinfo:
                c.get('/missing')

            assert 'missing_template.html' in str(excinfo.value)
        finally:
            app.logger.handlers[:] = old_handlers
            app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting

    assert len(called) == 1
Example #4
0
def test_template_loader_debugging(test_apps, monkeypatch):
    from blueprintapp import app

    called = []

    class _TestHandler(logging.Handler):
        def handle(x, record):
            called.append(True)
            text = str(record.msg)
            assert '1: trying loader of application "blueprintapp"' in text
            assert ('2: trying loader of blueprint "admin" '
                    '(blueprintapp.apps.admin)') in text
            assert ('trying loader of blueprint "frontend" '
                    '(blueprintapp.apps.frontend)') in text
            assert 'Error: the template could not be found' in text
            assert ('looked up from an endpoint that belongs to '
                    'the blueprint "frontend"') in text
            assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text

    with app.test_client() as c:
        monkeypatch.setitem(app.config, 'EXPLAIN_TEMPLATE_LOADING', True)
        monkeypatch.setattr(
            logging.getLogger('flask'), 'handlers', [_TestHandler()]
        )

        with pytest.raises(TemplateNotFound) as excinfo:
            c.get('/missing')

        assert 'missing_template.html' in str(excinfo.value)

    assert len(called) == 1
Example #5
0
    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 #6
0
    def test_templates_and_static(self):
        from blueprintapp import app
        c = app.test_client()

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

        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, e:
                self.assert_equal(e.name, 'missing.html')
            else:
Example #7
0
 def test_add_template_test_with_name_and_template(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')
     @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 #8
0
def test_add_template_filter_with_name_and_template():
    bp = keyes.Blueprint('bp', __name__)
    def my_reverse(s):
        return s[::-1]
    bp.add_app_template_filter(my_reverse, 'super_reverse')
    app = keyes.Keyes(__name__)
    app.register_blueprint(bp, url_prefix='/py')
    @app.route('/')
    def index():
        return keyes.render_template('template_filter.html', value='abcd')
    rv = app.test_client().get('/')
    assert rv.data == b'dcba'
Example #9
0
def test_add_template_test_with_name_and_template():
    bp = keyes.Blueprint('bp', __name__)
    def is_boolean(value):
        return isinstance(value, bool)
    bp.add_app_template_test(is_boolean, 'boolean')
    app = keyes.Keyes(__name__)
    app.register_blueprint(bp, url_prefix='/py')
    @app.route('/')
    def index():
        return keyes.render_template('template_test.html', value=False)
    rv = app.test_client().get('/')
    assert b'Success!' in rv.data
Example #10
0
def test_template_filter_after_route_with_template():
    app = flask.Flask(__name__)
    @app.route('/')
    def index():
        return flask.render_template('template_filter.html', value='abcd')
    bp = flask.Blueprint('bp', __name__)
    @bp.app_template_filter()
    def super_reverse(s):
        return s[::-1]
    app.register_blueprint(bp, url_prefix='/py')
    rv = app.test_client().get('/')
    assert rv.data == b'dcba'
Example #11
0
def test_template_test_after_route_with_template():
    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('/')
    assert b'Success!' in rv.data
Example #12
0
 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 #13
0
    def test_route_decorator_custom_endpoint_with_dots(self):
        bp = flask.Blueprint('bp', __name__)

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

        try:
            @bp.route('/bar', endpoint='bar.bar')
            def foo_bar():
                return flask.request.endpoint
        except AssertionError:
            pass
        else:
            raise AssertionError('expected AssertionError not raised')

        try:
            @bp.route('/bar/123', endpoint='bar.123')
            def foo_bar_foo():
                return flask.request.endpoint
        except AssertionError:
            pass
        else:
            raise AssertionError('expected AssertionError not raised')

        def foo_foo_foo():
            pass

        self.assertRaises(
            AssertionError,
            lambda: bp.add_url_rule(
                '/bar/123', endpoint='bar.123', view_func=foo_foo_foo
            )
        )

        self.assertRaises(
            AssertionError,
            bp.route('/bar/123', endpoint='bar.123'),
            lambda: None
        )

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

        c = app.test_client()
        self.assertEqual(c.get('/py/foo').data, b'bp.foo')
        # The rule's didn't actually made it through
        rv = c.get('/py/bar')
        assert rv.status_code == 404
        rv = c.get('/py/bar/123')
        assert rv.status_code == 404
Example #14
0
    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, "1")
        self.assert_equal(c.get("/page/2").data, "2")
Example #15
0
def test_empty_url_defaults():
    bp = keyes.Blueprint('bp', __name__)

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

    app = keyes.Keyes(__name__)
    app.register_blueprint(bp)

    c = app.test_client()
    assert c.get('/').data == b'1'
    assert c.get('/page/2').data == b'2'
Example #16
0
    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 #17
0
def test_template_filter_after_route_with_template():
    app = flask.Flask(__name__)

    @app.route('/')
    def index():
        return flask.render_template('template_filter.html', value='abcd')

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

    @bp.app_template_filter()
    def super_reverse(s):
        return s[::-1]

    app.register_blueprint(bp, url_prefix='/py')
    rv = app.test_client().get('/')
    assert rv.data == b'dcba'
Example #18
0
def test_add_template_test_with_name_and_template():
    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')

    @app.route('/')
    def index():
        return flask.render_template('template_test.html', value=False)

    rv = app.test_client().get('/')
    assert b'Success!' in rv.data
Example #19
0
    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 #20
0
    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 #21
0
def test_endpoint_decorator():
    from werkzeug.routing import Rule
    app = flask.Flask(__name__)
    app.url_map.add(Rule('/foo', endpoint='bar'))

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

    @bp.endpoint('bar')
    def foobar():
        return flask.request.endpoint

    app.register_blueprint(bp, url_prefix='/bp_prefix')

    c = app.test_client()
    assert c.get('/foo').data == b'bar'
    assert c.get('/bp_prefix/bar').status_code == 404
Example #22
0
    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, "dcba")
Example #23
0
    def test_templates_and_static(self):
        from blueprintapp import app
        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()

        # try/finally, in case other tests use this app for Blueprint tests.
        max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
        try:
            expected_max_age = 3600
            if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:
                expected_max_age = 7200
            app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age
            rv = c.get('/admin/static/css/test.css')
            cc = parse_cache_control_header(rv.headers['Cache-Control'])
            self.assert_equal(cc.max_age, expected_max_age)
            rv.close()
        finally:
            app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default

        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 #24
0
def test_route_decorator_custom_endpoint_with_dots():
    bp = keyes.Blueprint('bp', __name__)

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

    try:

        @bp.route('/bar', endpoint='bar.bar')
        def foo_bar():
            return keyes.request.endpoint
    except AssertionError:
        pass
    else:
        raise AssertionError('expected AssertionError not raised')

    try:

        @bp.route('/bar/123', endpoint='bar.123')
        def foo_bar_foo():
            return keyes.request.endpoint
    except AssertionError:
        pass
    else:
        raise AssertionError('expected AssertionError not raised')

    def foo_foo_foo():
        pass

    pytest.raises(
        AssertionError, lambda: bp.add_url_rule(
            '/bar/123', endpoint='bar.123', view_func=foo_foo_foo))

    pytest.raises(AssertionError, bp.route('/bar/123', endpoint='bar.123'),
                  lambda: None)

    app = keyes.Keyes(__name__)
    app.register_blueprint(bp, url_prefix='/py')

    c = app.test_client()
    assert c.get('/py/foo').data == b'bp.foo'
    # The rule's didn't actually made it through
    rv = c.get('/py/bar')
    assert rv.status_code == 404
    rv = c.get('/py/bar/123')
    assert rv.status_code == 404
Example #25
0
    def test_templates_and_static(self):
        from blueprintapp import app

        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()

        # try/finally, in case other tests use this app for Blueprint tests.
        max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
        try:
            expected_max_age = 3600
            if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:
                expected_max_age = 7200
            app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age
            rv = c.get('/admin/static/css/test.css')
            cc = parse_cache_control_header(rv.headers['Cache-Control'])
            self.assert_equal(cc.max_age, expected_max_age)
            rv.close()
        finally:
            app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default

        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 #26
0
def test_templates_and_static(test_apps):
    from blueprintapp import app

    client = app.test_client()

    rv = client.get("/")
    assert rv.data == b"Hello from the Frontend"
    rv = client.get("/admin/")
    assert rv.data == b"Hello from the Admin"
    rv = client.get("/admin/index2")
    assert rv.data == b"Hello from the Admin"
    rv = client.get("/admin/static/test.txt")
    assert rv.data.strip() == b"Admin File"
    rv.close()
    rv = client.get("/admin/static/css/test.css")
    assert rv.data.strip() == b"/* nested file */"
    rv.close()

    # try/finally, in case other tests use this app for Blueprint tests.
    max_age_default = app.config["SEND_FILE_MAX_AGE_DEFAULT"]
    try:
        expected_max_age = 3600
        if app.config["SEND_FILE_MAX_AGE_DEFAULT"] == expected_max_age:
            expected_max_age = 7200
        app.config["SEND_FILE_MAX_AGE_DEFAULT"] = expected_max_age
        rv = client.get("/admin/static/css/test.css")
        cc = parse_cache_control_header(rv.headers["Cache-Control"])
        assert cc.max_age == expected_max_age
        rv.close()
    finally:
        app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default

    with app.test_request_context():
        assert (
            flask.url_for("admin.static", filename="test.txt")
            == "/admin/static/test.txt"
        )

    with app.test_request_context():
        with pytest.raises(TemplateNotFound) as e:
            flask.render_template("missing.html")
        assert e.value.name == "missing.html"

    with flask.Flask(__name__).test_request_context():
        assert flask.render_template("nested/nested.txt") == "I'm nested"
Example #27
0
def test_templates_and_static(test_apps):
    from blueprintapp import app

    client = app.test_client()

    rv = client.get("/")
    assert rv.data == b"Hello from the Frontend"
    rv = client.get("/admin/")
    assert rv.data == b"Hello from the Admin"
    rv = client.get("/admin/index2")
    assert rv.data == b"Hello from the Admin"
    rv = client.get("/admin/static/test.txt")
    assert rv.data.strip() == b"Admin File"
    rv.close()
    rv = client.get("/admin/static/css/test.css")
    assert rv.data.strip() == b"/* nested file */"
    rv.close()

    # try/finally, in case other tests use this app for Blueprint tests.
    max_age_default = app.config["SEND_FILE_MAX_AGE_DEFAULT"]
    try:
        expected_max_age = 3600
        if app.config["SEND_FILE_MAX_AGE_DEFAULT"] == expected_max_age:
            expected_max_age = 7200
        app.config["SEND_FILE_MAX_AGE_DEFAULT"] = expected_max_age
        rv = client.get("/admin/static/css/test.css")
        cc = parse_cache_control_header(rv.headers["Cache-Control"])
        assert cc.max_age == expected_max_age
        rv.close()
    finally:
        app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default

    with app.test_request_context():
        assert (
            flask.url_for("admin.static", filename="test.txt")
            == "/admin/static/test.txt"
        )

    with app.test_request_context():
        with pytest.raises(TemplateNotFound) as e:
            flask.render_template("missing.html")
        assert e.value.name == "missing.html"

    with flask.Flask(__name__).test_request_context():
        assert flask.render_template("nested/nested.txt") == "I'm nested"
Example #28
0
    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 #29
0
def test_dotted_names_from_app():
    app = keyes.Keyes(__name__)
    app.testing = True
    test = keyes.Blueprint('test', __name__)

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

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

    app.register_blueprint(test)

    with app.test_client() as c:
        rv = c.get('/')
        assert rv.data == b'/test/'
Example #30
0
    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 #31
0
def test_dotted_names_from_app():
    app = keyes.Keyes(__name__)
    app.testing = True
    test = keyes.Blueprint('test', __name__)

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

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

    app.register_blueprint(test)

    with app.test_client() as c:
        rv = c.get('/')
        assert rv.data == b'/test/'
Example #32
0
def test_templates_and_static(test_apps):
    from blueprintapp import app
    c = app.test_client()

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

    # try/finally, in case other tests use this app for Blueprint tests.
    max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
    try:
        expected_max_age = 3600
        if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:
            expected_max_age = 7200
        app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age
        rv = c.get('/admin/static/css/test.css')
        cc = parse_cache_control_header(rv.headers['Cache-Control'])
        assert cc.max_age == expected_max_age
        rv.close()
    finally:
        app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default

    with app.test_request_context():
        assert keyes.url_for('admin.static',
                             filename='test.txt') == '/admin/static/test.txt'

    with app.test_request_context():
        with pytest.raises(TemplateNotFound) as e:
            keyes.render_template('missing.html')
        assert e.value.name == 'missing.html'

    with keyes.Keyes(__name__).test_request_context():
        assert keyes.render_template('nested/nested.txt') == 'I\'m nested'
Example #33
0
def test_context_processing():
    app = flask.Flask(__name__)
    answer_bp = flask.Blueprint('answer_bp', __name__)

    template_string = lambda: flask.render_template_string(
        '{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}'
        '{% if answer %}{{ answer }} is the answer.{% endif %}'
    )

    # App global context processor
    @answer_bp.app_context_processor
    def not_answer_context_processor():
        return {'notanswer': 43}

    # Blueprint local context processor
    @answer_bp.context_processor
    def answer_context_processor():
        return {'answer': 42}

    # Setup endpoints for testing
    @answer_bp.route('/bp')
    def bp_page():
        return template_string()

    @app.route('/')
    def app_page():
        return template_string()

    # Register the blueprint
    app.register_blueprint(answer_bp)

    c = app.test_client()

    app_page_bytes = c.get('/').data
    answer_page_bytes = c.get('/bp').data

    assert b'43' in app_page_bytes
    assert b'42' not in app_page_bytes

    assert b'42' in answer_page_bytes
    assert b'43' in answer_page_bytes
Example #34
0
def test_templates_and_static(test_apps):
    from blueprintapp import app
    c = app.test_client()

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

    # try/finally, in case other tests use this app for Blueprint tests.
    max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT']
    try:
        expected_max_age = 3600
        if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age:
            expected_max_age = 7200
        app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age
        rv = c.get('/admin/static/css/test.css')
        cc = parse_cache_control_header(rv.headers['Cache-Control'])
        assert cc.max_age == expected_max_age
        rv.close()
    finally:
        app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default

    with app.test_request_context():
        assert keyes.url_for('admin.static', filename='test.txt') == '/admin/static/test.txt'

    with app.test_request_context():
        with pytest.raises(TemplateNotFound) as e:
            keyes.render_template('missing.html')
        assert e.value.name == 'missing.html'

    with keyes.Keyes(__name__).test_request_context():
        assert keyes.render_template('nested/nested.txt') == 'I\'m nested'
Example #35
0
    def test_templates_and_static(self):
        from blueprintapp import app

        c = app.test_client()

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

        # try/finally, in case other tests use this app for Blueprint tests.
        max_age_default = app.config["SEND_FILE_MAX_AGE_DEFAULT"]
        try:
            expected_max_age = 3600
            if app.config["SEND_FILE_MAX_AGE_DEFAULT"] == expected_max_age:
                expected_max_age = 7200
            app.config["SEND_FILE_MAX_AGE_DEFAULT"] = expected_max_age
            rv = c.get("/admin/static/css/test.css")
            cc = parse_cache_control_header(rv.headers["Cache-Control"])
            self.assert_equal(cc.max_age, expected_max_age)
        finally:
            app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default

        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, e:
                self.assert_equal(e.name, "missing.html")
            else:
Example #36
0
    def test_template_loader_debugging(self):
        from blueprintapp import app

        called = []
        class _TestHandler(logging.Handler):
            def handle(x, record):
                called.append(True)
                text = str(record.msg)
                self.assert_('1: trying loader of application '
                             '"blueprintapp"' in text)
                self.assert_('2: trying loader of blueprint "admin" '
                             '(blueprintapp.apps.admin)' in text)
                self.assert_('trying loader of blueprint "frontend" '
                             '(blueprintapp.apps.frontend)' in text)
                self.assert_('Error: the template could not be found' in text)
                self.assert_('looked up from an endpoint that belongs to '
                             'the blueprint "frontend"' in text)
                self.assert_(
                    'See http://flask.pocoo.org/docs/blueprints/#templates' in text)

        with app.test_client() as c:
            try:
                old_load_setting = app.config['EXPLAIN_TEMPLATE_LOADING']
                old_handlers = app.logger.handlers[:]
                app.logger.handlers = [_TestHandler()]
                app.config['EXPLAIN_TEMPLATE_LOADING'] = True

                try:
                    c.get('/missing')
                except TemplateNotFound as e:
                    self.assert_('missing_template.html' in str(e))
                else:
                    self.fail('Expected template not found exception.')
            finally:
                app.logger.handlers[:] = old_handlers
                app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting

        self.assert_equal(len(called), 1)
Example #37
0
    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 #38
0
    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(), "/be")
        self.assert_equal(c.get("/fe2").data.strip(), "/fe")
        self.assert_equal(c.get("/be").data.strip(), "/fe")
Example #39
0
def test_dotted_names():
    frontend = keyes.Blueprint('myapp.frontend', __name__)
    backend = keyes.Blueprint('myapp.backend', __name__)

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

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

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

    app = keyes.Keyes(__name__)
    app.register_blueprint(frontend)
    app.register_blueprint(backend)

    c = app.test_client()
    assert c.get('/fe').data.strip() == b'/be'
    assert c.get('/fe2').data.strip() == b'/fe'
    assert c.get('/be').data.strip() == b'/fe'
Example #40
0
def test_dotted_names():
    frontend = keyes.Blueprint('myapp.frontend', __name__)
    backend = keyes.Blueprint('myapp.backend', __name__)

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

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

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

    app = keyes.Keyes(__name__)
    app.register_blueprint(frontend)
    app.register_blueprint(backend)

    c = app.test_client()
    assert c.get('/fe').data.strip() == b'/be'
    assert c.get('/fe2').data.strip() == b'/fe'
    assert c.get('/be').data.strip() == b'/fe'
Example #41
0
    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')