def app(request):
    """Flask application fixture."""
    app = Flask('testapp')
    app.config.update(
        TESTING=True,
        SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI',
                                          'sqlite://'),
        SERVER_NAME='localhost',
    )
    Babel(app)
    Menu(app)
    Breadcrumbs(app)
    InvenioDB(app)
    InvenioCollections(app)
    InvenioRecords(app)

    app.register_blueprint(blueprint)

    with app.app_context():
        if str(db.engine.url) != 'sqlite://' and \
                not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    def teardown():
        with app.app_context():
            if str(db.engine.url) != 'sqlite://':
                drop_database(str(db.engine.url))

    request.addfinalizer(teardown)

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

    return app
def base_app():
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    base_app = Flask(__name__, instance_path=instance_path)

    base_app.config.update(
        ACCOUNTS_USE_CELERY=False,
        LOGIN_DISABLED=False,
        SECRET_KEY='testing_key',
        SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI',
                                          'sqlite://'),
        TEST_USER_EMAIL='test_user@example.com',
        TEST_USER_PASSWORD='test_password',
        TESTING=True,
        WTF_CSRF_ENABLED=False,
    )
    Babel(base_app)
    Mail(base_app)
    Menu(base_app)
    InvenioDB(base_app)
    InvenioAccounts(base_app)
    base_app.register_blueprint(accounts_blueprint)

    with base_app.app_context():
        if str(db.engine.url) != "sqlite://" and \
                not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    yield base_app

    with base_app.app_context():
        drop_database(str(db.engine.url))
    shutil.rmtree(instance_path)
class ModelizeTest(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.app.config.from_object(flask_stub_config)
        self.mongo = PyMongo(self.app)
        self.modelize = Modelize(self.mongo)

        class TestBaseModel(self.modelize.Model):
            __collection_name__ = 'test1'
            __fields__ = ['base_1', 'base_2']

        class TestModel1(TestBaseModel):
            __collection_name__ = 'test1'
            __type_identifier__ = {'type': 'いち'}
            __fields__ = ['name', 'age']

        class TestModel2(TestBaseModel):
            __collection_name__ = 'test1'
            __type_identifier__ = {'type': 'に'}
            __fields__ = ['color', 'shape']

        self.TestModel1 = TestModel1
        self.TestModel2 = TestModel2

        with self.app.app_context():
            self.mongo.db.test1.drop()

            model11 = TestModel1(name='完犊子', age=250)
            model12 = TestModel1(name='狗史', age=None)
            model21 = TestModel2(color='红', shape='S形')
            model22 = TestModel2(color='黄', shape='B形')
            TestModel1.query.insert(model11)
            TestModel1.query.insert(model12)
            TestModel2.query.insert(model21)
            TestModel2.query.insert(model22)

    def test_modelize_find_and_find_one(self):
        with self.app.app_context():
            new_model11 = self.TestModel1.query.find_one({'age': 250})
            self.assertIsNotNone(new_model11)
            self.assertIsInstance(new_model11, self.TestModel1)
            self.assertIsNone(new_model11.base_1)
            self.assertEqual(new_model11.name, '完犊子')
            none_model20 = self.TestModel2.query.find_one({'age': 250})
            self.assertIsNone(none_model20)
            models_with_ages = self.TestModel1.query.find({'age': {'$ne': None}})
            self.assertEqual(len(models_with_ages), 1)

    def test_modelize_update(self):
        # TODO: This is crappy. We should use change tracker or something, and
        # the user should be able to simple run update() to flush all changes.

        with self.app.app_context():
            model11 = self.TestModel1.query.find_one({'name': '狗史'})
            self.TestModel1.query.update(model11, {'$set': {'age': 500}})
            model11 = self.TestModel1.query.find_one({'name': '狗史'})
            self.assertEqual(model11.age, 500)

    def tearDown(self):
        pass
Example #4
0
class TestFlaskWhooshWriter(unittest.TestCase):
    def setUp(self):
        self.root_dir = tempfile.mkdtemp()
        schema = Schema(path=ID(stored=True), content=TEXT)
        self.index = create_in(self.root_dir, schema=schema)

        self.app = Flask(__name__)
        self.whoosh = Whoosh()
        self.whoosh.init_app(self.app)
        self.app.config['WHOOSH_INDEX_ROOT'] = self.root_dir

    def test_writer_is_usable(self):
        with self.app.app_context():
            writer = self.whoosh.writer
            writer.add_document(path=u'/blah/hello', content=u'this is awesome content')
            writer.commit()
            qp = QueryParser("content", schema=self.index.schema)
            q = qp.parse(u"awesome")
            with self.index.searcher() as s:
                results = s.search(q)
                self.assertEquals(1, len(results))
                self.assertEquals('/blah/hello', results[0]['path'])

    def test_same_writer_returned_in_multiple_calls(self):
        with self.app.app_context():
            writer1 = self.whoosh.writer
            writer2 = self.whoosh.writer
            self.assertEquals(writer1, writer2)
            
    def tearDown(self):
        assert self.root_dir != '/tmp/' and self.root_dir.startswith('/tmp/')
        shutil.rmtree(self.root_dir)
Example #5
0
def get_app(
        database_uri,
        exclude_tables=None,
        user_models=None,
        reflect_all=True,
        read_only=False):
    """Return an application instance connected to the database described in
    *database_uri*.

    :param str database_uri: The URI connection string for the database
    :param list exclude_tables: A list of tables to exclude from the API
                                service
    :param list user_models: A list of user-defined models to include in the
                             API service
    :param bool reflect_all: Include all database tables in the API service
    :param bool read_only: Only allow HTTP GET commands for all endpoints
    """
    app = Flask('sandman2')
    app.config['SQLALCHEMY_DATABASE_URI'] = database_uri
    app.config['SANDMAN2_READ_ONLY'] = read_only
    db.init_app(app)
    admin = Admin(app, base_template='layout.html', template_mode='bootstrap3')
    _register_error_handlers(app)
    if user_models:
        with app.app_context():
            _register_user_models(user_models, admin)
    elif reflect_all:
        with app.app_context():
            _reflect_all(exclude_tables, admin, read_only)
    return app
Example #6
0
class TestSession:

    def setup(self):
        utils.unload_modules('alchemist')
        self.app = Flask('alchemist')

    def test_unbound(self):
        from alchemist import db

        assert not db.session

    def test_acquire_no_database(self):
        from alchemist import db, exceptions

        with raises(exceptions.ImproperlyConfigured), self.app.app_context():
            assert db.session

    def test_acquire_default(self):
        from alchemist import db

        config = {'default': 'sqlite:///:memory:'}
        with settings(self.app, DATABASES=config), self.app.app_context():
            assert db.session

    def test_repr(self):
        from alchemist import db

        config = {'default': 'sqlite:///:memory:'}
        with settings(self.app, DATABASES=config), self.app.app_context():
            text = '<Session(bind=%r)>' % db.engine['default']
            assert repr(db.session) == text
def test_client_reference():
    """Test client reference."""
    client1 = {'name': 'client1'}
    client2 = {'name': 'client2'}

    app1 = Flask('testapp1')
    FlaskCLI(app1)
    app2 = Flask('testapp2')
    FlaskCLI(app2)

    ext = InvenioSearch()
    assert 'invenio-search' not in app1.extensions
    assert 'invenio-search' not in app2.extensions

    ext.init_app(app1, elasticsearch=client1)
    assert 'invenio-search' in app1.extensions

    ext.init_app(app2, elasticsearch=client2)
    assert 'invenio-search' in app2.extensions

    with app1.app_context():
        assert current_search_client == client1

    with app2.app_context():
        assert current_search_client == client2
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    FlaskCLI(app)
    app.url_map.converters['pid'] = PIDConverter
    ext = InvenioDeposit(app)
    assert 'invenio-deposit' in app.extensions

    app = Flask('testapp')
    FlaskCLI(app)
    app.url_map.converters['pid'] = PIDConverter

    # check that current_deposit cannot be resolved
    with app.app_context():
        with pytest.raises(KeyError):
            current_deposit.init_app

    ext = InvenioDeposit()
    assert 'invenio-deposit' not in app.extensions
    ext.init_app(app)
    assert 'invenio-deposit' in app.extensions

    # check that current_deposit resolves correctly
    with app.app_context():
        current_deposit.init_app
Example #9
0
class ZmqWorkflowResultsReceiver(object):
    def __init__(self, message_converter=ProtobufWorkflowResultsConverter, current_app=None):
        """Initialize a Receiver object, which will receive callbacks from the ExecutionElements.

        Args:
            current_app (Flask.App, optional): The current Flask app. If the Receiver is not started separately,
                then the current_app must be included in the init. Otherwise, it should not be included.
            message_converter (WorkflowResultsConverter): Class to convert workflow results
        """
        import walkoff.server.workflowresults  # Need this import

        ctx = zmq.Context.instance()
        self.message_converter = message_converter
        self.thread_exit = False
        self.workflows_executed = 0

        self.results_sock = ctx.socket(zmq.PULL)
        self.results_sock.curve_secretkey = walkoff.config.Config.SERVER_PRIVATE_KEY
        self.results_sock.curve_publickey = walkoff.config.Config.SERVER_PUBLIC_KEY
        self.results_sock.curve_server = True
        self.results_sock.bind(walkoff.config.Config.ZMQ_RESULTS_ADDRESS)

        if current_app is None:
            self.current_app = Flask(__name__)
            self.current_app.config.from_object(walkoff.config.Config)
            self.current_app.running_context = context.Context(init_all=False)
        else:
            self.current_app = current_app

    def receive_results(self):
        """Keep receiving results from execution elements over a ZMQ socket, and trigger the callbacks"""
        while True:
            if self.thread_exit:
                break
            try:
                message_bytes = self.results_sock.recv(zmq.NOBLOCK)
            except zmq.ZMQError:
                gevent.sleep(0.1)
                continue

            with self.current_app.app_context():
                self._send_callback(message_bytes)

        self.results_sock.close()
        return

    def _send_callback(self, message_bytes):
        event, sender, data = self.message_converter.to_event_callback(message_bytes)

        if sender is not None and event is not None:
            if self.current_app:
                with self.current_app.app_context():
                    event.send(sender, data=data)
            else:
                event.send(sender, data=data)
            if event in [WalkoffEvent.WorkflowShutdown, WalkoffEvent.WorkflowAborted]:
                self._increment_execution_count()

    def _increment_execution_count(self):
        self.workflows_executed += 1
Example #10
0
def get_app(
        database_uri,
        exclude_tables=None,
        user_models=None,
        reflect_all=True):
    """Return an application instance connected to the database described in
    *database_uri*.

    :param str database_uri: The URI connection string for the database
    :param list exclude_tables: A list of tables to exclude from the API
                                service
    :param list user_models: A list of user-defined models to include in the
                             API service
    :param bool reflect_all: Include all database tables in the API service
    """
    app = Flask('sandman2')
    app.config['SQLALCHEMY_DATABASE_URI'] = database_uri
    db.init_app(app)
    admin = Admin(app, base_template='layout.html')
    _register_error_handlers(app)
    if user_models:
        with app.app_context():
            _register_user_models(user_models, admin)
    elif reflect_all:
        with app.app_context():
            _reflect_all(exclude_tables, admin)
    return app
Example #11
0
def create_app(script_info=None):
    """Create app."""
    app = Flask(__name__)
    # logging
    if not os.path.exists(user_data_dir):
        os.makedirs(user_data_dir)
    log_dir = os.path.join(user_data_dir, 'log')
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    peewee_logger = logging.getLogger('peewee')
    peewee_logger.setLevel(logging.INFO)
    chardet_logger = logging.getLogger('chardet')
    chardet_logger.setLevel(logging.INFO)
    default_log_file = os.path.join(log_dir, 'iqdb_tagger_server.log')
    file_handler = TimedRotatingFileHandler(default_log_file, 'midnight')
    file_handler.setLevel(logging.WARNING)
    file_handler.setFormatter(logging.Formatter('<%(asctime)s> <%(levelname)s> %(message)s'))
    app.logger.addHandler(file_handler)
    app.logger.addHandler(peewee_logger)
    app.logger.addHandler(chardet_logger)
    # reloader
    reloader = app.config['TEMPLATES_AUTO_RELOAD'] = \
        bool(os.getenv('IQDB_TAGGER_RELOADER')) or app.config['TEMPLATES_AUTO_RELOAD']  # NOQA
    if reloader:
        app.jinja_env.auto_reload = True
    app.config['SECRET_KEY'] = os.getenv('IQDB_TAGGER_SECRET_KEY') or os.urandom(24)
    app.config['WTF_CSRF_ENABLED'] = False
    # debug
    debug = app.config['DEBUG'] = bool(os.getenv('IQDB_TAGGER_DEBUG')) or app.config['DEBUG']
    if debug:
        app.config['DEBUG'] = True
        app.config['LOGGER_HANDLER_POLICY'] = 'debug'
        logging.basicConfig(level=logging.DEBUG)
        pprint.pprint(app.config)
        print('Log file: {}'.format(default_log_file))
        print('script info:{}'.format(script_info))
    db_path = os.getenv('IQDB_TAGGER_DB_PATH') or default_db_path
    init_program()
    init_db(db_path)
    # app and db
    app.app_context().push()

    @app.shell_context_processor
    def shell_context():  # pylint: disable=unused-variable
        return {'app': app}

    # flask-admin
    app_admin = Admin(
        app, name='IQDB Tagger', template_mode='bootstrap3',
        index_view=views.HomeView(name='Home', template='iqdb_tagger/index.html', url='/'))

    app_admin.add_view(views.MatchView())
    # app_admin.add_view(ModelView(ImageMatch, category='DB'))
    # app_admin.add_view(ModelView(ImageMatchRelationship, category='DB'))
    # app_admin.add_view(ModelView(ImageModel, category='DB'))
    # app_admin.add_view(ModelView(MatchTagRelationship, category='DB'))
    # routing
    app.add_url_rule('/thumb/<path:basename>', view_func=thumb)
    return app
Example #12
0
def create_app():
	app = Flask(__name__)
	app.config.from_object('config')
	db.init_app(app)
	app.app_context().push()
	db.Model.metadata.reflect(db.engine)
	api = Api(app)
	return app
Example #13
0
def create_test_app(db_file):
  app = Flask(__name__)
  app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + db_file
  app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

  trips_models.db.init_app(app)
  app.app_context().push()

  return app
Example #14
0
class TestTorrents(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
        self.app.config['USER_LIST'] = ['Test Admin']
        db.init_app(self.app)
        d = TempDirectory()
        d.makedir('dataset')
        d.write('dataset/files/testfile.jpg', 'abc')
        d.write('dataset/testfile2.jpg', 'abc')
        self.directory = d
        self.app.config['DATASET_ROOT'] = d.path
        with self.app.app_context(), TempDirectory() as d:
            db.create_all()
            lib.models.buildDB()
            dataset = lib.models.Datasets()
            dataset.name = 'Test'
            dataset.path = "dataset"
            db.session.add(dataset)
            db.session.commit()

    def test_add_torrent_to_model(self):
        with self.app.app_context():
            dataset = lib.models.Datasets.query.first()
            mk = makeTorrent(announce='http://kb.se')
            mk.multi_file('{}/{}'.format(dataset.path, 'dataset'))
            torrent_model = lib.models.Torrent()
            torrent_model.datasetID = dataset.datasetID
            db.session.add(torrent_model)
            torrent_model = lib.torrents._add_torrent_to_model(
                torrent_model, mk
            )
            db.session.commit()
            self.assertEqual(mk.info_hash(), torrent_model.infoHash)
            self.assertEqual(torrent_model.datasetID, 1)
            self.assertEqual(torrent_model.torrentData, mk.getBencoded())
            self.assertIsNotNone(torrent_model.updated_at)

    def test_add_torrent_method_without_announce(self):
        with self.app.app_context():
            torrent_model = lib.models.Torrent()
            exceptText = "ANNOUNCE is required to create torrents"
            with self.assertRaisesRegexp(KeyError, exceptText):
                lib.torrents.add_torrent(torrent_model, 1)

    def test_add_torrent_method(self):
        with self.app.app_context():
            self.app.config['ANNOUNCE'] = 'http://kb.se'
            torrent_model = lib.models.Torrent()
            torrent_model = lib.torrents.add_torrent(torrent_model, 1)
            self.assertEqual(
                torrent_model.infoHash,
                'cf3010468fd2c2f048d2fd3162bcdcc937fcb06f'
            )

    def tearDown(self):
        self.directory.cleanup()
Example #15
0
    def test_login(self):
        user = 'testuser'
        passwd = 'supersecret'
        badpass = 'short'
        email = 'jim@test.com'
        request = dict(
            UserName=user,
            Email=email,
            Password=passwd
        )
        request_bad = dict(
            UserName=user,
            Email=email,
            Password=badpass
        )
        login = dict(
            loginUsername=user,
            loginPassword=passwd
        )
        bad_login = dict(
            loginUsername=user,
            loginPassword='badguess'
        )

        db = psycopg2.connect(
            database=wps.app.config['DATABASE'],
            user="postgres"
        )
        query = "delete from users"
        with db.cursor() as cur:
            cur.execute(query)
        db.commit()

        app = Flask(__name__)
        with app.app_context():
            g.db = psycopg2.connect(
                database=wps.app.config['DATABASE'],
                user="postgres"
            )
            rv = siteutils.addnewuser(request_bad)
            assert 'Registration error' in rv
            rv = siteutils.addnewuser(request)
            assert 'Registration completed' in rv
            rv = siteutils.addnewuser(request)
            assert 'You have already registered with this email' in rv

        #not sure why needs to do this twice but database fail otherwise
        with app.app_context():
            g.db = psycopg2.connect(
                database=wps.app.config['DATABASE'],
                user="postgres"
            )
            rv = siteutils.userauth(login)
            assert '"success": true' in rv
            rv = siteutils.userauth(bad_login)
            assert '{"success": false}' in rv
def app():
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND='memory',
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND='cache',
        JSONSCHEMAS_HOST='inveniosoftware.org',
        TESTING=True,
        SECRET_KEY='CHANGE_ME',
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite://'),
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        SERVER_NAME='app',
        OAISERVER_RECORD_INDEX='_all',
        # Disable set signals because the celery tasks cannot be run
        # synchronously
        OAISERVER_REGISTER_SET_SIGNALS=False,
        SEARCH_ELASTIC_KEYWORD_MAPPING={None: ['_all']},
    )
    if not hasattr(app, 'cli'):
        from flask_cli import FlaskCLI
        FlaskCLI(app)
    InvenioDB(app)
    FlaskCeleryExt(app)
    InvenioJSONSchemas(app)
    InvenioRecords(app)
    InvenioPIDStore(app)
    InvenioMARC21(app)
    client = Elasticsearch(hosts=[os.environ.get('ES_HOST', 'localhost')])
    search = InvenioSearch(app, client=client)
    search.register_mappings('records', 'data')
    InvenioIndexer(app)
    InvenioOAIServer(app)

    app.register_blueprint(blueprint)

    with app.app_context():
        if str(db.engine.url) != 'sqlite://' and \
           not database_exists(str(db.engine.url)):
                create_database(str(db.engine.url))
        db.create_all()
        list(search.create(ignore=[400]))
        sleep(5)

    with app.app_context():
        yield app

    with app.app_context():
        db.session.close()
        if str(db.engine.url) != 'sqlite://':
            drop_database(str(db.engine.url))
        list(search.delete(ignore=[404]))
    shutil.rmtree(instance_path)
Example #17
0
class TestFlaskGitFetches(unittest.TestCase):
    """Flask git extension - fetch commit"""
    def setUp(self):
        self.temprepo = setup_repo()
        self.app = Flask(__name__)
        self.app.config['GIT_REPOPATH'] = self.temprepo.root_dir            

    def test_fetches_all_commits(self):
        git = Git()
        git.init_app(self.app)
        with self.app.app_context():
            commits = git.commits()
            self.assertEquals(3, len(list(commits)))

    def test_fetches_all_commits_for_file_in_regular_order(self):
        git = Git()
        git.init_app(self.app)
        with self.app.app_context():
            commits = list(git.commits_for_path_recent_first('content/hello.md'))
            self.assertEquals(2, len(commits))
            self.assertEquals('second commit', commits[0].message)
            self.assertEquals('first commit', commits[1].message)

            commits = list(git.commits_for_path_recent_first('content/bar.md'))
            self.assertEquals(1, len(commits))

    def test_fetches_all_commits_for_file_in_reverse_order(self):
        git = Git()
        git.init_app(self.app)
        with self.app.app_context():
            commits = list(git.commits_for_path_recent_last('content/hello.md'))
            self.assertEquals(2, len(commits))
            self.assertEquals('first commit', commits[0].message)
            self.assertEquals('second commit', commits[1].message)

            commits = git.commits_for_path_recent_last('content/bar.md')
            self.assertEquals(1, len(list(commits)))
 
    def test_follows_renames(self):
        git = Git()
        git.init_app(self.app)

        # move bar.md to bar2.md
        self.temprepo.delete_contents('content/bar.md')
        self.temprepo.copy_contents('content/bar2.md', medium_sized_content())
        self.temprepo.commit('fourth commit', 400)

        with self.app.app_context():
            commits = list(git.commits_for_path_recent_first('content/bar2.md', follow=True))
            self.assertEquals(2, len(commits))
            self.assertEquals('fourth commit', commits[0].message)
            self.assertEquals('third commit', commits[1].message)

    def tearDown(self):
        self.temprepo.delete()
Example #18
0
class KafkaWorkflowResultsReceiver(object):
    _requires = ['confluent-kafka']

    def __init__(self, message_converter=ProtobufWorkflowResultsConverter, current_app=None):
        import walkoff.server.workflowresults  # Need this import

        self.thread_exit = False

        kafka_config = walkoff.config.Config.WORKFLOW_RESULTS_KAFKA_CONFIG
        self.receiver = Consumer(kafka_config)
        self.topic = walkoff.config.Config.WORKFLOW_RESULTS_KAFKA_TOPIC
        self.message_converter = message_converter
        self.workflows_executed = 0

        if current_app is None:
            self.current_app = Flask(__name__)
            self.current_app.config.from_object(walkoff.config.Config)
            self.current_app.running_context = context.Context(init_all=False)
        else:
            self.current_app = current_app

    def receive_results(self):
        """Constantly receives data from the Kafka Consumer and handles it accordingly"""
        logger.info('Starting Kafka workflow results receiver')
        self.receiver.subscribe(['{}.*'.format(self.topic)])
        while not self.thread_exit:
            raw_message = self.receiver.poll(1.0)
            if raw_message is None:
                gevent.sleep(0.1)
                continue
            if raw_message.error():
                if raw_message.error().code() == KafkaError._PARTITION_EOF:
                    gevent.sleep(0.1)
                    continue
                else:
                    logger.error('Received an error in Kafka receiver: {}'.format(raw_message.error()))
                    gevent.sleep(0.1)
                    continue
            with self.current_app.app_context():
                self._send_callback(raw_message.value())
        self.receiver.close()
        return

    def _send_callback(self, message_bytes):
        event, sender, data = self.message_converter.to_event_callback(message_bytes)

        if sender is not None and event is not None:
            with self.current_app.app_context():
                event.send(sender, data=data)
            if event in [WalkoffEvent.WorkflowShutdown, WalkoffEvent.WorkflowAborted]:
                self._increment_execution_count()

    def _increment_execution_count(self):
        self.workflows_executed += 1
Example #19
0
def create_json_app(config):
    app = Flask(__name__)
    CORS(app)
    app.config.from_object(config)
    for code in default_exceptions.iterkeys():
        app.error_handler_spec[None][code] = make_json_error
    db.init_app(app)
    with app.app_context():
        db.create_all()
    app.app_context().push()
    return app
Example #20
0
class DynamoTest(TestCase):
    """Test our Dynamo extension."""

    def setUp(self):
        """
        Set up a simple Flask app for testing.

        This will be used throughout our tests.
        """
        self.prefix = uuid4().hex

        self.app = Flask(__name__)
        self.app.config['DEBUG'] = True
        self.app.config['DYNAMO_TABLES'] = [
            Table('%s-phones' % self.prefix, schema=[HashKey('number')]),
            Table('%s-users' % self.prefix, schema=[HashKey('username')]),
        ]

        self.dynamo = Dynamo(self.app)

        with self.app.app_context():
            self.dynamo.create_all()
            sleep(60)

    def test_settings(self):
        self.assertEqual(len(self.app.config['DYNAMO_TABLES']), 2)
        self.assertEqual(self.app.config['AWS_ACCESS_KEY_ID'], environ.get('AWS_ACCESS_KEY_ID'))
        self.assertEqual(self.app.config['AWS_SECRET_ACCESS_KEY'], environ.get('AWS_SECRET_ACCESS_KEY'))
        self.assertEqual(self.app.config['AWS_REGION'], environ.get('AWS_REGION') or self.dynamo.DEFAULT_REGION)

    def test_connection(self):
        with self.app.app_context():
            self.assertIsInstance(self.dynamo.connection, DynamoDBConnection)

    def test_tables(self):
        with self.app.app_context():
            self.assertEqual(len(self.dynamo.tables.keys()), 2)

            for table_name, table in self.dynamo.tables.iteritems():
                self.assertIsInstance(table, Table)
                self.assertEqual(table.table_name, table_name)

    def test_table_access(self):
        with self.app.app_context():
            for table_name, table in self.dynamo.tables.iteritems():
                self.assertEqual(getattr(self.dynamo, table_name), table)

    def tearDown(self):
        """Destroy all provisioned resources."""
        with self.app.app_context():
            self.dynamo.destroy_all()
            sleep(60)
Example #21
0
def create_app(config_obj, no_sql=False):
	"""Flask application factory. Initializes and returns the Flask application.

	Blueprints are registered in here.

	Modeled after: http://flask.pocoo.org/docs/patterns/appfactories/

	Positional arguments:
	config_obj -- configuration object to load into app.config.

	Keyword arguments:
	no_sql -- does not run init_app() for the SQLAlchemy instance. For Celery compatibility.

	Returns:
	The initialized Flask application.
	"""
	# Initialize app. Flatten config_obj to dictionary (resolve properties).
	app = Flask(__name__, template_folder=TEMPLATE_FOLDER, static_folder=STATIC_FOLDER)
	config_dict = dict([(k, getattr(config_obj, k)) for k in dir(config_obj) if not k.startswith('_')])
	app.config.update(config_dict)

	# Import DB models. Flask-SQLAlchemy doesn't do this automatically like Celery does.
	with app.app_context():
		for module in app.config.get('DB_MODELS_IMPORTS', list()):
			import_module(module)		

	# Setup redirects and register blueprints.
	app.add_url_rule('/favicon.ico', 'favicon', lambda: app.send_static_file('favicon.ico'))
	for bp in all_blueprints:
		import_module(bp.import_name)
		app.register_blueprint(bp)

	# Initialize extensions/add-ons/plugins.
	if not no_sql:
		db.init_app(app)		
	Statics(app)  # Enable Flask-Statics-Helper features.
	redis.init_app(app)
	celery.init_app(app)
	mail.init_app(app)
	login_manager.init_app(app)
	with app.app_context():
		storage = SQLAStorage(db=db,document=Document)
		blogging_engine.init_app(app, storage)

    # Activate middleware.
	locale.setlocale(locale.LC_ALL, 'eng_US')  # For filters inside the middleware file.
	with app.app_context():
		import_module('reco.middleware')

	# Return the application instance.
	return app
def test_werkzeug_debugger():
    from flask import Flask
    app = Flask(__name__)

    with app.app_context():
        werkzeug_debugger.werkzeug_debugger()

    app.debug = True

    with app.app_context():
        with pytest.raises(AssertionError) as excinfo:
            werkzeug_debugger.werkzeug_debugger()

    assert 'werkzeug_debugger()' == str(excinfo.value)
Example #23
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('config')

    register_extensions(app)
    register_blueprints(app)
    register_commands(app)
    register_errorhandlers(app)

    # See http://flask.pocoo.org/docs/0.12/appcontext/#creating-an-application-context
    # and http://flask-sqlalchemy.pocoo.org/2.3/contexts/
    app.app_context().push()

    return app
Example #24
0
def main(argv):
    from flask import Flask
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../database.db'
    db.init_app(app)
    if(len(argv) > 0 and argv[0] == 'd'):
        with app.app_context():
            db.drop_all()
    else:
        with app.app_context():
            db.create_all()
            test_user = User(login="test", password=generate_password_hash("test"))
            db.session.add(test_user)
            db.session.commit()
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    ext = InvenioCollections(app)
    assert 'invenio-collections' in app.extensions
    with app.app_context():
        current_collections.unregister_signals()

    app = Flask('testapp')
    ext = InvenioCollections()
    assert 'invenio-collections' not in app.extensions
    ext.init_app(app)
    assert 'invenio-collections' in app.extensions
    with app.app_context():
        current_collections.unregister_signals()
Example #26
0
class TestShell(CommandTest):

    patch = 'flask.ext.script.Shell.run'

    def test_run(self):
        target = self._run(['shell'])
        target.assert_called()

    def test_context(self):
        utils.unload_modules('alchemist')

        from alchemist.commands import Shell
        shell = Shell()

        self.app = Flask('alchemist.tests.a')
        self.context = self.app.app_context()
        with self.context:

            alchemist.configure(self.app)

            context = shell.make_context()

            assert 'db' in context
            assert 'session' in context
            assert 'Entity' in context

    def test_pipe(self):
        utils.unload_modules('alchemist')

        self.app = Flask('alchemist.tests.a')
        self.context = self.app.app_context()

        with self.context:
            alchemist.configure(self.app)

            stdin = sys.stdin
            sys.stdin = io.StringIO('print(Entity)\nprint(session)')

            capture = py.io.StdCapture(out=True, in_=False)
            self._run(['shell', '--pipe'])
            out, err = capture.done()

            text = ("<class 'alchemist.tests.a.models.Entity'>\n"
                    "<Session(bind=Engine(sqlite:///:memory:))>\n")

            assert text == out.read()

            sys.stdin = stdin
Example #27
0
def script_info(request):
    """Get ScriptInfo object for testing CLI."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        ACCOUNTS_USE_CELERY=False,
        SECRET_KEY="CHANGE_ME",
        SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO",
        SQLALCHEMY_DATABASE_URI=os.environ.get(
            'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'),
        TESTING=True,
    )
    FlaskCLI(app)
    Babel(app)
    Mail(app)
    InvenioDB(app)
    InvenioAccounts(app)

    with app.app_context():
        if not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.drop_all()
        db.create_all()

    def teardown():
        with app.app_context():
            drop_database(str(db.engine.url))
        shutil.rmtree(instance_path)

    request.addfinalizer(teardown)
    return ScriptInfo(create_app=lambda info: app)
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app_ = Flask(__name__, instance_path=instance_path)
    app_.config.update(
        FILES_REST_PERMISSION_FACTORY=lambda *a, **kw: type(
            'Allow', (object, ), {'can': lambda self: True}
        )(),
        SECRET_KEY='CHANGE_ME',
        SQLALCHEMY_DATABASE_URI=os.environ.get(
            'SQLALCHEMY_DATABASE_URI', 'sqlite://'),
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        TESTING=True,
    )
    app_.register_blueprint(files_rest_blueprint)
    InvenioDB(app_)
    InvenioRecords(app_)
    InvenioFilesREST(app_)
    InvenioIndexer(app_)
    search = InvenioSearch(app_)
    search.register_mappings('records-files', 'data')

    with app_.app_context():
        yield app_

    shutil.rmtree(instance_path)
Example #29
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .api_v1 import api as api_v1_blueprint
    app.register_blueprint(api_v1_blueprint, url_prefix='/api/v1')

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

    return app
Example #30
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_pyfile(config)

    CORS(
        app,
        origins=[
            'http://127.0.0.1:5994',
            'http://living-with-django.astex.io'
        ],
        supports_credentials=True
    )

    from blog.lib.database import db
    db.init_app(app)

    from blog import views
    views.register(app)

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

    from blog.lib.session import SessionInterface
    app.session_interface = SessionInterface()

    return app