Exemplo n.º 1
0
    def create_database(self, db_name, db_usr, db_pwd):
        # Generate Postgres safe identifiers.
        safe_db_name = StringUtil.pg_safe(db_name)
        safe_db_usr = StringUtil.pg_safe(db_usr)

        conn = self._engine.connect()

        # commit the current transaction so we can get a plain connection.
        # SQL DDL does not work within a transaction.
        conn.execute("COMMIT")

        db_created = False
        user_created = False
        user_assigned = False
        try:
            # Create the database.
            conn.execute("CREATE DATABASE {0}".format(safe_db_name))
            db_created = True
            conn.execute(
                "CREATE USER {0} WITH ENCRYPTED PASSWORD '{1}'".format(
                    safe_db_usr, db_pwd))
            user_created = True
            conn.execute("GRANT ALL PRIVILEGES ON DATABASE {0} TO {1}".format(
                safe_db_name, safe_db_usr))
            user_assigned = True

            # Initialise the database session attribute..
            engine = sqlalchemy.create_engine(
                "postgresql://{0}:{1}@localhost/{2}".format(
                    safe_db_usr, db_pwd, safe_db_name))

            # Generate tables.
            Base.metadata.create_all(engine)

            # Generate session class.
            self.Session = sessionmaker(engine)
            return True
        except Exception as e:
            logging.error("Couldn't create database: {0}".format(str(e)))
        finally:
            conn.execute("COMMIT")

            try:
                if db_created and not user_created:
                    # If user is not assigned after database assignment, drop the database.
                    conn.execute("DROP DATABASE {0}".format(safe_db_name))
                elif user_created and not user_assigned:
                    # If unable to assign user drop user and the database.
                    conn.execute("DROP DATABASE {0}".format(safe_db_name))
                    conn.execute("DROP USER {0}".format(safe_db_usr))
            except Exception as e:
                logging.error(
                    "Couldn't rollback database creation: {0}".format(str(e)))
            finally:
                conn.close()

        return False
Exemplo n.º 2
0
 def test_is_num(self):
     positive_cases = []
     negative_cases = []
     positive_cases.append("123")
     positive_cases.append("123.123")
     negative_cases.append("affgaf")
     negative_cases.append(" ")
     negative_cases.append("")
     for positive_case, negative_case in zip(positive_cases,
                                             negative_cases):
         self.assertTrue(StringUtil.isnum(positive_case))
         self.assertFalse(StringUtil.isnum(negative_case))
Exemplo n.º 3
0
    def read_atom_line(line):
        ''' Read a line from a PDB file starting with ATOM '''
        elem = StringUtil.cstrip(line[76:78])
        if not PDBReader.ELEMENT.match(elem):
            elem = StringUtil.cstrip(line[12:14])

        x = float(line[30:38])
        y = float(line[38:46])
        z = float(line[46:54])

        return Atom(
            StringUtil.cstrip(line[0:6]),  # label
            int(line[6:11]),  # atom number
            StringUtil.cstrip(line[12:16]),  # atom name
            StringUtil.cstrip(line[16]),  # alternative atom
            StringUtil.cstrip(line[17:21]),  # residue name
            StringUtil.cstrip(line[21]),  # chain id
            int(line[22:26]),  # residue number
            line[26],  # resExt
            x,  # X coordinate
            y,  # Y coordinate
            z,  # Z coordinate
            float(line[54:60]),  # occupancy
            float(line[60:66]),  # B-Factor
            elem)  # element
 def login(self, cpf: str, password: str):
     try:
         only_cpf = StringUtil.get_cpf(cpf)
         data = self.repository.login(cpf=only_cpf, password=password)
         return self.create_schema.dump(data)
     except NotFoundException:
         raise NotFoundException('Not found')
     except Exception as err:
         raise NotMappedException(err)
 def find_by_cpf(self, cpf: str):
     try:
         only_cpf = StringUtil.get_cpf(cpf)
         data = self.repository.find_by_cpf(cpf=only_cpf)
         return self.view_schema.dump(data)
     except NotFoundException:
         raise NotFoundException(message='Not found')
     except Exception as err:
         raise NotMappedException(message=err)
 def find_by_cpf(self, cpf):
     try:
         logging.info('Start find purchase')
         only_cpf = StringUtil.get_cpf(cpf)
         return ViewPurchaseSchema(many=True).dump(
             self.repository.find_by_cpf(only_cpf))
     except NotFoundException:
         raise NotFoundException('Not found')
     except Exception as err:
         raise NotMappedException(err)
Exemplo n.º 7
0
def initial_reseller():
    if CREATE_FIRST_RESELLER:
        service = ResellerService()
        only_cpf = StringUtil.get_cpf(CPF_ADM)
        try:
            service.add({
                "full_name": "Administrator",
                "cpf": only_cpf,
                "email": "{0}@email.com".format(only_cpf),
                "password": DEFAULT_PASSWORD
            })
        except Exception:
            pass
 def cash_back(self, cpf):
     try:
         only_cpf = StringUtil.get_cpf(cpf)
         if only_cpf == '':
             raise ConsumeApiException('Problem with cashback api')
         url = URL_CASH_BACK.format(only_cpf)
         header = {'token': TOKEN_CASH_BACK}
         response = requests.get(url, headers=header)
         return response.json()["body"]["credit"]
     except ConsumeApiException as err:
         raise ConsumeApiException(err)
     except Exception as err:
         raise NotMappedException(err)
Exemplo n.º 9
0
 def test_parse_until_duration(self):
     '''
     验证parser能够正确解析出duration
     :return:
     '''
     parser = self.parser
     for ltl in self.ltls:
         parsed_ltl = parser.parse_line(ltl)
         str_duration = self._get_duration(parsed_ltl)
         self.assertTrue(
             StringUtil.isnum(str_duration),
             "parsed_ltl:{}, str_duration:{}".format(
                 parsed_ltl, str_duration))
 def test_11_add(self):
     reseller = {
         "cpf": self.CONST_CPF,
         "email": "*****@*****.**",
         "password": "******",
         "full_name": "Administrator"
     }
     duplicate_reseller = {
         "cpf": self.CONST_CPF,
         "email": "*****@*****.**",
         "password": "******",
         "full_name": "Administrator"
     }
     invalid_reseller = {"cpf": self.CONST_CPF, "password": ""}
     new_reseller = self.reseller_service.add(reseller)
     assert new_reseller["cpf"] == StringUtil.get_cpf(self.CONST_CPF)
     with self.assertRaises(InvalidDataException):
         self.reseller_service.add(invalid_reseller)
     with self.assertRaises(DuplicateDataException):
         self.reseller_service.add(duplicate_reseller)
Exemplo n.º 11
0
 def read_atom_line(line):
     ''' Read a line from a PDB file starting with ATOM '''
     elem = StringUtil.cstrip(line[76:78])
     if not PDBReader.ELEMENT.match(elem):
         elem = StringUtil.cstrip(line[12:14])
     
     x = float(line[30:38])
     y = float(line[38:46])
     z = float(line[46:54])
     
     return Atom (StringUtil.cstrip(line[0:6]),      # label
                  int(line[6:11]),                   # atom number
                  StringUtil.cstrip(line[12:16]),    # atom name
                  StringUtil.cstrip(line[16]),       # alternative atom
                  StringUtil.cstrip(line[17:21]),    # residue name
                  StringUtil.cstrip(line[21]),       # chain id
                  int(line[22:26]),                  # residue number
                  line[26],                          # resExt
                  x,                                 # X coordinate
                  y,                                 # Y coordinate
                  z,                                 # Z coordinate
                  float(line[54:60]),                # occupancy
                  float(line[60:66]),                # B-Factor
                  elem)                              # element
 def test_12_find_by_cpf(self):
     data = self.reseller_service.find_by_cpf(cpf=self.CONST_CPF)
     with self.assertRaises(NotFoundException):
         self.reseller_service.find_by_cpf(cpf="0")
     assert data["cpf"] == StringUtil.get_cpf(self.CONST_CPF)
def _get_status(cpf):
    if StringUtil.get_cpf(cpf) == StringUtil.get_cpf(CPF_ADM):
        return 'Aprovado'
    else:
        return 'Em validação'