class BaseTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.engine = create_engine(sqlalchemy_url) Base.metadata.create_all(cls.engine) def setUp(self): self.session = DBSession() transaction.begin() def tearDown(self): # for unit testing, we throw away any modifications we may have made. transaction.abort() self.session.close() def add_objs_and_assert_ids(self, objs): if type(objs) is list: for o in objs: self.session.add(o) self.session.flush() for o in objs: assert o.id is not None else: self.session.add(objs) self.session.flush() assert objs.id is not None
def get_oil(oil_name): """ function returns the Oil object given the name of the oil as a string. :param oil_: name of the oil that spilled. If it is one of the names stored in _sample_oil dict, then an Oil object with specified API is returned. Otherwise, query the database for the oil_name and return the associated Oil object. :type oil_: str It should be updated to take **kwargs so if user wants to define a new oil with specific properties, they can do so by defining properties in kwargs. NOTE I: ------- One issue is that the kwargs in Oil contain spaces, like 'Oil Name'. This can be handled if the user defines a dict as follows: kw = {'Oil Name': 'new oil', 'Field Name': 'field name'} get_oil(**kw) however, the following will not work: get_oil('Oil Name'='new oil', 'Field Name'='field name') This is another reason, we need an interface (business logic) between the SQL object and the end user. NOTE II: -------- currently, the _sample_oils contained in dict in this module are not part of the database. May want to add them to the final persistent database to make a consistent interface which always accesses DB for any 'oil_name' """ if oil_name in _sample_oils.keys(): return Oil(**_sample_oils[oil_name]) else: if not os.path.exists(_db_file): """ if db_file doesn't exist in webgnome, then download it from remote_data.data_server and put it in py_gnome/gnome/data/ """ # _db_from_flatfile() get_datafile(_db_file) # not sure we want to do it this way - but let's use for now engine = sqlalchemy.create_engine("sqlite:///" + _db_file) # let's use global DBSession defined in oillibrary # alternatively, we could define a new scoped_session # Not sure what's the proper way yet but this needs # to be revisited at some point. # session_factory = sessionmaker(bind=engine) # DBSession = scoped_session(session_factory) DBSession.bind = engine try: return DBSession.query(Oil).filter(Oil.name == oil_name).one() except sqlalchemy.orm.exc.NoResultFound, ex: # or sqlalchemy.orm.exc.MultipleResultsFound as ex: ex.message = "oil with name '{0}' not found in database. " "{1}".format(oil_name, ex.message) ex.args = (ex.message,) raise ex
def setUp(self): self.session = DBSession() transaction.begin()