Пример #1
0
Файл: base.py Проект: agdsn/sipa
    def create_app(self):
        """Create a new instance of sipa using :py:func:`create_app`

        A new instance of sipa will be executed with the following
        config customizations:

            - SECRET_KEY is set to a random value

            - TESTING is set to True

            - debug is enabled

            - WTF_CSRF_ENABLED is set to False

            - PRESERVE_CONTEXT_ON_EXCEPTION

        This config is extended by the values of the attribute
        :py:attr:`app_config`.
        """
        test_app = Flask('sipa')
        test_app.config['SECRET_KEY'] = os.urandom(100)
        test_app.config['TESTING'] = True
        test_app.config['LOG_CONFIG'] = WARNINGS_ONLY_CONFIG
        test_app.config['WTF_CSRF_ENABLED'] = False
        test_app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False
        test_app.config['CONTACT_SENDER_MAIL'] = "test@foo.de"
        test_app.debug = True
        return create_app(app=test_app, config=self.app_config)
Пример #2
0
    def create_app(self):
        app = Flask(__name__)
        app.config['TESTING'] = True

        # Default port is 5000
        app.config['LIVESERVER_PORT'] = 8943
        return app
Пример #3
0
def create_app(disable_hmac=None):
    app = Flask(__name__)
    app.config['TESTING'] = True
    app.config['HMAC_KEY'] = 's3cr3tk3y'
    app.config['HMAC_KEYS'] = {
        'a': 'f00',
        'b': 'b4r',
    }
    if disable_hmac:
        app.config['HMAC_DISARM'] = disable_hmac
    hmac.init_app(app)

    @app.route('/no_auth_view')
    def no_auth_view():
        return 'no_auth_view'

    @app.route('/hmac_auth_view', methods=['GET', 'POST'])
    @hmac.auth()
    def hmac_auth_view():
        return 'hmac_auth_view'

    @app.route('/only_view', methods=['GET', 'POST'])
    @hmac.auth(only=["b"])
    def only_view():
        return 'hmac_auth_view'

    return app
Пример #4
0
def create_app(test_mode=False):
    app = Flask(
        __name__,
        static_url_path='/static',
        static_folder='static',
        instance_relative_config=False)

    app.config.from_object(rq_dashboard.default_settings)
    app.config.from_object(rq_scheduler_dashboard.default_settings)
    app.config.from_pyfile('config.py')

    if test_mode:
        # sobreescrita de conf para testing
        app.config.from_pyfile('config_testing.py')
        app.config['TESTING'] = True
        app.config['DEBUG'] = False

    # init extensions
    register_extensions(app)
    # blueprints
    regiter_bluprints(app)
    # jinja custom filters
    register_jinja_filters(app)

    app.wsgi_app = ProxyFix(app.wsgi_app)
    urls.add_url_rules(app)

    return app
Пример #5
0
 def create_app(self):
     """
     Create app
     """
     app = Flask(__name__)
     app.config['TESTING'] = True
     return app
Пример #6
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)
Пример #7
0
    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)
Пример #8
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))
Пример #9
0
    def setUp(self):
        app = Flask(__name__)
        app.config['TESTING'] = True
        app.config['DEBUG'] = True
        app.config['TRAP_HTTP_EXCEPTIONS'] = True

        secret_key = u'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
Пример #10
0
    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 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 test_process_request_with_one_middleware_that_doesnt_return(self):
        app = Flask(__name__)

        def get_tasks(request):
            return self.tasks

        api_201409 = Api(version="v1")
        with mock.patch.object(DummyMiddleware, 'process_request',
                               return_value=None) as mock_method:
            api_201409.register_endpoint(ApiEndpoint(
                http_method="GET",
                endpoint="/task/",
                handler=get_tasks,
                middleware=[
                    DummyMiddleware
                ]
            ))
            app.register_blueprint(api_201409)

            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, self.tasks)

        self.assertEqual(mock_method.call_count, 1)
    def test_exception_is_overwritten_by_endpoint(self):
        "The endpoint exception should take precedence"
        app = Flask(__name__)

        def get_tasks(request):
            return self.tasks

        api_201409 = Api(version="v1")
        api_201409.register_endpoint(ApiEndpoint(
            http_method="GET",
            endpoint="/task/",
            handler=get_tasks,
            middleware=[
                FullCustomExceptionMiddleware
            ],
            exceptions=[
                (CustomException, 409),
            ]
        ))
        app.register_blueprint(api_201409)

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

        resp = self.app.get('/v1/task/', content_type='application/json')
        self.assertEqual(resp.status_code, 409)
    def test_process_request_with_multiple_middlewares_order_1(self):
        app = Flask(__name__)

        def get_tasks(request):
            return self.tasks

        api_201409 = Api(version="v1")
        api_201409.register_endpoint(ApiEndpoint(
            http_method="GET",
            endpoint="/task/",
            handler=get_tasks,
            middleware=[
                RedirectDataMiddleware,
                ForbiddenMiddleware
            ]
        ))
        app.register_blueprint(api_201409)

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

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

        self.assertEqual(json.loads(resp.data.decode(resp.charset)), {})
Пример #15
0
    def create_app(self, additional_config=None):
        """Create a new instance of sipa using

        A new instance of sipa will be executed with the following
        config customizations:

            - SECRET_KEY is set to a random value

            - TESTING is set to True

            - debug is enabled

            - WTF_CSRF_ENABLED is set to False

            - PRESERVE_CONTEXT_ON_EXCEPTION

        :param dict additional_config: a dict of additional config
            values taking precedence of what has ben set before.  This
            argument can be used when subclassing by calling ``super()``
            with the desired config.
        """
        test_app = Flask('sipa')
        test_app.config['SECRET_KEY'] = os.urandom(100)
        test_app.config['TESTING'] = True
        test_app.config['LOG_CONFIG'] = WARNINGS_ONLY_CONFIG
        test_app.config['WTF_CSRF_ENABLED'] = False
        test_app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False
        test_app.debug = True
        test_app = create_app(
            app=test_app,
            config=additional_config if additional_config else {},
        )
        return test_app
Пример #16
0
    def create_app(selfself):
        app = Flask(__name__)
        app.config['TESTING'] = True

        # fire up server for testing
        app.config['LIVESERVER_PORT'] = 8943
        return app
Пример #17
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
Пример #18
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['IMAGINE_ADAPTER'] = {
            'name': 'fs',
        }

        app.config['IMAGINE_FILTER_SETS'] = {
            'test_scale_cached': {
                'cached': True,
                'filters': {
                    'thumbnail': {'size': [100, 100], 'mode': 'inset'}
                }
            },
            'test_scale_dynamic': {
                'cached': False,
                'filters': {
                    'thumbnail': {'size': [100, 100], 'mode': 'inset'}
                }
            }
        }
        self.imagine = Imagine(app)
        return app
Пример #19
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())
Пример #20
0
 def create_app(self):
     app = Flask(__name__)
     app.config['TESTING'] = True
     app.config['SECRET_KEY'] = 'secret secret'
     app.config['IMAGES_PATH'] = ['assets']
     self.images = Images(app)
     return app
Пример #21
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()
Пример #22
0
    def setUp(self):
        self.engine = Engine("op1", "op2")
        self.engine.op1.setup(in_name="in", out_name="middle", required=False)
        self.engine.op2.setup(in_name="middle", out_name="out")

        self.engine.op1.set(OptProductEx())
        foisdouze = OptProductEx("foisdouze")
        foisdouze.force_option_value("factor", 12)
        self.engine.op2.set(foisdouze, OptProductEx())

        egn_view = EngineView(self.engine, name="my_egn")
        egn_view.add_input("in", Numeric(vtype=int, min=-5, max=5))
        egn_view.add_input("middle", Numeric(vtype=int))
        print(self.engine.needed_inputs())
        egn_view.add_output("in")
        egn_view.add_output("middle")
        egn_view.add_output("out")

        api = ReliureAPI()
        api.register_view(egn_view)

        app = Flask(__name__)
        app.config['TESTING'] = True
        app.register_blueprint(api, url_prefix="/api")
        self.app = app.test_client()
Пример #23
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
Пример #24
0
 def setUp(self):
     from flask import Flask
     app = Flask(__name__)
     app.config['TESTING'] = True
     self.provider = GreetingProvider()
     provider_for_flask(app, '/', self.provider)
     self.client = app.test_client()
Пример #25
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')
Пример #26
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
Пример #27
0
 def setUp(self):
     """Setup up."""
     app = Flask(__name__)
     app.config['DEBUG'] = True
     app.config['TESTING'] = True
     app.logger.disabled = True
     self.app = app
Пример #28
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
Пример #29
0
 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
Пример #30
0
def app(request):
    app = Flask(__name__)
    app.debug = True
    app.config['SECRET_KEY'] = 'secret'
    app.config['TESTING'] = True
    app.config['BITMAPIST_REDIS_URL'] = 'redis://localhost:6379'
    app.config['SECRET_KEY'] = 'verysecret'
    return app