示例#1
0
def test_MySQLWrapper(number=100):
    cfg = ReadConfig('./db.info')
    cfgd = cfg.check_config()
    sop = cfgd['mysql']['app_eemsop']
    print('sop', sop)
    ####
    try:
        sql_pool1 = MySQLWrapper(**sop)
    except:
        print('error')
        return -1
    time1_start = time.time()
    for i in range(int(number)):
        sql = 'select * from users where id=%s' % (int(random.random() * 5))
        res = sql_pool1.do_work(sql)
    print(res)
    time1_end = time.time()
    time1_spend = time1_end - time1_start
    print('my own mysql wraper, query  times %s, spend %s s' %
          (number, time1_spend))
    time2_start = time.time()
    for i in range(int(number)):
        conn = MySQLdb.connect(**sop)
        c = conn.cursor()
        c.execute('select * from users where id=%s' %
                  (int(random.random() * 5)))
        res = c.fetchall()
        conn.close()
    time2_end = time.time()
    time2_spend = time2_end - time1_start
    print('normal, query  times %s, spend %s s' % (number, time2_spend))
    return [time1_spend, time2_spend]
示例#2
0
 def __init__(self):
     """
     Constructor to initialise credentials.
     """
     self.config = ReadConfig()
     self.access_token = self.config.get_access_token()
     self.access_secret = self.config.get_access_secret()
     self.consumer_key = self.config.get_consumer_key()
     self.consumer_secret = self.config.get_consumer_secret()
示例#3
0
def main():
    print('db_pool is a database connection pool, as tool class.')
    cfg = ReadConfig('./db.info')
    cfgd = cfg.check_config()
    rp = RedisWrapper(host=cfgd['redis']['91']['host'])
    r1 = rp.redis_connect()
    rp2 = redis.ConnectionPool(host='172.16.5.91', port=6379)
    r2 = redis.Redis(connection_pool=rp2)
    print(r1)
    print(r2)
    test_MySQLWrapper()
示例#4
0
    def test_get_consumer_key(self, mock_open, mock_yaml):
        mock_open.return_value.__enter__.return_value = True
        mock_yaml.safe_load.return_value = {
            'development': {
                'consumer_key': 'my_consumer_key'
            }
        }

        r = ReadConfig()
        actual_result = r.get_consumer_key()

        self.assertEqual(actual_result, 'my_consumer_key')
示例#5
0
    def test_get_access_token(self, mock_open, mock_yaml):
        mock_open.return_value.__enter__.return_value = True
        mock_yaml.safe_load.return_value = {
            'development': {
                'access_token': 'my_access_token'
            }
        }

        r = ReadConfig()
        actual_result = r.get_access_token()

        self.assertEqual(actual_result, 'my_access_token')
示例#6
0
def rd(server='91'):
    cfg = ReadConfig('./db.info')
    cfgd = cfg.check_config()
    try:
        host = '6379' if not ('host' in cfgd['redis'][server].keys()
                              ) else cfgd['redis'][server]['host']
        port = '6379' if not ('port' in cfgd['redis'][server].keys()
                              ) else cfgd['redis'][server]['port']
        db = '0' if not ('db' in cfgd['redis'][server].keys()
                         ) else cfgd['redis'][server]['db']
        # print(host, port, db)
        rp = RedisWrapper(host=host, port=port, db=db, name=server)
    except:
        return None
    return rp.redis_connect()
示例#7
0
class GetCookie:
    check_list = eval(ReadConfig().get_config(project_path.case_config_path,
                                              'CHECKLEAVEAMOUNT',
                                              'check_list'))
    Cookie = None
    loanId = None
    NoRegTel = pd.read_excel(project_path.test_case_path,
                             sheet_name="init").iloc[0, 0]
    #参照init表单查看我们这个变量的用处
    normal_tel = pd.read_excel(project_path.test_case_path,
                               sheet_name="init").iloc[1, 0]
    admin_tel = pd.read_excel(project_path.test_case_path,
                              sheet_name="init").iloc[2, 0]
    loan_member_id = pd.read_excel(project_path.test_case_path,
                                   sheet_name="init").iloc[3, 0]
示例#8
0
def get_suntime():
    location = ReadConfig('location').get()
    city = LocationInfo(name=location['city'],
                        region=location['country'],
                        timezone=location['timezone'],
                        latitude=location['latitude'],
                        longitude=location['longitude'])
    city_sun = sun(city.observer,
                   date=datetime.date.today(),
                   tzinfo=city.timezone)

    city_sunrise = city_sun['sunrise'].time()
    city_sunset = city_sun['sunset'].time()

    print(city_sunrise.minute, city_sunrise.hour, city_sunset.minute,
          city_sunset.hour)
示例#9
0
class OPMysql(object):

    __pool = None
    data = ReadConfig()

    def __init__(self):
        # 构造函数,创建数据库连接、游标
        self.conn = OPMysql.getmysqlconn()
        self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 数据库连接池连接
    @staticmethod
    def getmysqlconn():
        host = OPMysql.data.get_db("mysql", "host")
        user = OPMysql.data.get_db("mysql", "user")
        password = OPMysql.data.get_db("mysql", "passwd")
        db = OPMysql.data.get_db("mysql", "db")
        port = OPMysql.data.get_db("mysql", "port")
        charset = OPMysql.data.get_db("mysql", "charset")
        if OPMysql.__pool is None:
            __pool = PooledDB(creator=pymysql,
                              mincached=1,
                              maxcached=20,
                              host=host,
                              user=user,
                              passwd=password,
                              db=db,
                              port=int(port),
                              charset=charset)
        return __pool.connection()

    # 插入\更新\删除sql
    def op_execute(self, sql, data):
        related_num = self.cur.execute(sql, data)
        self.conn.commit()
        return related_num

    # 查询sql
    def op_search(self, sql):
        self.cur.execute(sql)
        select_res = self.cur.fetchall()
        return select_res

    # 释放资源
    def dispose(self):
        self.conn.close()
        self.cur.close()
示例#10
0
import unittest
from ddt import ddt, data
from read_config import ReadConfig
import HTMLTestRunnerNew
#导入测试报告模块
import HTMLTestRunnerNew
#导入被测试类(即需要测试的接口代码)
from unittest_math_method import MathMethod
from unittest_testcase_excel import DoExcel
from unittest_testcase_excel import GetExcel

excel_path = GetExcel("testdata.xlsx").Get_Excel_Path()
excel_title = "testdata"
button = ReadConfig().read_config("case.config", 'FLAG', 'button')
case_id_list = eval(ReadConfig().read_config("case.config", 'FLAG',
                                             'cse_id_list'))
test_data = DoExcel(excel_path, excel_title).do_excel2(button,
                                                       case_id_list)  #列表数据


#优化测试用例
@ddt
class Test_Add_ddt(unittest.TestCase):  #测试类
    def setUp(self):
        self.t = MathMethod()
        # self.doexcel = DoExcel()
        print("********************")
        print("Test Begin:")
        # print("Test describtion:{0}".format(self.test_des))

    def tearDown(self):
示例#11
0
文件: nfpa.py 项目: P4ELTE/cbt
    def initialize(self):

        #read config
        self.rc = ReadConfig(self.config_file)
        if (self.rc == -1):
            #error during reading config
            return -1

        self.config = self.rc.getConfig()

        self.log = l.getLogger(self.__class__.__name__,
                               self.config['LOG_LEVEL'],
                               self.config['app_start_date'],
                               self.config['LOG_PATH'])

        self.pid_file = self.config['MAIN_ROOT'] + "/" + "nfpa.pid"
        self.log.info("Deleting previous pid_file: %s" % self.pid_file)
        os.system("rm -rf " + self.pid_file)

        #before fresh start remove temporary files if they were not removed
        #already. This could be happen, if in some case, NFPA crashes, and
        #temporary res files in PKTGEN_ROOT/ still remains existing and can
        #influence a latter measurement results in a wrong way
        self.log.info("Clean up old .res files in PKTGEN's root dir...")
        self.deleteResFiles()
        self.log.info("[DONE]")

        #create a tmp directory for flow rules under nfpa/of_rules
        path = self.config["MAIN_ROOT"] + "/of_rules/tmp"
        if not os.path.exists(path):
            os.makedirs(path)

        self.log.debug("tmp directory created under of_rules")


        self.log.info("### Measurement scenario '" + self.scenario_name + \
                      "' has been initiated ###")

        #append scenario name to self.config dictionary for later usage
        self.config['scenario_name'] = self.scenario_name

        self.log.debug(str(self.config))
        #assembling log file path
        self.log_file_path = self.config['MAIN_ROOT'] + "/log/log_" + \
                             df.getDateFormat(self.config['app_start_date']) +\
                             ".log"

        self.log.info("Log file for this measurement is: %s" %
                      self.log_file_path)
        self.log.info("THANKS FOR USING NFPA FOR MEASURING")

        self.storePID(str(os.getpid()))
        self.log.debug("NFPA PID stored")

        # create an instance of the EmailAdapter and store this object in self.config
        # if email service was enabled in the config file
        if self.config['email_service'].lower() == "true":
            self.config['email_adapter'] = EmailAdapter(self.config)
        else:
            self.config['email_adapter'] = None

        #adding no_plot variable to self.config to be able to share it later with visualizer
        self.config['no_plot'] = self.no_plot
示例#12
0
import xlrd
from read_config import ReadConfig

localConfig = ReadConfig()
filePath = localConfig.file_path('testfile', 'testfile.xlsx')


class ReadExcel:
    def read_excel(self, sheetname):
        cls = []
        excelFile = xlrd.open_workbook(filePath)
        sheet = excelFile.sheet_by_name(sheetname)
        nrows = sheet.nrows
        for nrow in range(nrows):
            if sheet.row_values(nrow)[0] != 'case_name':
                cls.append(sheet.row_values(nrow))
        return cls
示例#13
0
from read_config import ReadConfig
cf = ReadConfig()
print(cf.get_config('path'))
示例#14
0
# coding=utf-8
from read_config import ReadConfig

# 调用readConfig从配置文件获取配置文件中的参数
protocol = ReadConfig().get_protocol('protocol')
domin = ReadConfig().get_domin('domin')
basepath = ReadConfig().get_basepath('basepath')
port = ReadConfig().get_port('port')

base_url = protocol + '://' + domin + ':' + port + basepath

if __name__ == "__main__":
    print(base_url)
示例#15
0
 def __init__(self):
     self.data = ReadConfig()
示例#16
0
import shutil
from os import getcwd, path

logging.basicConfig(
    filename="log.txt",
    filemode='a',
    format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
    datefmt='%H:%M:%S',
    level=logging.INFO)

if __name__ == '__main__':
    try:
        cwd = getcwd()
        if not path.isfile(cwd + 'log.txt'):
            open(cwd + 'log.txt', 'w')
        cfg = ReadConfig()
        switcher = {
            "#S": "site_name",
            "#I": "site_code",
            "#D": str(datetime.datetime.today().strftime('%y%m%d')),
            "#T": "000000",
            "#M": "xx:xx:xx:xx:xx:xx"
        }
        common = xc.ServerProxy('{}/xmlrpc/2/common'.format(cfg.url))
        common.version()
        uid = common.authenticate(cfg.db, cfg.username, cfg.password, {})
        models = xc.ServerProxy('{}/xmlrpc/2/object'.format(cfg.url))
        can_access_sensor = models.execute_kw(cfg.db, uid, cfg.password,
                                              'htc.sensor',
                                              'check_access_rights', ['read'],
                                              {'raise_exception': False})
示例#17
0
# coding=utf-8
import requests
from common.get_base_url import base_url
from read_config import ReadConfig

# 调用readConfig从配置文件获取配置文件中的参数
agentid = ReadConfig().get_agentid('agentid')
corpid = ReadConfig().get_corpid('corpid')
agent_secret = ReadConfig().get_agent_secret('agent_secret')
txl_secret = ReadConfig().get_txl_secret('txl_secret')
apphelper_secret = ReadConfig().get_apphelper_secret('apphelper_secret')
device_secret = ReadConfig().get_device_secret('device_secret')
log_secret = ReadConfig().get_log_secret('log_secret')

agent_payload = {
                "corpid": corpid,
                "corpsecret": agent_secret
                }

txl_payload = {
                "corpid": corpid,
                "corpsecret": txl_secret
                }

apphelper_payload = {
                "corpid": corpid,
                "corpsecret": apphelper_secret
                }

device_payload = {
                "corpid": corpid,