def test_session_scope(): """Test the session scope object.""" db = DB(connect_url=TEST_URL, web_app=False) db.init() with db.session() as session: session.add(User(user_id='U', name='U', secret='U', active=True)) # Query all users. Expects two objects in the resulting list (te created # user and the default user). with db.session() as session: assert len(session.query(User).all()) == 2 # Error when adding user with duplicate key. with pytest.raises(IntegrityError): with db.session() as session: session.add(User(user_id='U', name='U', secret='U', active=True)) # Query all users. Still expects one object in the resulting list. with db.session() as session: assert len(session.query(User).all()) == 2 # Raise an exception within the session scope. with pytest.raises(ValueError): with db.session() as session: session.add(User(user_id='W', name='W', secret='W', active=True)) raise ValueError('some error') # Query all users. Still expects two object in the resulting list. with db.session() as session: assert len(session.query(User).all()) == 2
def init_db(env: Dict) -> DB: """Create an instance of the database object based on the given configuration settings. Sets the respective variables to the default value if not set. Parameters ---------- env: dict, default=None Dictionary that provides access to configuration parameter values. Returns ------- flowserv.model.database.DB """ # Get the web app flag. Use True as the default if the value is not set. if WEBAPP not in env: env[WEBAPP] = True web_app = env[WEBAPP] # Ensure that the databse connection Url is specified in the configuration. url = env.get(DATABASE) if url is None: # Use a SQLite database in the dabase directory as default. # This database needs to be initialized if it does not exist. dbfile = '{}/flowserv.db'.format(env[config.FLOWSERV_BASEDIR]) url = 'sqlite:///{}'.format(dbfile) env[DATABASE] = url # Maintain a reference to the local database instance for use # when creating API instances. db = DB(connect_url=url, web_app=web_app) if not os.path.isfile(dbfile): # Initialize the database if the database if the configuration # references the default database and the database file does # not exist. db.init() else: # If the database Url is specified in the configuration we create the # database object for that Url. In this case we assume that the referenced # database has been initialized. db = DB(connect_url=env[DATABASE], web_app=web_app) # Return the created database object. return db
def database(): """Create a fresh instance of the database.""" db = DB(connect_url=TEST_URL) db.init() return db
def test_db_webapp(web_app, echo): """Basic tests to ensure that the different parameter options for DB instantiation work without generating errors. """ db = DB(connect_url=TEST_URL, web_app=web_app, echo=echo) db.init()