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
1
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
1
    def setUp(self):
        app = Flask(__name__)
        app.config.from_object(settings)
        app.testing = True
        app.config["MONGO_DBNAME"] = "bergenholmtest"
        database.init_db(app)

        app.register_blueprint(frontend, url_prefix="")
        app.register_blueprint(ipxe, url_prefix="/ipxe")
        app.register_blueprint(hosts, url_prefix="/api/1.0/hosts")
        app.register_blueprint(groups, url_prefix="/api/1.0/groups")
        app.register_blueprint(templates, url_prefix="/api/1.0/templates")
        app.register_blueprint(power, url_prefix="/api/1.0/power")

        self.app = app
        self.client = app.test_client()
        self.mongo = database.mongo

        with self.app.test_request_context("/"):
            self.mongo.db.hosts.remove()
            self.mongo.db.groups.remove()
            self.mongo.db.templates.remove()

            params = {u"_id": self.host_id}
            params.update(self.host_params)
            self.mongo.db.hosts.insert(params)

            self.mongo.db.groups.insert({u"_id": u"default", u"base_url": u"http://127.0.0.1"})

            params = {u"_id": self.group_id}
            params.update(self.group_params)
            self.mongo.db.groups.insert(params)

            self.mongo.db.templates.insert({u"_id": self.template_id, u"content": self.template})
Beispiel #4
1
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 #5
1
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
Beispiel #6
1
def get_flask_app(roles=False, views=None, **kwargs):
    db = SQLAlchemy("sqlite:///:memory:")
    views = views or []
    auth = authcode.Auth(SECRET_KEY, db=db, roles=roles, views=views, **kwargs)
    User = auth.User

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

    app = Flask("test")
    app.secret_key = os.urandom(32)
    app.testing = True
    authcode.setup_for_flask(auth, app)

    @app.route("/login/")
    def login():
        user = User.by_id(1)
        auth.login(user)
        return "login"

    @app.route("/logout/")
    def logout():
        auth.logout()
        return "logout"

    return auth, app, user
Beispiel #7
1
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)
    InvenioTheme(app)
    return app
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
Beispiel #9
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 #10
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 #11
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
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 #13
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)
Beispiel #14
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 #15
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 #16
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 #17
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
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)

    # 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

    # 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"))

    return app
    def setUp(self):
        app = Flask(__name__)
        app.debug = True
        app.testing = True
        app.secret_key = "development"

        self.db_fd, self.db_file = tempfile.mkstemp()
        config = {"SQLALCHEMY_DATABASE_URI": "sqlite:///%s" % self.db_file}
        app.config.update(config)

        app = create_server(app)
        app = create_client(app)

        self.app = app
        self.client = app.test_client()
        return app
Beispiel #20
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 #21
0
    def setUp(self):
        app = Flask(__name__, template_folder="test_templates")
        app.testing = True
        pushrod = Pushrod(app)

        pushrod.register_renderer(repr_renderer)
        pushrod.default_renderer = repr_renderer

        self.app = app
        self.pushrod = app.extensions["pushrod"]
        self.client = app.test_client()

        app_context = app.app_context()
        app_context.push()
        if not hasattr(self, "app_contexts"):
            self.app_contexts = []
        self.app_contexts.append(app_context)
Beispiel #22
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)

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

    # Register the Bookshelf CRUD blueprint.
    from .views import views

    app.register_blueprint(views, url_prefix="/gps")

    # Add a default root route.
    @app.route("/")
    def index():
        return redirect(url_for("views.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
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]
    # Configure logging
    if not app.testing:
        logging.basicConfig(level=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"]
        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"))

    return app
Beispiel #24
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 #25
0
    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")

        # Kill
        @app.route("/kill", methods=["POST"])
        def kill():
            raise KeyboardInterrupt("/kill")

        # Run
        run_simple("0.0.0.0", port, app, passthrough_errors=True)
    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
Beispiel #27
0
    def create_application():
        """Create a test Flask application.
        """
        ret_val = Flask(__name__)
        ret_val.testing = True
        ret_val.config["EXCEPTIONAL_API_KEY"] = "key"
        ret_val.config["EXCEPTIONAL_DEBUG_URL"] = (
            os.environ.get("EXCEPTIONAL_DEBUG_URL") or "http://www.postbin.org/m7viy8"
        )

        @ret_val.route("/error")
        def error():
            """Do something that raises an exception.
            """
            1 / 0

        @ret_val.route("/http/<int:code>")
        def http(code):
            """Raises an HTTP exception.
            """
            abort(code)

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

    # Configurations
    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)

    # Import a module / component using its blueprint handler variable (mod_auth)
    from blogapp.mod_auth.controllers import mod_auth as auth_module
    from blogapp.mod_post import mod_post

    with app.app_context():
        model.init_app(app)

    # Register blueprint(s)
    app.register_blueprint(auth_module)
    app.register_blueprint(mod_post)

    # Add a default root route.
    @app.route("/")
    def index():
        return render_template("index.html")

    # Sample HTTP error handling
    @app.errorhandler(404)
    def not_found(error):
        return render_template("404.html"), 404

    return app
Beispiel #29
0
    def create_application():
        """Create a test Flask application.
        """
        ret_val = Flask(__name__)
        ret_val.testing = True
        ret_val.config["EXCEPTIONAL_API_KEY"] = "key"
        ret_val.config["EXCEPTIONAL_DEBUG_URL"] = environ.get(
            "EXCEPTIONAL_DEBUG_URL", "http://posttestserver.com/post.php"
        )
        ret_val.config["PROPAGATE_EXCEPTIONS"] = False

        @ret_val.route("/error")
        def error():
            """Do something that raises an exception.
            """
            1 / 0

        @ret_val.route("/http/<int:code>")
        def http(code):
            """Raises an HTTP exception.
            """
            abort(code)

        return ret_val
Beispiel #30
0
import os
from flask import Flask
from flask_login import LoginManager

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///codegolf.db"
app.config["GITHUB_CONSUMER_KEY"] = os.environ["CODEGOLF_GITHUB_CONSUMER_KEY"]
app.config["GITHUB_CONSUMER_SECRET"] = os.environ["CODEGOLF_GITHUB_CONSUMER_SECRET"]
app.config["SECRET_KEY"] = os.environ["CODEGOLF_SECRET_KEY"]
app.testing = False

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "user.login"
login_manager.login_message = "Log In Please"

from .models import *

from .user import user as user_bp
from .challenge import challenge as challenge_bp
from .submission import submission as submission_bp

BLUEPRINTS = (user_bp, challenge_bp, submission_bp)

for blueprint in BLUEPRINTS:
    app.register_blueprint(blueprint)

from . import views