Пример #1
0
    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()
Пример #2
0
    def test_user_creation(self):
        name = self.fake.first_name()
        user = User()
        user.name = name

        self.assertEqual(user.name, name)
        orm.rollback()
Пример #3
0
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__()
Пример #4
0
 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()
Пример #5
0
    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
Пример #6
0
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()
Пример #7
0
 def wrapped_f(*args):
     with db_session:
         try:
             rv = f(*args)
             commit()
             return rv
         except Exception:
             rollback()
             raise
Пример #8
0
 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()
Пример #9
0
    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
Пример #10
0
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')
Пример #11
0
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
Пример #12
0
    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__()
Пример #13
0
def not_found(e):
    rollback()
    return NotFound(e.entity.__name__)
Пример #14
0
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
Пример #15
0
def transaction():
    with orm.db_session:
        yield
        orm.rollback()
Пример #16
0
 def wrapper(*args, **kwargs):
     with db_session:
         func_test(*args, **kwargs)
         rollback()
Пример #17
0
 def tearDown(self):
     orm.rollback()
     orm.db_session.__exit__()
     self.proc.terminate()
Пример #18
0
def not_found(e):
    rollback()
    return NotFound(e.entity.__name__)
Пример #19
0
def value_error(e):
    rollback()
    return GenericError("{0.__class__.__name__}: {0}".format(e))
Пример #20
0
def key_error(e):
    rollback()
    return MissingParameter()
Пример #21
0
def value_error(e):
    rollback()
    return GenericError("{0.__class__.__name__}: {0}".format(e))
Пример #22
0
def do_rollback(test):
    try:
        yield
    finally:
        rollback()
Пример #23
0
def key_error(e):
    rollback()
    return MissingParameter()
Пример #24
0
def generic_error(e): # pragma: nocover
    rollback()
    return ServerError("{0.__class__.__name__}: {0}".format(e))
Пример #25
0
def generic_error(e):  # pragma: nocover
    rollback()
    return ServerError("{0.__class__.__name__}: {0}".format(e))
Пример #26
0
 def wrapper(*args, **kwargs):
     with db_session():
         func(*args, **kwargs)
         rollback()
Пример #27
0
 def tearDown(self):
     orm.rollback()
     orm.db_session.__exit__()
     self.pony.db.drop_all_tables(with_all_data=True)
     self.pony.db.disconnect()
Пример #28
0
 def test_if_engine_is_creating(self):
     from NLP import nlp
     self.assertIsInstance(nlp, WitAI)
     orm.rollback()
 def tearDown(self):
     orm.rollback()
Пример #30
0
 def test_if_tts_is_creating(self):
     from TTS import tts
     self.assertIsInstance(tts, TtsGoogle)
     orm.rollback()
Пример #31
0
 def wrapper(*args, **kwargs):
     with db_session:
         test_func(*args, **kwargs)
         rollback()
Пример #32
0
def transaction(Agent, Target):
    with pn.db_session:
        yield
        pn.rollback()