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
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
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.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.app
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
Beispiel #5
1
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
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)
Beispiel #7
1
def create_app():
    options = {"port": 0, "unitTesting": False}
    WebConfig.config(options)

    b = Borg()
    app = Flask(__name__)
    app.config["DEBUG"] = True
    app.config["SECRET_KEY"] = b.secretKey
    app.config["SECURITY_PASSWORD_HASH"] = b.passwordHash
    app.config["SECURITY_PASSWORD_SALT"] = b.passwordSalt
    app.config["SQLALCHEMY_DATABASE_URI"] = (
        "mysql://" + b.auth_dbUser + ":" + b.auth_dbPasswd + "@" + b.auth_dbHost + "/" + b.auth_dbName
    )
    b.logger.setLevel(b.logLevel)
    b.logger.debug("Error handlers: {0}".format(app.error_handler_spec))
    app.secret_key = os.urandom(24)
    logger = logging.getLogger("werkzeug")
    logger.setLevel(b.logLevel)
    enable_debug = b.logLevel = logging.DEBUG

    cors = CORS(app)
    db.init_app(app)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    from main import main as main_blueprint

    app.register_blueprint(main_blueprint)

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

    return app
def gen_app(config):
    """Generate a fresh app."""
    app = Flask("testapp")
    app.testing = True
    app.config.update(**config)

    FlaskCLI(app)
    FlaskMenu(app)
    Babel(app)
    Mail(app)
    InvenioDB(app)
    InvenioAccounts(app)
    FlaskOAuth(app)
    InvenioOAuthClient(app)

    app.register_blueprint(blueprint_client)
    app.register_blueprint(blueprint_settings)

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

    app.test_request_context().push()

    datastore = app.extensions["invenio-accounts"].datastore

    datastore.create_user(email="existing@invenio-software.org", password="tester", active=True)
    datastore.create_user(email="test2@invenio-software.org", password="tester", active=True)
    datastore.create_user(email="test3@invenio-software.org", password="tester", active=True)
    datastore.commit()

    return app
class MongoManagerTest(TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.app.config.update({"MONGO_HOST": "localhost", "MONGO_DBNAME": "madacra_manager_test", "TESTING": True})
        self.manager = MongoManager()
        self.addCleanup(self._delete_db)

    def _delete_db(self):
        with self.app.app_context():
            self.manager.cx.drop_database(self.app.config["MONGO_DBNAME"])

    def test_manager_collection_manager_class(self):
        """MongoManager.CollectionManager property returns a bound
        collection manager suitable for subclassing"""
        manager = self.manager

        # @manager.bind_collection
        class TestManager(manager.CollectionManager):
            name = "test_collection"

        tm = TestManager()

        manager.init_app(self.app)

        with self.app.app_context():
            tm.collection.insert({u"attr1": u"value1"})
            self.assertEqual(len(list(tm.collection.find())), 1)

    def test_manager_collection_manager_registration(self):
        """MongoManager.bind_collection binds collection manager"""
        manager = self.manager

        @manager.bind_collection
        class TestManager(CollectionManager):
            name = "test_collection"

        tm = TestManager()

        manager.init_app(self.app)

        with self.app.app_context():
            tm.collection.insert({u"attr1": u"value1"})
            self.assertEqual(len(list(tm.collection.find())), 1)

    def test_manager_indices(self):
        """MongoManager.init_app ensures collection indices"""
        manager = self.manager

        class TestManager(manager.CollectionManager):
            name = "test_collection"
            indices = [CollectionIndex("foo"), CollectionIndex("bar")]

        tm = TestManager()

        manager.init_app(self.app)

        with self.app.app_context():
            self.assertEqual(len(manager.db.test_collection.index_information()), 3)
Beispiel #10
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
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)
Beispiel #12
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
Beispiel #13
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()
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()
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)
Beispiel #16
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
class GetUriMethodTestCase(ItemsServiceTestCase):
    """Tests for the _get_uri() helper method."""

    def setUp(self):
        super().setUp()

        self.app = Flask(__name__)
        self.app.config["PUBLICAPI_URL"] = "http://content_api.com"
        self.app.config["URLS"] = {"items": "items_endpoint", "packages": "packages_endpoint"}

        self.app_context = self.app.app_context()
        self.app_context.push()

    def tearDown(self):
        self.app_context.pop()
        super().tearDown()

    def test_generates_correct_uri_for_non_composite_items(self):
        document = {"_id": "foo:bar", "type": "picture"}

        instance = self._make_one(datasource="items")
        result = instance._get_uri(document)

        self.assertEqual(result, "http://content_api.com/items_endpoint/foo%3Abar")

    def test_generates_correct_uri_for_composite_items(self):
        document = {"_id": "foo:bar", "type": "composite"}

        instance = self._make_one(datasource="items")
        result = instance._get_uri(document)

        self.assertEqual(result, "http://content_api.com/packages_endpoint/foo%3Abar")
Beispiel #18
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask(__name__, instance_path=instance_path)
    app.config.update(
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND="memory",
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND="cache",
        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)
    FlaskCeleryExt(app)
    InvenioDB(app)
    InvenioWorkflows(app)
    InvenioOAIHarvester(app)
    INSPIRECrawler(app)

    with app.app_context():
        yield app

    shutil.rmtree(instance_path)
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)

    def teardown():
        with app.app_context():
            db.drop_all()
            current_collections.unregister_signals()

    request.addfinalizer(teardown)

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

    return app
Beispiel #20
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)
    oauth.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()
        from app.models import User

        if app.config["DEBUG"]:
            if not User.query.filter_by(username="admin").first():
                admin = User(password="admin", email="admin@email.com", username="admin", confirmed=True)
                db.session.add(admin)
                db.session.commit()

    return app
    def setUp(self):
        _ENGINES.clear()
        _BASES.clear()
        app = Flask(__name__)
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.sqlite"
        db.init_app(app)
        self.app = app
        with app.app_context():
            db.create_all(app=app)
            self.db = db
            self.user = User(username="user", password="password", database_uri="sqlite:///:memory:")
            db.session.add(self.user)
            try:
                db.session.commit()
            except IntegrityError:
                db.session.rollback()
        self.engine = create_engine("sqlite:///:memory:")
        self.base = declarative_base()

        class Blah(self.base):
            __tablename__ = "blah"
            id = Column(Integer, primary_key=True)

        self.model = Blah
        self.base.metadata.create_all(self.engine)
        _ENGINES["sqlite:///:memory:"] = self.engine
Beispiel #22
0
def create_app(init=False):
    app = Flask(__name__, static_url_path="/elegon/static", template_folder="templates")
    app.config.from_object("elegon.config")
    app.secret_key = "c534d51a57638e8a8a51c36d4a4128b89f8beb22"

    for ext in (db, openid2):
        ext.init_app(app)

    for bp in blueprints:
        import_name = "%s.ui.%s:bp" % (__package__, bp)
        app.register_blueprint(import_string(import_name))

    for fl in (max, min, paginator_kwargs, enumerate):
        app.add_template_global(fl)

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

    @app.before_request
    def init_global_vars():
        user_dict = json.loads(request.cookies.get(app.config["OPENID2_PROFILE_COOKIE_NAME"], "{}"))
        g.user = user_dict and User.get_or_create(user_dict["username"], user_dict["email"]) or None
        g.start = request.args.get("start", type=int, default=0)
        g.limit = request.args.get("limit", type=int, default=20)

    init_logging()

    if init:
        init_scheduler()
        start_scheduler()
        signal.signal(signal.SIGTERM, stop_scheduler)
        signal.signal(signal.SIGHUP, stop_scheduler)

    return app
Beispiel #23
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
def create_schema(uri, pkg_name):
    app = Flask("schema generator")
    app.config["SQLALCHEMY_DATABASE_URI"] = uri
    list(load_all_modules(pkg_name))
    db.init_app(app)
    with app.app_context():
        db.create_all()
Beispiel #25
0
def create_app(config):
    if config is None:
        config = "dev"
    if not os.path.isfile(CONFIG_FILE):
        create_config()
    # Create Flask application
    app = Flask(__name__)
    app.config.from_object(configurations[config])

    # set 404 errors to the not_found function
    app.error_handler_spec[None][404] = not_found

    # Init flask extentinons
    db.init_app(app)
    with app.app_context():
        from models import Setting

        try:
            db_version = Setting.db_version()
            if db_version < Setting.DB_VERSION:
                # TODO: Implement settings db upgrade code
                print " * Upgrading the settings database"
        except:
            pass

    from .api_v1 import api_v1

    app.register_blueprint(api_v1)

    return app
Beispiel #26
0
def app(request):
    """Flask application fixture."""
    app = Flask("testapp")
    app.config.update(
        TESTING=True,
        SQLALCHEMY_DATABASE_URI=os.environ.get("SQLALCHEMY_DATABASE_URI", "sqlite://"),
        CELERY_ALWAYS_EAGER=True,
        CELERY_RESULT_BACKEND="cache",
        CELERY_CACHE_BACKEND="memory",
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        RECORDS_UI_DEFAULT_PERMISSION_FACTORY=None,  # No permission checking
    )
    FlaskCeleryExt(app)
    FlaskCLI(app)
    Babel(app)
    InvenioDB(app)
    InvenioPIDStore(app)
    InvenioRecords(app)

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

    def finalize():
        with app.app_context():
            db.drop_all()

    request.addfinalizer(finalize)
    return app
Beispiel #27
0
    def test_parse_foo_operators_four_hunderd(self):
        app = Flask(__name__)
        with app.app_context():
            parser = RequestParser()
            parser.add_argument("foo", type=int),

            self.assertRaises(exceptions.BadRequest, lambda: parser.parse_args(Request.from_values("/bubble?foo=bar")))
def test_contributors():
    """Test contributors."""
    app = Flask(__name__)
    app.config.update(dict(DEPOSIT_CONTRIBUTOR_DATACITE2MARC=dict(Other="...", DataCurator="...")))
    s = legacyjson.LegacyMetadataSchemaV1(strict=True)
    with app.app_context():
        assert s.load(
            d(
                **{
                    "contributors": [
                        dict(
                            name="Doe, John",
                            affiliation="Atlantis",
                            orcid="0000-0002-1825-0097",
                            gnd="170118215",
                            type="DataCurator",
                        ),
                        dict(name="Smith, Jane", affiliation="Atlantis", type="Other"),
                    ]
                }
            )
        ).data["contributors"] == [
            dict(
                name="Doe, John",
                affiliation="Atlantis",
                orcid="0000-0002-1825-0097",
                gnd="170118215",
                type="DataCurator",
            ),
            dict(name="Smith, Jane", affiliation="Atlantis", type="Other"),
        ]
Beispiel #29
0
def create_app():
    app = Flask(__name__)
    from . import config

    app.config.from_object(config)

    DecentWeb(app)

    from . import models

    from . import auth

    auth.init(app)

    from . import admin

    with app.app_context():
        g.identity = AnonymousIdentity()
        admin.init_app(app)

    Mail(app)

    DebugToolbarExtension(app)

    return app
Beispiel #30
0
def app(request):
    """Flask application fixture."""
    app = Flask("testapp")
    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():
        db.create_all()

    def teardown():
        with app.app_context():
            db.drop_all()

    request.addfinalizer(teardown)
    return app