def test__create_entity(self): self.pony.define_all_models() self.pony.binddb(create_tables=True) with orm.db_session: alcolea_ns = self.samplePlantNS() alcolea = self.pony.db.Plant(name=alcolea_ns['name'], codename=alcolea_ns['codename']) alcolea = alcolea.importPlant(alcolea_ns) orm.flush() devices = orm.select(p.name for p in self.pony.db.Plant)[:].to_list() self.assertListEqual(devices, ['alcolea']) devices = orm.select((p.name, m.name, i.name) for p in self.pony.db.Plant for m in p.meters for i in p.inverters)[:].to_list() self.assertListEqual(devices, [('alcolea', '1234578', '6666'), ('alcolea', '1234578', '5555')]) alcolea_in_db = orm.select(p for p in self.pony.db.Plant).limit(1)[0] alcolea_dict = alcolea_in_db.to_dict(with_collections=True, related_objects=False) expected = { 'id': 1, 'name': 'alcolea', 'codename': 'SCSOM04', 'description': 'la bonica planta', 'meters': [1], 'inverters': [1, 2], 'sensors': [1,2,3] } alcolea_thin_dict = {k:d for k,d in alcolea_dict.items() if d} self.assertDictEqual(alcolea_thin_dict, expected) orm.rollback()
def test_user_creation(self): name = self.fake.first_name() user = User() user.name = name self.assertEqual(user.name, name) orm.rollback()
def pytest_runtest_teardown(item, nextitem): """ """ marker = item.get_closest_marker("pony") # import test db db = _ponydb(item) provider = db.provider.dialect if marker: if not marker.kwargs.get("db_session", True): orm.db_session.__enter__() # delete all entries from db at end of test # unless @pytest.mark.pony(reset_db=False) is specified if not marker.kwargs.get("db_session", True): orm.db_session.__enter__() if marker.kwargs.get("reset_db", True): orm.rollback( ) # clear possible uncommitted things before delete so the base is Ok. Not good with # commit for entity in db.entities.values(): orm.delete(e for e in entity) # reset sequence : postgres support if provider == "PostgreSQL": _pg_reset_sequences(db) # delete or not the db_session is closed orm.db_session.__exit__()
def tearDown(self): orm.rollback() orm.db_session.__exit__() self.pony.db.drop_all_tables(with_all_data=True) self.pony.db.disconnect() # comment this if you want to check the date format self.cleanLastDateFile()
def handler(*args, **kwargs): try: try: assert_authorized() ret = api_function(*args, **kwargs) if isinstance(ret, flask.Response): return ret if isinstance(ret, tuple): return flask.jsonify(ret[0]), *ret[1:] return flask.jsonify(ret) except Exception as ex: rollback() raise ex except RequestException as ex: ret = flask.jsonify(error=str(ex)), ex.code except DatabaseException as ex: ret = flask.jsonify(error=f"Database error: {ex}"), 500 except PdfException as ex: ret = flask.jsonify(error=f"Internal error: {ex}"), 500 except Exception as ex: ret = flask.jsonify(error=f"Unknown error: {ex}"), 500 return ret
def test_user_creation_already_exists(): User(email='abc', password='******') try: User(email='abc', password='******') except CacheIndexError as ex: assert str( ex ) == "Cannot create User: value 'abc' for key email already exists" rollback()
def wrapped_f(*args): with db_session: try: rv = f(*args) commit() return rv except Exception: rollback() raise
def tearDown(self): orm.rollback() orm.db_session.__exit__() ''' binddb calls gneerate_mapping which creates the tables outside the transaction drop them ''' self.pony.db.drop_all_tables(with_all_data=True) self.pony.db.disconnect()
def setUpORM(self): from conf import envinfo self.assertEqual(envinfo.SETTINGS_MODULE, 'conf.settings.testing') orm.rollback() self.pony = PonyManager(envinfo.DB_CONF) self.pony.define_all_models() self.pony.binddb(create_tables=True) self.pony.db.drop_all_tables(with_all_data=True) self.pony.db.create_tables() self.maxDiff = None
def new_shop(req: ShopCreateRequest): try: b64decode(req.shop_pub_key) except binascii.Error: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='公鑰錯誤') shop = Shop(name=req.name, shop_pub_key=req.shop_pub_key) private_key = PrivateKey.generate() box = SecretBox(SERVER_MASTER_SECRET) try: Secret(shop=shop, server_secret_key=b64encode( box.encrypt(private_key._private_key)).decode('ascii')) commit() except TransactionIntegrityError: rollback() raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail='公鑰已被使用') return b64encode(private_key.public_key._public_key).decode('ascii')
def put(body): for song in body: try: Song.add_entry(song) except IntegrityError: orm.rollback() return { "message": "song of id {} already exists, aborting insert".format( song.get('id')) }, 400 except TransactionIntegrityError: orm.rollback() return { "message": "song of id {} already exists, aborting insert".format( song.get('id')) }, 400 except Exception as e: orm.rollback() logger.error(e) return { "message": "failed to insert the song of id {}, unknown error, check log for more info." " TIMESTAMP {}".format(song.get('id'), time.asctime()) }, 400 return {"message": "Successfully inserted {} songs".format(len(body))}, 200
def setUp(self): from conf import envinfo self.assertEqual(envinfo.SETTINGS_MODULE, 'conf.settings.testing') orm.rollback() self.pony = PonyManager(envinfo.DB_CONF) self.pony.define_all_models() self.pony.binddb(create_tables=True) self.pony.db.drop_all_tables(with_all_data=True) self.storage = PonyMetricStorage(self.pony.db) self.maxDiff = None # orm.set_sql_debug(True) self.pony.db.create_tables() # database.generate_mapping(create_tables=True) orm.db_session.__enter__()
def not_found(e): rollback() return NotFound(e.entity.__name__)
def parse_project_data(project_id, old=False): ''' get rest of project data from excel file based on Project instance ''' with orm.db_session(): project = models.Project[project_id] xl_path = project.path version = project.spreadsheet_version detail_classes = [models.RoomType, models.Room, models.Ahu, models.Fan] if project.xl_mapping_present == False: logging.info('No mapping available for %s\n file:\n %s' % (version, xl_path)) return None # parse files that are in 'old' folders? if r'\old' in xl_path.lower(): project.reparse = False if project.reparse == False: logging.info('Reparse flag False for file:\n %s' % (xl_path)) return None xl_path = project.path tables_data = xl_functions.parse_xls(xl_path, version) if tables_data == None: return None detail_entities = [] for cls_template in detail_classes: # select data for current class template data = tables_data[cls_template._table_] #iterate over each row found in xl for current class template for row in data: entity = None key = None selected = [] # set column name that is unique for current sheet if cls_template._table_ != 'rooms': key = 'name' val = change_type(cls_template, key, row[key]) #selected = list(cls_template.select(lambda c: c.name == val)) entity = orm.select( c for c in cls_template if c.name == val and c.project.id == project_id).get() else: key = 'number' val = change_type(cls_template, key, row[key]) #selected = list(cls_template.select(lambda c: c.number == val)) entity = orm.select(c for c in cls_template if c.number == val and c.project.id == project_id).get() # find if current row is already present in DB (based on unique column) #selected = list(cls_template.select(lambda c: getattr(c, key) == row[key])) #entity = cls_template.filter(getattr(cls_template,key)==row[key]).one_or_none() try: if entity is None: attr = key required = dict() required[key] = change_type(cls_template, key, row[key]) entity = cls_template(project=project, **required) for attr, value in row.items(): value = change_type(cls_template, attr, value) setattr(entity, attr, value) except: orm.rollback() message = 'error parsing xl details: ver:%r , sh|row: %r | %r, col: %r' % ( version, cls_template._table_, row[key], attr) logging.info('current file: %s \n %r' % (xl_path, message)) return write_parse_error(project_id, message) #logging.debug('class entity created for %r: %r' % (row[key],entity)) detail_entities.append(entity) #session.add(entity) logging.info('# of class entities created/updated: %r\n' % (len(detail_entities))) modified = os_functions.get_date_modified(xl_path) project.date_modified = modified project.date_parsed = time.strftime('%Y-%m-%d') project.debug = None project.reparse = False project.show = True return None
def transaction(): with orm.db_session: yield orm.rollback()
def wrapper(*args, **kwargs): with db_session: func_test(*args, **kwargs) rollback()
def tearDown(self): orm.rollback() orm.db_session.__exit__() self.proc.terminate()
def value_error(e): rollback() return GenericError("{0.__class__.__name__}: {0}".format(e))
def key_error(e): rollback() return MissingParameter()
def do_rollback(test): try: yield finally: rollback()
def generic_error(e): # pragma: nocover rollback() return ServerError("{0.__class__.__name__}: {0}".format(e))
def wrapper(*args, **kwargs): with db_session(): func(*args, **kwargs) rollback()
def tearDown(self): orm.rollback() orm.db_session.__exit__() self.pony.db.drop_all_tables(with_all_data=True) self.pony.db.disconnect()
def test_if_engine_is_creating(self): from NLP import nlp self.assertIsInstance(nlp, WitAI) orm.rollback()
def tearDown(self): orm.rollback()
def test_if_tts_is_creating(self): from TTS import tts self.assertIsInstance(tts, TtsGoogle) orm.rollback()
def wrapper(*args, **kwargs): with db_session: test_func(*args, **kwargs) rollback()
def transaction(Agent, Target): with pn.db_session: yield pn.rollback()