def setUp(self):
     application = Flask(__name__)
     application.config["TESTING"] = True
     application.secret_key = "you will not guess"
     application.permanent_session_lifetime = timedelta(seconds=1)
     self.application = application
     # Use an in memory database
     settings.EQ_SERVER_SIDE_STORAGE_DATABASE_URL = "sqlite://"
     self.session_manager = DatabaseSessionManager()
Beispiel #2
0
    def create_app(selfself):
        app = Flask(__name__)
        app.config["TESTING"] = True

        # fire up server for testing
        app.config["LIVESERVER_PORT"] = 8943
        return app
    def setUp(self):
        app = Flask(__name__)
        self.username = "testing@example.com"
        self.password = "ShowMeTheMoney"

        def is_valid_user(username, password):
            return (username, password) == (self.username, self.password)

        self.tasks = [{"id": 1, "task": "Do the laundry"}, {"id": 2, "task": "Do the dishes"}]

        def get_tasks(request):
            return self.tasks

        api_201409 = Api(version="v1")
        api_201409.register_endpoint(
            ApiEndpoint(
                http_method="GET",
                endpoint="/task/basic",
                handler=get_tasks,
                authentication=BasicAuth(is_valid_user=is_valid_user),
            )
        )

        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": "Decimal task", "price": Decimal(22.755)},
            {"id": 2, "task": "Float task", "price": 88.322},
            {"id": 3, "task": "Integer task", "price": 882},
        ]

        def get_tasks(request):
            return self.tasks

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

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

        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="GET", endpoint="/task/<int:task_id>/", 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()
Beispiel #5
0
    def assertRequest(self, method, request, response, want):
        """Execute a request and check the results."""
        error = isinstance(response, Exception)
        want_status = len(want) and want[1] or 200
        want_content = self.serialize(want[0])

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

        route = self.create_view(app, serializer, response)
        client_method = getattr(app.test_client(), method.lower())
        client_res = client_method(route)

        view_req, view_res = serializer.after
        self.assertEqual(client_res.status_code, want_status)
        self.assertEqual(client_res.data, want_content)
        if method == "GET":
            self.assertIsNone(view_req)
        else:
            self.assertEqual(view_req, request)
        if isinstance(response, int):
            self.assertEqual(view_res[1], response)
        else:
            if isinstance(response, Exception):
                response = get_error_response(response)
            self.assertEqual(view_res, response)
Beispiel #6
0
 def create_app(self):
     """
     Create app
     """
     app = Flask(__name__)
     app.config["TESTING"] = True
     return app
Beispiel #7
0
    def setUp(self):
        """Creates the Flask application and the APIManager."""
        # create the Flask application
        app = Flask(__name__)
        app.config["DEBUG"] = True
        app.config["TESTING"] = True
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
        app.logger.disabled = True
        self.flaskapp = app

        # create the test client
        self.app = app.test_client()

        # Ensure that all requests have Content-Type set to "application/json"
        # unless otherwise specified.
        for methodname in ("get", "put", "patch", "post", "delete"):
            # Create a decorator for the test client request methods that adds
            # a JSON Content-Type by default if none is specified.
            def set_content_type(func):
                def new_func(*args, **kw):
                    if "content_type" not in kw:
                        kw["content_type"] = "application/json"
                    return func(*args, **kw)

                return new_func

            # Decorate the original test client request method.
            old_method = getattr(self.app, methodname)
            setattr(self.app, methodname, set_content_type(old_method))
Beispiel #8
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
Beispiel #9
0
    def setUp(self):
        app = Flask(__name__)
        app.config["TESTING"] = True
        app.config["DEBUG"] = True
        app.config["TRAP_HTTP_EXCEPTIONS"] = True

        secret_key = "really big secret"
        token_manager = TokenManager(secret_key)

        token_auth = TokenAuth(secret_key)

        @app.route("/token")
        def get_token():
            user = "test_user"
            token = token_manager.generate(user).decode("utf-8")
            doc = {"token": token}
            return jsonify(doc)

        @app.route("/")
        def root():
            return jsonify({"message": "OK"})

        @app.route("/token_required")
        @token_auth.token_required
        def token_required():
            response = jsonify({"message": "OK"})
            response.status_code = 200
            return response

        self.app = app
        self.client = app.test_client()
        self.secret_key = secret_key
        self.token_manager = token_manager

        return self.app
    def setUp(self):
        app = Flask(__name__)

        def raises_dummy_exception(request):
            exc_type = request.args.get("exc_type")

            if exc_type == "subclass":
                raise DummyExceptionSubclass()
            elif exc_type == "other-subclass":
                raise DummyExceptionOtherSubclass()

            raise DummyException()

        api_201409 = Api(version="v1")
        api_201409.register_endpoint(
            ApiEndpoint(
                http_method="GET",
                endpoint="/dummy-exception",
                handler=raises_dummy_exception,
                exceptions=[(DummyExceptionOtherSubclass, 409), (DummyExceptionSubclass, 406), (DummyException, 400)],
            )
        )

        app.register_blueprint(api_201409)

        app.config["TESTING"] = True
        self.app = app.test_client()
    def test_data_returned_with_correct_status_code(self):
        app = Flask(__name__)
        self.conflicted_user = {"username": "johndoe"}

        def raises_exception(request):
            raise DummyDataException(data=self.conflicted_user)

        api_201409 = Api(version="v1")
        api_201409.register_endpoint(
            ApiEndpoint(
                http_method="GET",
                endpoint="/dummy-exception",
                handler=raises_exception,
                exceptions=[(DummyDataException, 409)],
            )
        )

        app.register_blueprint(api_201409)

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

        resp = self.app.get("/v1/dummy-exception", content_type="application/json")
        self.assertEqual(resp.status_code, 409)

        data = json.loads(resp.data.decode(resp.charset))
        self.assertEqual(data, self.conflicted_user)
Beispiel #12
0
    def test_flask(self):
        app = Flask(__name__)
        db = SQLAlchemy(app)
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"

        class Cities(db.Model):
            __tablename__ = "users"

            id = Column(Integer, primary_key=True)
            name = Column(String)
            population = Column(Integer)

            def __init__(self, name, population):
                self.name = name
                self.population = population

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

        city = Cities("Cordoba", 1000000)
        db.session.add(city)
        city = Cities("Rafaela", 99000)
        db.session.add(city)
        db.session.commit()

        query_string = '{ "sort": { "population" : "desc" } }'
        results = elastic_query(Cities, query_string)
        assert results[0].name == "Cordoba"
Beispiel #13
0
    def setUp(self):
        from flask import Flask

        app = Flask(__name__)
        app.config["TESTING"] = True
        provider_for_flask(app, "/", GreetingProvider())
        self.client = app.test_client()
Beispiel #14
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()
Beispiel #15
0
 def create_app(self):
     app = Flask("test")
     app.register_blueprint(blueprint, url_prefix="/bbg")
     app.config["DEBUG"] = True
     app.config["TESTING"] = True
     app.config["PRESERVE_CONTEXT_ON_EXCEPTION"] = True
     return app
Beispiel #16
0
 def setUp(self):
     """Setup up."""
     app = Flask(__name__)
     app.config["DEBUG"] = True
     app.config["TESTING"] = True
     app.logger.disabled = True
     self.app = app
Beispiel #17
0
    def setUp(self):
        """Creates the Flask application and the APIManager."""
        # create the Flask application
        app = Flask(__name__)
        app.config["DEBUG"] = True
        app.config["TESTING"] = True
        app.config["SECRET_KEY"] = "testing..."
        del app.logger.handlers[0]
        # sqlalchemy flask
        self.base = declarative_base()
        self.engine = create_engine("sqlite://")
        self.session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine))
        self.app = app
        self._ctx = self.app.test_request_context()
        self._ctx.push()
        self.client = self.app.test_client()

        # Add an error handler that returns straight LeverException
        # recommendations
        @self.app.errorhandler(LeverException)
        def handler(exc):
            tb = exc.extra.pop("tb", None)
            self.app.logger.debug(
                "Lever Exception Thrown!\n" "Extra: {0}\nEnd User: {1}".format(exc.extra, exc.end_user), exc_info=True
            )
            if tb:
                self.app.logger.debug("Traceback from lever exception:" "\n{0}".format(tb.replace("\\n", "\n")))
            return jsonify(**exc.end_user), exc.code

        return app
    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})
    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"})
Beispiel #20
0
def app_context(request):
    """Initialize the Flask application for tests."""
    app = Flask(__name__)
    app.config["TESTING"] = True
    context = app.app_context()
    context.push()
    request.addfinalizer(lambda: context.pop())
    def setUp(self):
        app = Flask(__name__, template_folder=os.path.dirname(__file__))
        app.debug = True
        app.config["TESTING"] = True
        app.config["SOLRQUERY_URL"] = "http://httpbin.org/get"

        self.solr = FlaskSolrQuery(app)
        self.app = app
 def create_app(self):
     config._set_connection_string("sqlite:///test.db")
     app = Flask("test")
     app.register_blueprint(FDPLoaderBlueprint, url_prefix="/loader")
     app.config["DEBUG"] = True
     app.config["TESTING"] = True
     app.config["PRESERVE_CONTEXT_ON_EXCEPTION"] = True
     return app
Beispiel #23
0
 def create_app(self):
     """
     This is a requirement for Flask-Testing
     """
     app = Flask(__name__)
     app.config["TESTING"] = True
     self.baseURL = "http://lvh.me:5000/"
     return app
Beispiel #24
0
 def create_app(self):
     app = Flask(__name__)
     app.config["TESTING"] = True
     app.config["SERVER_NAME"] = "localhost"
     app.config["SECRET_KEY"] = "secret secret"
     app.config["IMAGES_PATH"] = ["assets"]
     self.images = Images(app)
     return app
Beispiel #25
0
 def create_app(self):
     app = Flask(__name__)
     app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
     app.config["TESTING"] = True
     # app.config['SQLALCHEMY_ECHO'] = True
     app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
     db.init_app(app)
     return app
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
Beispiel #27
0
def app(request):
    flask_app = Flask(__name__)
    flask_app.config["TESTING"] = True
    flask_app.config["DEBUG"] = True
    flask_app.config["SERVER_NAME"] = "localhost"
    ctx = flask_app.app_context()
    ctx.push()
    request.addfinalizer(ctx.pop)
    return flask_app
Beispiel #28
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 create_app(self):
        app = Flask(__name__)
        app.config["TESTING"] = True

        @app.route("/candidates")
        def candidates():
            pass

        return app
Beispiel #30
0
def create_app():
    app = Flask(__name__)
    app.config["TESTING"] = True
    app.config["MONGODB_DATABASE"] = "flask_testing"

    maybe_conf_file = os.path.join(os.getcwd(), "config_test.cfg")
    if os.path.exists(maybe_conf_file):
        app.config.from_pyfile(maybe_conf_file)

    return app