def test(config):
        """Test the given Flask configuration. If configured correctly,
        an error will be tracked by Exceptional for your app. Unlike
        the initialized extension, this test will post data to Exceptional,
        regardless of the configured ``DEBUG`` setting.

        :param config: The Flask application configuration object to test.
                       Accepts either :class:`flask.Config` or the object
                       types allowed by :meth:`flask.Config.from_object`.
        """
        context = getattr(stack.top, "exceptional_context", None)
        app = Flask(__name__)
        exceptional = Exceptional()

        if isinstance(config, Config):
            app.config = config
        else:
            app.config.from_object(config)

        assert "EXCEPTIONAL_API_KEY" in app.config
        app.debug = False
        app.testing = False
        exceptional.init_app(app)
        app.testing = True

        @app.route("/exception")
        def exception():
            setattr(stack.top, "exceptional_context", context)
            message = "Congratulations! Your application is configured for Exceptional error tracking."  # NOQA

            raise Exception(message)

        with app.test_client() as client:
            client.get("/exception")
            json.loads(g.exceptional)
Beispiel #2
0
def test_menu_render():
    menu = decorators.menu
    menu.clear()
    app = Flask(__name__)
    app.testing = True

    @menu("Hello World", group_name="admin")
    class Hello(object):

        @menu("Index")
        def index(self):
            pass

        @menu("Page 2")
        def index2(self):
            pass

    @menu("Monster")
    class Monster(object):

        @menu("Home")
        def maggi(self):
            pass

    with app.test_client() as c:
        c.get("/")
        assert len(menu.render()) == 2
Beispiel #3
0
 def create_app(self):
     app = Flask(__name__)
     app.config.update({"OAUTH1_PROVIDER_ENFORCE_SSL": False})
     app.debug = True
     app.testing = True
     app.secret_key = "development"
     return app
Beispiel #4
0
def app_error_handler(request):
    """Flask app error handler fixture."""
    app = Flask('myapp')

    # Creation of a fake theme error template file.
    temp_dir = tempfile.mkdtemp()
    invenio_theme_dir = os.path.join(temp_dir, 'invenio_theme')
    os.mkdir(invenio_theme_dir)
    fake_file = open(os.path.join(invenio_theme_dir, 'fake.html'), 'w+')
    fake_file.write("{# -*- coding: utf-8 -*- -#}"
                    "<!DOCTYPE html>{% block message %}"
                    "{% endblock message %}")
    fake_file.close()

    # Adding the temporal path to jinja engine.
    app.jinja_loader = jinja2.ChoiceLoader([
        jinja2.FileSystemLoader(temp_dir),
        app.jinja_loader
    ])

    # Setting by default fake.html as a THEME_ERROR_TEMPLATE
    app.config['THEME_ERROR_TEMPLATE'] = 'invenio_theme/fake.html'

    # Tear down method to clean the temp directory.
    def tear_down():
        shutil.rmtree(temp_dir)
    request.addfinalizer(tear_down)

    app.testing = True
    Babel(app)
    InvenioI18N(app)
    InvenioTheme(app)
    return app
Beispiel #5
0
def setup_app(debug=False, testing=False, production=False, config='dev', gae=False, **kwargs):
    from flask import Flask

    # Passing __name__ for reference point on where your code and resources are
    # This will influence a default template location
    # http://flask.pocoo.org/docs/api/#flask.Flask

    app = Flask(__name__, **kwargs)
    app.debug = debug
    # WARNING: setting True will disable login_manager decorators
    app.testing = testing

    import website.settings
    app.config.from_object(website.settings)

    import importlib
    logging.debug("Additional settings: %s" % "website.settings_"+config)
    cfg = importlib.import_module("website.settings_"+config)
    logging.debug("Loaded website.settings_%s" % config)
    app.config.from_object(cfg)

    # Enable jinja2 extensions
    app.jinja_env.add_extension('jinja2.ext.loopcontrols')
    app.jinja_env.add_extension('jinja2.ext.with_')
    from ext.relative_templates import RelativeInclude
    app.jinja_env.add_extension(RelativeInclude)
    #app.jinja_env.add_extension('compressor.contrib.jinja2ext.CompressorExtension')

    if gae and not production:
        # enable jinja debugging info in GAE SDK
        # http://jinja.pocoo.org/docs/faq/#my-tracebacks-look-weird-what-s-happening
        from google.appengine.tools.devappserver2.python import sandbox
        sandbox._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt']

    return app
    def _runFlask(self, gw, port):
        """
        :param gw: Gateway
        :type gw: smsframework.Gateway.Gateway
        :return:
        :rtype:
        """
        # Init flask
        app = Flask(__name__)
        app.debug = True
        app.testing = True

        # Register gateway receivers
        gw.receiver_blueprints_register(app, prefix='/sms')

        # Stop manually
        @app.route('/kill', methods=['GET','POST'])
        def kill():
            func = request.environ.get('werkzeug.server.shutdown')
            if func is None:
                raise RuntimeError('Not running with the Werkzeug Server')
            func()
            return ''

        # Run
        app.run('0.0.0.0', port, threaded=False, use_reloader=False, passthrough_errors=True)
def create_app(config, debug=False, testing=False, config_overrides=None):
  app = Flask(__name__)
  app.config.from_object(config)

  app.debug = debug
  app.testing = testing

  if config_overrides:
    app.config.update(config_overrides)

  #Configure logging
  if not app.testing:
    logging.basicConfig(level=logging.INFO)

  #Setup the data model
  with app.app_context():
    model = get_model()
    model.init_app(app)

  from .app import appview
  app.register_blueprint(appview, url_prefix='')

  @app.errorhandler(500)
  def server_error(e):
    return """
    An internal error occurred:<pre>{}</pre>
    """.format(e), 500

  return app
Beispiel #8
0
def create_app(config, debug=False, testing=False, config_overrides=None):
    app = Flask(__name__)
    app.config.from_object(config)

    app.debug = debug
    app.testing = testing

    if config_overrides:
        app.config.update(config_overrides)

    # Setup the data model.
    with app.app_context():
        model = get_model()
        model.init_app(app)

    # Register the Bookshelf CRUD blueprint.
    from .user_crud import user_crud
    app.register_blueprint(user_crud, url_prefix='/users')

    # Add a default root route.
    @app.route("/")
    def index():
        return redirect(url_for('user_crud.list'))

    return app
Beispiel #9
0
def create_app(config, debug=False, testing=False, config_overrides=None):
  """Application factory
  """
  # define the WSGI application object
  flask_app = Flask(__name__)

  # configuration
  flask_app.config.from_object(config)
  flask_app.debug = debug
  flask_app.testing = testing

  if config_overrides:
    flask_app.config.update(config_overrides)

  # initialize the database
  db.init_app(flask_app)

  # blueprints
  from app.users import users_blueprint
  flask_app.register_blueprint(users_blueprint)

  # flask-restful
  from app.users import UserListAPI, UserAPI

  api = Api(prefix='/api/v0')
  api.add_resource(UserListAPI, '/users', endpoint='users')
  api.add_resource(UserAPI, '/users/<id>', endpoint='user')

  api.init_app(flask_app)

  cors = CORS(resources={r'/api/*': {'origins': '*'}})
  cors.init_app(flask_app)

  return flask_app
Beispiel #10
0
def app():
    app = Flask(__name__)
    app.debug = True
    app.testing = True

    @app.context_processor
    def expose_current_timestamp():
        return {
            'now': datetime.now(),
        }

    @app.route('/naturalday')
    def naturalday():
        return render_template_string("{{ now|humanize('naturalday') }}")

    @app.route('/naturaltime')
    def naturaltime():
        return render_template_string("{{ now|humanize('naturaltime') }}")

    @app.route('/naturaldelta')
    def naturaldelta():
        return render_template_string("{{ value|humanize('naturaldelta') }}",
                                      value=timedelta(days=7))

    return app
Beispiel #11
0
def _get_flask_app(roles=False, **kwargs):
    db = SQLAlchemy('sqlite:///:memory:')
    auth = authcode.Auth(
        SECRET_KEY, db=db, roles=roles, password_minlen=3, **kwargs)
    User = auth.User

    db.create_all()
    user = User(login=u'meh', password='foobar')
    db.add(user)

    user2 = User(login=u'foo', password='bar')
    db.add(user2)
    db.commit()

    app = Flask('test')
    app.secret_key = os.urandom(32)
    app.testing = True

    @app.route('/protected/')
    @auth.protected()
    def protected():
        return u'Welcome'

    authcode.setup_for_flask(auth, app)
    auth.session = {}
    return auth, app, user
def gen_app(config):
    """Generate a fresh app."""
    app = Flask('testapp')
    app.testing = True
    app.config.update(**config)

    FlaskCLI(app)
    FlaskMenu(app)
    Babel(app)
    Mail(app)
    InvenioDB(app)
    InvenioAccounts(app)
    FlaskOAuth(app)
    InvenioOAuthClient(app)

    app.register_blueprint(blueprint_client)
    app.register_blueprint(blueprint_settings)

    with app.app_context():
        db.create_all()

    app.test_request_context().push()

    datastore = app.extensions['invenio-accounts'].datastore

    datastore.create_user(
        email="existing@invenio-software.org", password='tester', active=True)
    datastore.create_user(
        email="test2@invenio-software.org", password='tester', active=True)
    datastore.create_user(
        email="test3@invenio-software.org", password='tester', active=True)
    datastore.commit()

    return app
    def setUp(self):
        # Create an Flask application instance for testing.
        app = Flask(__name__)
        app.secret_key = 'testkey'
        app.testing = True
        app.config.update(CURRENT_CONFIG)

        # Attach routes for testing values in the app config.
        @app.route('/test_default_config/<config_key>/')
        def test_default_config(config_key):
            self.assertEqual(CURRENT_CONFIG[config_key],
                             app.config[config_key])
            return ''

        @app.route('/test_overridden_config/<config_key>/<value_expected>/')
        def test_overridden_config(config_key, value_expected):
            self.assertEqual(value_expected,
                             app.config[config_key])
            return ''

        # Attach the ConfigOverride to the created app
        ConfigOverride(app)

        # instance available for testing
        self.app = app
def create_app(config, debug=False, testing=False, config_overrides=None):
    app = Flask(__name__)
    app.config.from_object(config)

    app.debug = debug
    app.testing = testing

    if config_overrides:
        app.config.update(config_overrides)

    # [START setup_logging]
    if not app.testing:
        client = google.cloud.logging.Client(app.config['PROJECT_ID'])
        handler = CloudLoggingHandler(client)
        # Attaches the handler to the root logger
        setup_logging(handler)
        logging.getLogger().setLevel(logging.INFO)
    # [END setup_logging]

    # Setup the data model.
    with app.app_context():
        model = get_model()
        model.init_app(app)

    # Initalize the OAuth2 helper.
    oauth2.init_app(
        app,
        scopes=['email', 'profile'],
        authorize_callback=_request_user_info)

    # Add a logout handler.
    @app.route('/logout')
    def logout():
        # Delete the user's profile and the credentials stored by oauth2.
        del session['profile']
        session.modified = True
        oauth2.storage.delete()
        return redirect(request.referrer or '/')

    # Register the Bookshelf CRUD blueprint.
    from .crud import crud
    app.register_blueprint(crud, url_prefix='/books')

    # Add a default root route.
    @app.route("/")
    def index():
        return redirect(url_for('crud.list'))

    # Add an error handler. This is useful for debugging the live application,
    # however, you should disable the output of the exception for production
    # applications.
    @app.errorhandler(500)
    def server_error(e):
        return """
        An internal error occurred: <pre>{}</pre>
        See logs for full stacktrace.
        """.format(e), 500

    return app
Beispiel #15
0
def test_error_unexpected_exception_testing():
    test_app = Flask(__name__)
    test_app.testing = True
    with test_app.test_request_context():
        msg = 'missing stuff'
        error = Exception(msg)
        with assert_raises(Exception):
            api.error_handler(error)
Beispiel #16
0
def app(request):
    # XXX: __name__ doesn't work due to a bug in Flask / an optional method not
    # implemented by a py.test meta path loader. py.test has the method in the
    # trunk version, so let's change this to __name__ when that version comes
    # out, currently we are at pytest 2.3.5
    app = Flask('__main__')
    app.config['SECRET_KEY'] = b'secret'
    app.testing = True
    return app
def create_app(config, debug=False, testing=False, config_overrides=None):
    app = Flask(__name__)
    app.config.from_object(config)

    app.debug = debug
    app.testing = testing

    if config_overrides:
        app.config.update(config_overrides)

    # Configure logging
    if not app.testing:
        client = google.cloud.logging.Client(app.config['PROJECT_ID'])
        # Attaches a Google Stackdriver logging handler to the root logger
        client.setup_logging(logging.INFO)
    # Setup the data model.
    with app.app_context():
        model = get_model()
        model.init_app(app)

    # Initalize the OAuth2 helper.
    oauth2.init_app(
        app,
        scopes=['email', 'profile'],
        authorize_callback=_request_user_info)

    # Add a logout handler.
    @app.route('/logout')
    def logout():
        # Delete the user's profile and the credentials stored by oauth2.
        del session['profile']
        session.modified = True
        oauth2.storage.delete()
        return redirect(request.referrer or '/')

    # Register the Bookshelf CRUD blueprint.
    from .crud import crud
    app.register_blueprint(crud, url_prefix='/books')

    # Add a default root route.
    @app.route("/")
    def index():
        return redirect(url_for('crud.list'))

    # Add an error handler that reports exceptions to Stackdriver Error
    # Reporting. Note that this error handler is only used when debug
    # is False
    @app.errorhandler(500)
    def server_error(e):
        client = error_reporting.Client(app.config['PROJECT_ID'])
        client.report_exception(
            http_context=error_reporting.build_flask_context(request))
        return """
        An internal error occurred.
        """, 500

    return app
def create_flask_app(db_url):
    app = Flask(__name__)
    (app.db_session, app.db_metadata, app.db_engine) = init_db(db_url)
    app.debug = os.environ.get('DEBUG') == 'True'
    app.testing = os.environ.get('TESTING') == 'True'
    @app.teardown_request
    def shutdown_session(exception=None):
        app.db_session.remove()
    return app
Beispiel #19
0
    def create_app(self):
        app = Flask(__name__)
        app.testing = True
        app.secret_key = "secret"
        app.config["WTF_HIDDEN_TAG"]="div"

        @app.route("/", methods=("GET", "POST"))
        def index():

            form = MyForm()
            if form.validate_on_submit():
                name = form.name.data.upper()
            else:
                name = ''

            return render_template("index.html",
                                   form=form,
                                   name=name)

        @app.route("/simple/", methods=("POST",))
        def simple():
            form = SimpleForm()
            form.validate()
            assert form.meta.csrf
            assert not form.validate()
            return "OK"

        @app.route("/two_forms/", methods=("POST",))
        def two_forms():
            form = SimpleForm()
            assert form.meta.csrf
            assert form.validate()
            assert form.validate()
            form2 = SimpleForm()
            assert form2.meta.csrf
            assert form2.validate()
            return "OK"

        @app.route("/hidden/")
        def hidden():

            form = HiddenFieldsForm()
            return render_template("hidden.html", form=form)

        @app.route("/ajax/", methods=("POST",))
        def ajax_submit():
            form = MyForm()
            if form.validate_on_submit():
                return jsonify(name=form.name.data,
                               success=True,
                               errors=None)

            return jsonify(name=None,
                           #errors=form.errors,
                           success=False)

        return app
Beispiel #20
0
def app():
    _app = Flask(__name__)
    _app.secret_key = "anything"
    _app.testing = True

    @_app.route("/")
    def index():
        return "index"

    return _app
Beispiel #21
0
def make_app():
    app = Flask(__name__)

    # Load configuration.
    conf_file = os.environ.get("CONFIG", None)
    if not conf_file:
        raise Exception("Missing CONFIG environment variable with the configuration")
    app.config.from_pyfile(conf_file)
    if app.config['DEBUG']:
        app.testing = True

    return app
Beispiel #22
0
def test_render_as_xml():

    app = Flask(__name__)
    app.testing = True

    @app.route("/")
    @decorators.render_as_xml
    def index():
        return {"test": "ok"}

    with app.test_client() as c:
        data = c.get("/").data
        assert '<?xml version="1.0"' in data
Beispiel #23
0
        def create_app(info):
            app = Flask(__name__)
            app.testing = True

            @app.route('/get_post/<int:x>/<int:y>', methods=['GET', 'POST'])
            def yyy_get_post(x, y):
                pass

            @app.route('/zzz_post', methods=['POST'])
            def aaa_post():
                pass

            return app
Beispiel #24
0
def test_render_as_json():
    import json

    app = Flask(__name__)
    app.testing = True

    @app.route("/")
    @decorators.render_as_json
    def index():
        return {"test": "ok"}

    with app.test_client() as c:
        assert {"test": "ok"} == json.loads(c.get("/").data)
def create_app(config, debug=False, testing=False, config_overrides=None):
    app = Flask(__name__)
    app.config.from_object(config)

    app.debug = debug
    app.testing = testing

    if config_overrides:
        app.config.update(config_overrides)

    # Configure logging
    if not app.testing:
        logging.basicConfig(level=logging.INFO)

    # Setup the data model.
    with app.app_context():
        model = get_model()
        model.init_app(app)

    # Initalize the OAuth2 helper.
    oauth2.init_app(
        app,
        scopes=['email', 'profile'],
        authorize_callback=_request_user_info)

    # Add a logout handler.
    @app.route('/logout')
    def logout():
        # Delete the user's profile and the credentials stored by oauth2.
        del session['profile']
        oauth2.storage.delete()
        return redirect(request.referrer or '/')

    # Register the Bookshelf CRUD blueprint.
    from .crud import crud
    app.register_blueprint(crud, url_prefix='/books')

    # Add a default root route.
    @app.route("/")
    def index():
        return redirect(url_for('crud.list'))

    # Create a health check handler. Health checks are used when running on
    # Google Compute Engine by the load balancer to determine which instances
    # can serve traffic. Google App Engine also uses health checking, but
    # accepts any non-500 response as healthy.
    @app.route('/_ah/health')
    def health_check():
        return 'ok', 200

    return app
Beispiel #26
0
def make_app(app_name):
    app = Flask(app_name)

    # Load configuration.
    # conf_file = os.environ.get("CONFIG", None)
    # if not conf_file:
    #     raise Exception("Missing CONFIG environment variable with the configuration")
    # app.config.from_pyfile(conf_file)
    app.config.from_object('config')

    if app.config['DEBUG']:
        app.testing = True

    return app
Beispiel #27
0
def test_custom_templates():
    db = SQLAlchemy('sqlite:///:memory:')
    options = {
        'template_sign_in': 'sign-in.html',
        'template_sign_out': 'sign-out.html',
        'template_reset': 'reset-password.html',
        'template_reset_email': 'reset-password-email.html',
        'template_change_password': 'change-password.html',
    }
    inbox = []

    def send_email(user, subject, msg):
        inbox.append(msg)

    auth = authcode.Auth(SECRET_KEY, db=db, **options)
    User = auth.User
    db.create_all()
    user = User(login=u'meh', password='foobar')
    db.add(user)
    db.commit()

    custom_templates = os.path.join(
        os.path.dirname(__file__),
        'custom_templates'
    )
    app = Flask('test', template_folder=custom_templates)
    app.secret_key = os.urandom(32)
    app.testing = True
    authcode.setup_for_flask(auth, app, send_email=send_email)
    auth.session = {}
    client = app.test_client()

    resp = client.get(auth.url_sign_in)
    assert resp.data == b'OK SIGN IN'

    resp = client.get(auth.url_reset_password)
    assert resp.data == b'OK RESET PASSWORD'

    data = dict(login=user.login, _csrf_token=auth.get_csrf_token())
    resp = client.post(auth.url_reset_password, data=data)
    assert inbox[0] == 'OK RESET PASSWORD EMAIL'

    auth.login(user)

    resp = client.get(auth.url_change_password)
    assert resp.data == b'OK CHANGE PASSWORD'

    url = '{0}?_csrf_token={1}'.format(auth.url_sign_out, auth.get_csrf_token())
    resp = client.get(url)
    assert resp.data == b'OK SIGN OUT'
Beispiel #28
0
def create_app(config):
    app = Flask(__name__)
    app.debug = True
    app.testing = True
    app.config['SECRET_KEY'] = 'so secret'

    for key, value in config.items():
        app.config[key] = value

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

    return app
Beispiel #29
0
def create_app():
    app = Flask(__name__)

    app.debug = True
    app.testing = False

    import config
    app.config.from_object(config)

    app.config['SHELF_PAGES'] = {
        "index": (IndexPage, IndexPageModelView),
        "contact": (ContactPage, ContactPageModelView),
    }

    with app.app_context():
        db.init_app(app)
        db.create_all()

        babel = Babel(app)

        shlf = Shelf(app)
        shlf.init_db(db)

        dview = DashboardView()
        shlf.init_admin(index_view=dview)

        shlf.init_security(User, Role)

        shlf.load_plugins((
            "shelf.plugins.dashboard",
            "shelf.plugins.i18n",
            "shelf.plugins.library",
            "shelf.plugins.page",
            "shelf.plugins.preview",
            "shelf.plugins.workflow",
            "shelf.plugins.wysiwyg",
            "shelf.plugins.ecommerce",
        ))
        init_admin(shlf.admin, db.session)
        shlf.setup_plugins()

        page = shlf.get_plugin_by_class(PagePlugin)
        page.register_pages(app, shlf.db)

        init_views(app)
        init_filters(app)

    return app
Beispiel #30
0
def create_app(config=None, debug=False, testing=False, config_overrides=None):
    """ Create the flask application
        Args:
            config flask configuration (python file)
            debug flask app mode
            testing flask app mode
            config_overrides a dictionary given if config has to be overrides
    """
    app = Flask(__name__, static_folder='templates')

    if config is not None:
        app.config.from_object(config)

    app.debug = debug
    app.testing = testing

    # import controllers
    from .controllers import init_app

    # load all routes with controllers
    init_app(app)

    if config_overrides:
        app.config.update(config_overrides)

    # Configure logging
    if not app.testing:
        logging.basicConfig(level=logging.INFO)

    # Add an error handler. This is useful for debugging the live application,
    # however, you should disable the output of the exception for production
    # applications.
    @app.errorhandler(500)
    def server_error(e):
        return """
        An internal error occurred: <pre>{}</pre>
        See logs for full stacktrace
        """.format(e), 500

    # @app.errorhandler(404)
    # def not_found_error(e):
    #     return """
    #     The requested page can't be found: <pre>{}</pre>
    #     """.format(e), 404


    return app