def test_query_params_are_accesible(self):
        app = Flask(__name__)

        def multiplier(request, value):
            return {"result": value * int(request.args.get("multiplier", 1))}

        api_v1 = Api(version="v1")
        multiplier_endpoint = ApiEndpoint(http_method="GET", endpoint="/multiply/<int:value>/", handler=multiplier)
        api_v1.register_endpoint(multiplier_endpoint)

        app.register_blueprint(api_v1)

        app.config["TESTING"] = True
        self.app = app.test_client()

        resp = self.app.get("/v1/multiply/3/", content_type="application/json")
        self.assertEqual(resp.status_code, 200)

        data = json.loads(resp.data.decode(resp.charset))
        self.assertEqual(data, {"result": 3})

        resp = self.app.get("/v1/multiply/3/?multiplier=5", content_type="application/json")
        self.assertEqual(resp.status_code, 200)

        data = json.loads(resp.data.decode(resp.charset))
        self.assertEqual(data, {"result": 15})
Example #2
0
    def create_app(self):
        """Create the app."""
        from flask_iiif import IIIF
        from flask_restful import Api
        from flask_iiif.cache.simple import ImageSimpleCache

        app = Flask(__name__)
        app.config["DEBUG"] = True
        app.config["TESTING"] = True
        app.config["SERVER_NAME"] = "shield.worker.node.1"
        app.config["SITE_URL"] = "http://shield.worker.node.1"
        app.config["IIIF_CACHE_HANDLER"] = ImageSimpleCache()
        app.logger.disabled = True

        api = Api(app=app)

        iiif = IIIF(app=app)

        iiif.uuid_to_image_opener_handler(self.create_image)

        def api_decorator_test(*args, **kwargs):
            if "decorator" in kwargs.get("uuid"):
                abort(403)

        iiif.api_decorator_handler(api_decorator_test)

        iiif.init_restful(api)
        return app
Example #3
0
    def setUp(self):
        app = Flask(__name__)
        app.config["TESTING"] = True

        @app.route(CONSUMES_JSON_ONLY)
        @consumes(JSON)
        def consumes_json_only():
            return CONSUMES_JSON_ONLY

        @app.route(CONSUMES_JSON_AND_HTML)
        @consumes(JSON, HTML)
        def consumes_json_and_html():
            return CONSUMES_JSON_AND_HTML

        @app.route(PRODUCES_JSON_ONLY)
        @produces(JSON)
        def produces_json_only():
            return PRODUCES_JSON_ONLY

        @app.route(PRODUCES_JSON_AND_HTML)
        @produces(JSON, HTML)
        def produces_json_and_html():
            return PRODUCES_JSON_AND_HTML

        self.app = app
        self.client = app.test_client()
    def test_version_accesible_from_handler(self):
        app = Flask(__name__)

        def get_task(request):
            return {"version": request.api.version}

        api_201409 = Api(version="v1")
        api_201507 = Api(version="v2")
        task_endpoint = ApiEndpoint(http_method="GET", endpoint="/task/", handler=get_task)
        api_201409.register_endpoint(task_endpoint)
        api_201507.register_endpoint(task_endpoint)

        app.register_blueprint(api_201409)
        app.register_blueprint(api_201507)

        app.config["TESTING"] = True
        self.app = app.test_client()

        resp = self.app.get("/v1/task/", content_type="application/json")
        self.assertEqual(resp.status_code, 200)

        data = json.loads(resp.data.decode(resp.charset))
        self.assertEqual(data, {"version": "v1"})

        resp = self.app.get("/v2/task/", content_type="application/json")
        self.assertEqual(resp.status_code, 200)

        data = json.loads(resp.data.decode(resp.charset))
        self.assertEqual(data, {"version": "v2"})
Example #5
0
def app(request):
    from flask import Flask

    app = Flask(__name__)
    app.config["TESTING"] = True
    app.config["SEGMENTIO_SEND"] = False
    app.config["SEGMENTIO_WRITE_KEY"] = "testing"
    return app
Example #6
0
    def create_app(self):
        app = Flask(
            __name__,
            template_folder="../../app/static/templates"
        )
        app.config["TESTING"] = True
        app.register_blueprint(main)

        return app      
Example #7
0
    def _get_test_client(self, api):
        @api.dispatcher.add_method
        def dummy():
            return ""

        app = Flask(__name__)
        app.config["TESTING"] = True
        app.register_blueprint(api.as_blueprint())
        return app.test_client()
def app(request):
    from flask import Flask

    app = Flask(__name__)
    app.config["TESTING"] = True
    app.config["FLYWHEEL_DATABASE_HOST"] = "localhost"
    app.config["FLYWHEEL_DATABASE_PORT"] = 8000
    app.config["FLYWHEEL_SECURE"] = False
    return app
Example #9
0
    def create_app(self):
        app = Flask(config.APP_NAME)
        app = create_app(app)
        app.config["TESTING"] = True

        if app.config.get('TEST_DB_URI') is None:
            raise TestCaseDBException("No TEST_DB_URI specified in config.py!")

        app.config['SQLALCHEMY_DATABASE_URI'] = app.config.get('TEST_DB_URI')
        self.migration = Migration(app)
        return app
Example #10
0
 def setup_method(self, test_method):
     #self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()
     #flaskr.app.config['TESTING'] = True
     app = Flask(__name__)
     app.config["DEBUG"] = True
     app.config["TESTING"] = True
     app.register_blueprint(module_one)
     self.app = app.test_client()
     #flaskr.init_db()
     self.api_payload = {
         "user_name": "Alice",
         "greeting": "Howdy",
     }
Example #11
0
    def setUp(self):
        """Creates the Flask application and the APIManager."""
        super(FlaskTestBase, self).setUp()

        # create the Flask application
        app = Flask(__name__)
        app.config["DEBUG"] = True
        app.config["TESTING"] = True
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///%s" % DB["filename"]
        self.flaskapp = app

        # create the test client
        self.app = app.test_client()
Example #12
0
def create_test_app():
    """
    Create the Slack-lmgtfy application.

    @param instance_path the instance path of the web application. See Flask doc for more info
    @return the Slack-lmgtfy flask application
    """
    app = Flask("slack_lmgtfy")
    app.config["TESTING"] = True
    app.config.from_object("slack_lmgtfy.default_config")

    from slack_lmgtfy.views import bp
    app.register_blueprint(bp)
    return app
Example #13
0
def app_context():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "deterministic"
    app.config["TESTING"] = True
    app.config["PROPAGATE_EXCEPTIONS"] = True
    app.config["DEBUG"] = True

    @app.route("/")
    def index():
        return u"The index"

    @app.route("/login")
    def login():
        id = int(request.args["id"])
        force = "force" in request.args
        remember = "remember" in request.args
        if login_user(USERS[id], force=force, remember=remember):
            if "permanent" in request.args:
                session.permanent = True
            return u"Logged in"
        else:
            return u"Go away, creeper"

    class Protected(LoginRequiredMixin, MethodView):
        def get(self):
            return u"Welcome, %s" % current_user.name

    app.add_url_rule("/protected", view_func=Protected.as_view("protected"))

    @app.route("/sensitive-action")
    @fresh_login_required
    def sensitive_action():
        return u"Be careful, %s" % current_user.name

    @app.route("/logout")
    @login_required
    def logout():
        logout_user()
        return u"Logged out"

    @app.route("/reauth")
    @login_required
    def reauth():
        confirm_login()
        return u"Login confirmed"

    with app.test_request_context():
        yield app
def app():
    app_ = Flask("testapp")
    app_.config["DEBUG"] = True
    app_.config["TESTING"] = True

    @app_.route("/posts/<post_id>/comments/")
    def posts_comments(post_id):
        return "Comments for post {}".format(post_id)

    @app_.route("/authors/<int:author_id>")
    def author_detail(author_id):
        return "Detail for author {}".format(author_id)

    ctx = app_.test_request_context()
    ctx.push()
    yield app_
    ctx.pop()
    def setUp(self):
        app = Flask(__name__)
        self.tasks = [{"id": 1, "task": "Do the laundry"}, {"id": 2, "task": "Do the dishes"}]

        def get_tasks(request):
            return self.tasks

        def post_task(request):
            data = request.json
            self.tasks.append({"task": data["task"]})
            return {}, 201

        def put_task(request, task_id):
            task = get_task_by_id(self.tasks, task_id)
            data = request.json
            task["task"] = data["task"]
            task["id"] = data["id"]
            return {}, 204

        def patch_task(request, task_id):
            task = get_task_by_id(self.tasks, task_id)
            data = request.json
            task["task"] = data["task"]
            return {}, 204

        def delete_task(request, task_id):
            index = get_task_index_by_id(self.tasks, task_id)
            task = self.tasks.pop(index)
            return task

        api_201409 = Api(version="v1")
        api_201409.register_endpoint(ApiEndpoint(http_method="GET", endpoint="/task/", handler=get_tasks))
        api_201409.register_endpoint(ApiEndpoint(http_method="POST", endpoint="/task/", handler=post_task))
        api_201409.register_endpoint(ApiEndpoint(http_method="PUT", endpoint="/task/<int:task_id>/", handler=put_task))
        api_201409.register_endpoint(
            ApiEndpoint(http_method="PATCH", endpoint="/task/<int:task_id>/", handler=patch_task)
        )
        api_201409.register_endpoint(
            ApiEndpoint(http_method="DELETE", endpoint="/task/<int:task_id>/", handler=delete_task)
        )

        app.register_blueprint(api_201409)

        app.config["TESTING"] = True
        self.app = app.test_client()
    def test_versions_with_different_endpoints_different_url(self):
        app = Flask(__name__)

        get_tasks = mock.MagicMock(return_value={"id": 1, "task": "Do dishes"})
        get_tasks.__name__ = "get_tasks"
        get_users = mock.MagicMock(return_value={"id": 2, "username": "johndoe"})
        get_users.__name__ = "get_users"

        api_201409 = Api(version="v1")
        api_201507 = Api(version="v2")
        api_201409.register_endpoint(ApiEndpoint(http_method="GET", endpoint="/task/", handler=get_tasks))
        api_201507.register_endpoint(ApiEndpoint(http_method="GET", endpoint="/users/", handler=get_users))

        app.register_blueprint(api_201409)
        app.register_blueprint(api_201507)

        app.config["TESTING"] = True
        self.app = app.test_client()

        resp = self.app.get("/v1/users/", content_type="application/json")
        self.assertEqual(resp.status_code, 404)

        resp = self.app.get("/v1/task/", content_type="application/json")
        self.assertEqual(resp.status_code, 200)

        data = json.loads(resp.data.decode(resp.charset))
        self.assertEqual(data, {"id": 1, "task": "Do dishes"})

        self.assertEqual(get_tasks.call_count, 1)
        self.assertEqual(get_users.call_count, 0)

        resp = self.app.get("/v2/task/", content_type="application/json")
        self.assertEqual(resp.status_code, 404)

        resp = self.app.get("/v2/users/", content_type="application/json")
        self.assertEqual(resp.status_code, 200)

        data = json.loads(resp.data.decode(resp.charset))
        self.assertEqual(data, {"id": 2, "username": "johndoe"})

        self.assertEqual(get_tasks.call_count, 1)
        self.assertEqual(get_users.call_count, 1)
Example #17
0
def app_context():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "deterministic"
    app.config["TESTING"] = True
    app.config["PROPAGATE_EXCEPTIONS"] = True
    app.config["DEBUG"] = True
    
    @app.route("/")
    def index():
        return u"The index"
    
    @app.route("/login")
    def login():
        id = int(request.args["id"])
        force = "force" in request.args
        remember = "remember" in request.args
        if login_user(USERS[id], force=force, remember=remember):
            if "permanent" in request.args:
                session.permanent = True
            return u"Logged in"
        else:
            return u"Go away, creeper"
    
    @app.route("/protected")
    @login_required
    def protected():
        return u"Welcome, %s" % current_user.name
    
    @app.route("/logout")
    @login_required
    def logout():
        logout_user()
        return u"Logged out"
    
    @app.route("/reauth")
    @login_required
    def reauth():
        confirm_login()
        return u"Login confirmed"
    
    with app.test_request_context():
        yield app
    def setUp(self):
        app = Flask(__name__)

        def success_handler(request):
            if request.method == "GET":
                return {}, 200
            elif request.method == "POST":
                return {}, 201

        def conflict_handler(request):
            return {"task": "Conflicted Task"}, 409

        api_201409 = Api(version="v1")
        api_201409.register_endpoint(ApiEndpoint(http_method=["GET", "POST"], endpoint="/", handler=success_handler))
        api_201409.register_endpoint(ApiEndpoint(http_method="GET", endpoint="/conflict", handler=conflict_handler))

        app.register_blueprint(api_201409)

        app.config["TESTING"] = True
        self.app = app.test_client()
    def test_api_without_a_version_and_with_name(self):
        app = Flask(__name__)

        get_tasks = mock.MagicMock(return_value={"id": 1, "task": "Do dishes"})
        get_tasks.__name__ = "get_tasks"

        api_v1 = Api(name="Test-API")

        api_v1.register_endpoint(ApiEndpoint(http_method="GET", endpoint="/task/", handler=get_tasks))
        app.register_blueprint(api_v1)

        app.config["TESTING"] = True
        self.app = app.test_client()

        resp = self.app.get("/task/", content_type="application/json")
        self.assertEqual(resp.status_code, 200)

        data = json.loads(resp.data.decode(resp.charset))
        self.assertEqual(data, {"id": 1, "task": "Do dishes"})

        self.assertEqual(get_tasks.call_count, 1)
Example #20
0
def generate_context(config):
    """Creates the Flask app context and initializes any extensions such as Celery, Redis, SQLAlchemy, etc.

    Positional arguments:
    config -- partial Flask config dict from generate_config().

    Returns:
    The Flask app instance.
    """
    flask_app = Flask(__name__)
    flask_app.config.update(config)
    flask_app.config["TESTING"] = True
    flask_app.config["CELERY_ACCEPT_CONTENT"] = ["pickle"]

    if "SQLALCHEMY_DATABASE_URI" in flask_app.config:
        db = SQLAlchemy(flask_app)
        db.engine.execute("DROP TABLE IF EXISTS celery_tasksetmeta;")
    elif "REDIS_URL" in flask_app.config:
        redis = Redis(flask_app)
        redis.flushdb()

    Celery(flask_app)
    return flask_app
    def test_versions_with_same_endpoints(self):
        app = Flask(__name__)

        def get_task(request):
            return self.tasks

        api_201409 = Api(version="v1")
        api_201507 = Api(version="v2")
        task_endpoint = ApiEndpoint(http_method="GET", endpoint="/task/", handler=get_task)
        api_201409.register_endpoint(task_endpoint)
        api_201507.register_endpoint(task_endpoint)

        app.register_blueprint(api_201409)
        app.register_blueprint(api_201507)

        app.config["TESTING"] = True
        self.app = app.test_client()

        resp = self.app.get("/v1/task/", content_type="application/json")
        self.assertEqual(resp.status_code, 200)

        resp = self.app.get("/v2/task/", content_type="application/json")
        self.assertEqual(resp.status_code, 200)
    def setUp(self):
        app = Flask(__name__)
        self.tasks = [{"id": 1, "task": "Do the laundry"}, {"id": 2, "task": "Do the dishes"}]

        def get_tasks(request):
            return self.tasks, 200, {"Access-Control-Allow-Origin": "*"}

        def post_task(request):
            data = request.json
            self.tasks.append({"task": data["task"]})
            return {}, 201, {"X-Special-Header": "XXX", "Access-Control-Allow-Origin": "*"}

        api_201409 = Api(version="v1")
        task_endpoint = ApiEndpoint(http_method="GET", endpoint="/task/", handler=get_tasks)
        api_201409.register_endpoint(task_endpoint)

        task_endpoint = ApiEndpoint(http_method="POST", endpoint="/task/", handler=post_task)
        api_201409.register_endpoint(task_endpoint)

        app.register_blueprint(api_201409)

        app.config["TESTING"] = True
        self.app = app.test_client()
    def setUp(self):
        app = Flask(__name__)
        tasks = [{"id": 1, "task": "Do the laundry"}, {"id": 2, "task": "Do the dishes"}]

        def get_task(request):
            return tasks

        def post_task(request):
            data = request.json
            tasks.append({"task": data["task"]})
            return {}, 201

        api_201409 = Api(version="v1")
        task_endpoint = ApiEndpoint(http_method="GET", endpoint="/task/", handler=get_task)
        api_201409.register_endpoint(task_endpoint)

        task_endpoint = ApiEndpoint(http_method="POST", endpoint="/task/", handler=post_task)
        api_201409.register_endpoint(task_endpoint)

        app.register_blueprint(api_201409)

        app.config["TESTING"] = True
        self.app = app.test_client()
    def setUp(self):
        app = Flask(__name__)
        self.tasks = [
            {"id": 1, "task": "Do the laundry"},
            {"id": 2, "task": "Do the dishes"},
            {"id": 3, "task": "Take the dog out"},
        ]

        def get_tasks(request):
            return self.tasks

        def get_task(request, task_id):
            return get_task_by_id(self.tasks, task_id)

        api_201409 = Api(version="v1")
        all_task_endpoint = ApiEndpoint(http_method="GET", endpoint="/task/", handler=get_tasks)
        task_endpoint = ApiEndpoint(http_method="GET", endpoint="/task/<int:task_id>/", handler=get_task)
        api_201409.register_endpoint(task_endpoint)
        api_201409.register_endpoint(all_task_endpoint)

        app.register_blueprint(api_201409)

        app.config["TESTING"] = True
        self.app = app.test_client()
Example #25
0
 def setUp(self):
     app = Flask(__name__)
     app.config["DEBUG"] = True
     app.config["TESTING"] = True
     app.logger.disabled = True
     self.app = app
Example #26
0
from flask import Flask, render_template, send_from_directory, jsonify, redirect, url_for, request, abort
from flask.ext.sqlalchemy import SQLAlchemy
import uuid

import random, string

from dungeon import dungeon
from cards import cards

# Initilization
APPLICATION_CONFIG = os.environ.get("BLUE_MONGOOSE_SETTINGS")
BASE_URL = "https://blue-mongoose.herokuapp.com/"

app = Flask(__name__)
app.config["DEBUG"] = False
app.config["TESTING"] = False

if APPLICATION_CONFIG == "production":
    print("Starting in production mode")
    app.config["DATABASE_URI"] = os.environ["DATABASE_URL"]
    GITHUB_CLIENT_ID = os.environ["GITHUB_CLIENT_ID"]
    GITHUB_CLIENT_SECRET = os.environ["GITHUB_CLIENT_SECRET"]
else:
    BASE_URL = "http://localhost:5000/"
    app.config["DATABASE_URI"] = os.environ["BLUE_MONGOOSE_DATABASE_URL"]

    GITHUB_CLIENT_ID = os.environ["BLUE_MONGOOSE_GITHUB_CLIENT_ID"]
    GITHUB_CLIENT_SECRET = os.environ["BLUE_MONGOOSE_GITHUB_CLIENT_SECRET"]

    if APPLICATION_CONFIG == "testing":
        app.config["TESTING"] = True
Example #27
0
    from pprint import pprint

    class TestedNamedView(NamedMethodView):
        @namedmethod("editor")
        def get(self):
            return "editor get"

        @namedmethod("editor", "post")
        def editor_post(self):
            return "editor post"

        def post(self):
            return "raw post"

    test = Flask(__name__)
    test.config["TESTING"] = True
    test.config["DEBUG"] = True
    test.config["SERVER_NAME"] = "localhost:5000"

    test.add_url_rule("/test", view_func=TestedNamedView.as_view("test"))

    class TestNamedMethodView(unittest.TestCase):
        def setUp(self):
            self.client = test.test_client()

        def test_405(self):
            self.assertTrue(self.client.get("/test").status_code == 405)

        def test_named_get(self):
            self.assertTrue(
                "".join(self.client.get("/test", headers=[("X-View-Name", "editor")]).response) == "editor get"
Example #28
0
def create_app(_run_mode=None):
    # Create Flask app
    global app
    template_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
    app = Flask("application", template_folder=template_dir)

    # Load kill switches
    # app.config["APP_KILL_CACHE"] = os.environ.get("APP_KILL_CACHE", False)

    # Load default configuration
    app.config.from_object("application.default_config")

    # Dev run mode
    if _run_mode == "dev":
        app.config["DEBUG"] = True

        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"    # Replace with local DB

        app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False  # Otherwise this gets annoying real fast
        DebugToolbarExtension(app)

    # Test run mode
    elif _run_mode == "test":
        app.config["DEBUG"] = True
        app.config["TESTING"] = True
        app.config["WTF_CSRF_ENABLED"] = False  # Or CSRF checks will fail
#        app.config["APP_KILL_CACHE"] = True
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"

    # Production run mode
    elif _run_mode == "production":
        # Get additional configuration based on run environment
        run_environment = os.environ.get("APP_RUN_ENV", "local")
        if run_environment == "heroku":
            # Get configuration data from Heroku environment variables
            app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")

        elif run_environment == "vagrant":
            app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"    # Replace with local DB

        set_up_logging(app)

    # Unrecognized run mode
    else:
        logging.error("Did not recognize run mode '%s'" % _run_mode)
        return None, None

    # Initialize the database
    global db
    import application.models
    db.init_app(app)

    # Initialize other Flask extensions

    # Import the views, to apply the decorators which use the global app object.
    import application.views

    # Register blueprints
    # from application.widget import widget_blueprint
    # app.register_blueprint(widget_blueprint)

    # Set up Jinja 2 filters
    set_up_jinja_filters(app)

    return app, db
from werkzeug.datastructures import Headers
import unittest
from base64 import b64encode


class MyAuthenticator(Authenticator):
    def authenticate(self, auth_data):
        if auth_data.username == "admin" and auth_data.password == "admin":
            return {"username": auth_data.username, "password": auth_data.password}
        return None


authenticator = MyAuthenticator(basic_auth_getter)

app = Flask(__name__)
app.config["TESTING"] = True


def send_401(message):
    """Sends a 401 response that enables basic auth"""
    return Response(message, 401, {"WWW-Authenticate": 'Basic realm="Login Required"'})


@app.errorhandler(AuthDataDecodingException)
def bad_auth_data_callback(ex):
    return send_401("Missing credentials")


@app.errorhandler(NotAuthenticatedException)
def not_authenticated_callback(ex):
    return send_401("User not recognized")
Example #30
0
 def create_app(self):
     app = Flask(__name__)
     app.config["TESTING"] = True
     app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
     return app