def encryption_zip(self, xtbh): cg = ReadConfig() zippath = cg.getvalue('localPath', 'path') + '\\' + str(xtbh) + '.zip' logger.info(zippath) if os.path.exists(zippath): logger.info('压缩包存在,开始加密') jarpath1 = os.path.join( os.path.abspath('.'), '../tools//jar//ebcp-exchange-1.1.6-minio-SNAPSHOT.jar') jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % (jarpath1)) # 启动jvm JClass = jpype.JClass( 'com.thunisoft.ebcp.exchange.support.utils.DESUtil') test = JClass() zipanme = os.path.split(zippath)[1] # 获取压缩包名称 logger.info("压缩包名称%s" % zipanme) zip_path = os.path.split(zippath)[0] # 获取压缩包路径 logger.info("压缩包路径%s" % zip_path) zip_path_after = os.path.join( zip_path, "./after_jiami") # 默认在当前路径下创建一级目录,用来存放解密之后的压缩包 test.encryptZip(zippath, zip_path_after, zipanme, "75AFFF024BDA72E9CAAB5E019BB94729") jpype.shutdownJVM() # 最后关闭jvm logger.info("加密成功") logger.info("加密后文件存放路径:%s" % zip_path_after) else: logger.info('压缩包不存在,无法加密')
def mylog(self, msg_level, msg): mylog = logging.Logger('mylog') # 获取日志收集器级别 mylog.setLevel(ReadConfig().get('testconfig', 'log_level')) # log_path 日志的存放路径和文件名称 log_path = constants.log_path filename = log_path + time.strftime('%Y%m%d', time.localtime(time.time())) fh = logging.FileHandler(filename, 'a+', encoding='utf-8') # 获取配置文件中的文件日志输出级别 fh.setLevel(ReadConfig().get('testconfig', 'fh_level')) # 获取配置文件中的日志输出格式 formatter = logging.Formatter(ReadConfig().get('testconfig', 'Formatter')) fh.setFormatter(formatter) # 对接日志收集器 mylog.addHandler(fh) if msg_level == 'DEBUG': mylog.debug(msg) elif msg_level == 'INFO': mylog.info(msg) elif msg_level == 'WARNING': mylog.warning(msg) elif msg_level == 'ERROR': mylog.error(msg) elif msg_level == 'CRITICAL': mylog.critical(msg) # 使用完后移除渠道,减少重复日志 mylog.removeHandler(fh)
def __init__(self): user = ReadConfig().get_cx('user') pwd = ReadConfig().get_cx('pwd') ip = ReadConfig().get_cx('ip') host = ReadConfig().get_cx('host') sid = ReadConfig().get_cx('sid') self.connect = cx_Oracle.connect(user + "/" + pwd + "@" + ip + ":" + host + "/" + sid) self.cursor = self.connect.cursor()
def __init__(self): global url, timeout config = ReadConfig() url = config.get_config_value('apiDomain','domain') timeout = config.get_config_value('apiDomain','timeout') self.data = {} self.headers = {} self.url = None self.files = {}
def rename_pdf(self, xtbh, xyrxm): cg = ReadConfig() pdfpath = cg.getvalue('localPath', 'path') + '\\' + str(xtbh) + "\ws" + '\\' for file in os.listdir(pdfpath): filename = file.split('.') name = filename[0] fileNew = name[0:7] + "(" + xyrxm + ")" + "." + filename[1] if fileNew != file: os.rename(pdfpath + file, pdfpath + fileNew)
def setUpClass(cls): conf = ReadConfig() cls.mylog = MyLog() mysql = MySql() options = conf.getoptions('test_user') for item in options: memberId_sql = 'SELECT Id from future.member WHERE MobilePhone = "{0}"'.format( conf.getstr('test_user', item)['user']) cls.mylog.info('初始化用户数据sql:{}'.format(memberId_sql)) memberId = mysql.fet_one(memberId_sql) setattr(contex, item + '_id', str(memberId['Id'])) cls.mylog.info('获取到{},的id是{}'.format(conf.getstr('test_user', item)['user'], memberId['Id']))
def config_app(self): r = ReadConfig() platformName = r.get_platformName('platformName') # print('platformName------', platformName) if platformName == 'android': self.driver = self.Android() return self.driver elif platformName == "ios": self.driver = self.ios() return self.driver
def __init__(self, name=''): global url, timeout, header header = {} config = ReadConfig() url = config.get_config_value('apiDomain', 'domain') timeout = config.get_config_value('apiDomain', 'timeout') self.headers = config.get_config_section_dict('HEADERS') self.data = {} self.json = {} self.url = None self.files = {} self.cookies = None self.filename = "" self.filepath = ""
def putto_server(self, xtbh): cg = ReadConfig() localpath = cg.getvalue( 'localPath', 'path') + '\\after_jiami' + '\\' + str(xtbh) + '.zip' logger.info("本地文件路径{}".format(localpath)) servicepath = '/home/ftp' + cg.getvalue( 'servicefilepath', 'filepath') + '/' + str(xtbh) + '.zip' logger.info("ftp服务器路径{}".format(servicepath)) transport = paramiko.Transport(self.__hostname, self.__port) transport.connect(username=self.__username, password=self.__password) logger.info("连接服务器%s成功,开始上传压缩包" % self.__hostname) sftp = paramiko.SFTPClient.from_transport(transport) sftp.put(localpath, servicepath) logger.info("上传到服务器成功") sftp.close()
def read_excel(self, sheet_name, section): try: wb = load_workbook(self.file_name) sheet = wb[sheet_name] Log().info('-----------------------------------------开始读取测试数据-----------------------------------------') except Exception as e: Log().error('---打开用例失败{}'.format(traceback.format_exc())) print(e) data_case = [] final_data = [] case_amount = eval(ReadConfig().cf.get(section, 'case_amount')) # column_name = ['CaseId', 'Module', 'Url', 'Method', 'Description', 'Param', 'ExpectedResult'] # for row in range(2, sheet.max_row+1): # row_data = {} # for col, item in enumerate(column_name): # row_data[item] =sheet.cell(row, col + 1).value # # data_case.append(row_data) # wb.close() # print(data_case) # return data_case # 方法二 for row in range(2, sheet.max_row + 1): # print(row) row_data = {} row_data['CaseId'] = sheet.cell(row, 1).value row_data['Module'] = sheet.cell(row, 2).value row_data['Url'] = sheet.cell(row, 3).value row_data['Method'] = sheet.cell(row, 4).value row_data['Description'] = sheet.cell(row, 5).value # 方法一:在字符串中替换tel,非常麻烦不可取,建议先变成字典然后再字典中转换 # row_data['Param'] = sheet.cell(row, 6).value # if row_data['Param'].find('tel') != -1: # Log().info('查看电话号码') # new_tel = DoExcel(project_path.test_cases_path).read_tel() # row_data['Param'] = eval(row_data['Param'].replace('tel', str(new_tel))) # DoExcel(project_path.test_cases_path).write_tel(new_tel) # else: # row_data['Param'] = eval(row_data['Param']) # 方法二 row_data['Param'] = eval(sheet.cell(row, 6).value) if row_data['Param'].get('mobilephone') == 'tel': row_data['Param']['mobilephone'] = DoExcel(project_path.test_cases_path).read_tel() DoExcel(project_path.test_cases_path).write_tel(DoExcel(project_path.test_cases_path).read_tel()) row_data['ExpectedResult'] = eval(sheet.cell(row, 7).value) data_case.append(row_data) wb.close() # 此处获取配置文件配置用例,0代表执行全部用例 if case_amount == 0: final_data = data_case else: for i in case_amount: final_data.append(data_case[int(i) - 1]) print(len(final_data), final_data) return final_data
def read_excel(self): """read模块把不同sheet页的用例根据配置文件设置全部取出,""" try: wb = load_workbook(self.file_name) Log().info( '-----------------------------------------开始读取测试数据-----------------------------------------' ) except Exception as e: Log().error('---打开用例失败{}'.format(traceback.format_exc())) print(e) final_data = [] case_amount = ReadConfig().case_amount() # column_name = ['CaseId', 'Module', 'Url', 'Method', 'Description', 'Param', 'ExpectedResult'] # for row in range(2, sheet.max_row+1): # row_data = {} # for col, item in enumerate(column_name): # row_data[item] =sheet.cell(row, col + 1).value # # data_case.append(row_data) # wb.close() # print(data_case) # return data_case # 方法二 for key in case_amount: # 取到配置文件{'recharge':0,'Sheet1':[1,3,5]}, data_case = [] sheet = wb[key] # key代表表单名 for row in range(2, sheet.max_row + 1): # print(row) row_data = {} row_data['CaseId'] = sheet.cell(row, 1).value row_data['Module'] = sheet.cell(row, 2).value row_data['Url'] = sheet.cell(row, 3).value row_data['Method'] = sheet.cell(row, 4).value row_data['Description'] = sheet.cell(row, 5).value # 方法二 row_data['Param'] = eval(sheet.cell(row, 6).value) if row_data['Param'].get('mobilephone') == 'tel': row_data['Param']['mobilephone'] = DoExcel( project_path.test_cases_path).read_tel() DoExcel(project_path.test_cases_path).write_tel( DoExcel(project_path.test_cases_path).read_tel()) row_data['Sql'] = eval(sheet.cell(row, 7).value) row_data['ExpectedResult'] = eval(sheet.cell(row, 8).value) data_case.append(row_data) # 此处获取配置文件配置用例,0代表执行全部用例 if case_amount[key] == 0: final_data += data_case else: for i in case_amount[key]: final_data.append(data_case[int(i) - 1]) wb.close() Log.info('测试用例共{}条,分别为:{}'.format(len(final_data), final_data)) Log.info( '--------------------------------------------读取测试数据完毕-----------------------------------------' ) print(len(final_data), final_data) return final_data
def zip_file(self, xtbh): """文件夹名称以协同编号结尾""" cg = ReadConfig() zippath = cg.getvalue('localPath', 'path') + '\\' + str(xtbh) file_news = zippath + ".zip" logger.info(file_news) # 压缩文件 z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(zippath): fpath = dirpath.replace(zippath, '') fpath = fpath and fpath + os.sep or '' for filename in filenames: z.write(os.path.join(dirpath, filename), fpath + filename) z.close() if os.path.exists(file_news): logger.info('文件压缩成功') else: logger.info('文件压缩失败') return file_news
class ConfigManager(object): # 项目目录 BASE_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) # 日志目录 LOG_DIR = os.path.join(BASE_DIR, 'logs') # 截图目录 SCREENSHOT_DIR = os.path.join(BASE_DIR, 'screen_capture') # 元素定位的类型 LOCATE_MODE = { 'css': By.CSS_SELECTOR, 'xpath': By.XPATH, 'name': By.NAME, 'id': By.ID, 'class': By.CLASS_NAME } # 测试项目应用管理 tests = { 'tests': os.path.join(BASE_DIR, 'tests'), 'baidu': os.path.join(BASE_DIR, 'tests', 'test_baidu') } # 测试项目配置文件应用管理 ini = { "baidu": ReadConfig(tests['baidu']) } # 测试项目元素文件应用管理 element = { "baidu": os.path.join(tests['baidu'], 'page', 'elements') } # airimages图片管理 airimages = { 'baidu': os.path.join(tests['baidu'], 'page', 'images') } @property def screen_path(self): """截图目录""" if not os.path.exists(self.SCREENSHOT_DIR): os.makedirs(self.SCREENSHOT_DIR) _now = datetime_strftime("%Y%m%d%H%M%S") screen_file = os.path.join(self.SCREENSHOT_DIR, "{}.png".format(_now)) return _now, screen_file @property def log_path(self): if not os.path.exists(self.LOG_DIR): os.makedirs(self.LOG_DIR) return os.path.join(self.LOG_DIR, '{}.log'.format(datetime_strftime()))
class Drive: def __init__(self): self.readconfig = ReadConfig() self.driver = webdriver.Chrome() self.action = ActionChains(self.driver) def open_browser(self, url): self.driver.maximize_window() self.driver.get(url) return self.driver def close_brwser(self): self.driver.quit() def find_element(self, name): pathType = self.readconfig.getPathType(name) pathValue = self.readconfig.getPathValue(name) if pathType == 'id': return self.driver.find_element_by_id(pathValue) elif pathType == 'class_name': return self.driver.find_element_by_class_name(pathValue) elif pathType == 'name': return self.driver.find_element_by_name(pathValue) elif pathType == 'css_selector': return self.driver.find_element_by_css_selector(pathValue) elif pathType == 'xpath': return self.driver.find_element_by_xpath(pathValue) elif pathType == 'link_text': return self.driver.find_element_by_link_text(pathValue) elif pathType == 'tag_name': return self.driver.find_element_by_tag_name(pathValue) elif pathType == 'partial_link_text': return self.driver.find_element_by_partial_link_text(pathValue) def right_click(self, element_name=None): ac = ActionChains(self.driver) return ac.context_click(self.find_element(element_name)).perform() def switch_to_iframe(self): self.driver.switch_to.frame()
def get_cookie(self): self.driver.get(self.url) # self.driver.maximize_window() self.driver.find_element_by_xpath("//input[@id='username']").send_keys( self.user_name) self.driver.find_element_by_xpath("//input[@id='password']").send_keys( self.passwd) self.driver.find_element_by_xpath( "//input[contains(@class,'loginBtn')]").click() cookie_items = self.driver.get_cookies()[0] # print(cookie_items) cookie = cookie_items['name'] + '=' + cookie_items['value'] # print(type(cookie)) ReadConfig().add_option('GetCookies', 'Cookie', cookie)
def my_sql(self, query, flag=1): """flag=1,代表返回一条SQL数据 flag=2,代表返回多条SQL数据 """ db_config = ReadConfig().db_config() # 获取数据库配置参数 cnn = connector.connect(**db_config) # 连接数据库 cursor = cnn.cursor() # 获取游标 # query = 'select memberid from loan where Id =18366' # 写SQL cursor.execute(query) # 执行SQL 如果涉及到到增删改,需执行cursor.execute('commit') if flag == 1: res = cursor.fetchone() # 获取一条SQL执行结果 else: res = cursor.fetchall() # 获取多条SQL执行结果 return res
class Login: def __init__(self): self.conf = ReadConfig() #"config.ini" print(self.conf.cf.sections()) def login(self, dev, ei): if (dev == 'test'): domain = "https://www.ceshi112.com" else: domain = "https://www.fxiaoke.com" login_url = domain + "/FHH/EM0HUL/Authorize/EnterpriseAccountLogin" login_key = self.conf.get_login_key(ei) print("login_key:" + login_key) response = requests.post(login_url, json=login_key) print(response.text)
def __init__(self): try: confObj = ReadConfig() host = confObj.get_config("redis", "REDIS_HOST") port = confObj.get_config("redis", "REDIS_PORT") bucket = confObj.get_config("redis", "REDIS_BUCKET") if confObj.get_config( "redis", "REDIS_BUCKET") else 0 pwd = confObj.get_config("redis", "REDIS_PWD") if confObj.get_config( "redis", "REDIS_PWD") else None self.ex = confObj.get_config("redis", "REDIS_EXPIRETIME") self.conn = redis.Redis(host=host, port=port, password=pwd, db=bucket) self._label = os.path.abspath(os.path.dirname(os.getcwd())).split( os.path.sep) self._label.reverse() except Exception as e: logging.error("Redis connection failed, error message:%s", e)
def __init__(self, dw): cg = ReadConfig() if dw == 'ga': self.__hostname = cg.getvalue('FtpServer-ga', 'host') self.__port = int(cg.getvalue('FtpServer-ga', 'port')) self.__username = str(cg.getvalue('FtpServer-ga', 'username')) self.__password = str(cg.getvalue('FtpServer-ga', 'password')) elif dw == 'zf': self.__hostname = cg.getvalue('FtpServer-zf', 'host') self.__port = int(cg.getvalue('FtpServer-zf', 'port')) self.__username = cg.getvalue('FtpServer-zf', 'username') self.__password = cg.getvalue('FtpServer-zf', 'password') else: logger.info("该单位未配置ftp服务器")
class InfoPart(object): results = ReadConfig().get_config() '''TestMode''' # 控制执行的case suit r_mode = results['TestMode'] test_mode = eval(r_mode['test_mode']) ddt_sheet_name = r_mode['ddt_sheet_name'] '''HttpConfig''' # 接口的url r_url = results['HttpConfig'] url = eval(r_url['url']) '''DBConfig''' # db配置信息 r_db = results['DBConfig'] db_info = eval(r_db['db_info']) '''TestDataConfig''' # test_data相关文件的配置信息 r_data = results['TestDataConfig'] # 存储测试数据的文件名 excel_name = r_data['excel_name'] # 测试数据的路径 test_data_path = path_joint(r_data['test_data_path'], excel_name) # 测试数据中的表名 sheet_name = eval(r_data['sheet_name']) '''RunCaseConfig''' r_run = results['RunCaseConfig'] # 运行指定case的配置,mode=all_run("all_run":全部跑;"part":跑部分,通过run_list确定) mode = r_run['mode'] run_list = eval(r_run['run_list']) '''TestResultConfig''' r_report = results['TestResultConfig'] # 测试结果的存储路径 test_result_path = path_joint(r_report['test_result_path']) log_path = path_joint(r_report['log_path']) report_path = path_joint(r_report['report_path']) '''获取cookie''' r_cookie = results['GetCookies'] home_page = r_cookie['home_page'] user_name = r_cookie['user_name'] passwd = r_cookie['passwd'] cookie = r_cookie['cookie']
# coding utf-8 # @time :2019/3/1816:59 # @Author :zjunbin # @Email :[email protected] # @File :myloger1.py import logging from common.readconfig import ReadConfig from common import constants import time mylog = logging.Logger('mylog') mylog.setLevel('DEBUG') mylog.setLevel(ReadConfig().get('testconfig', 'log_level')) # log_path 日志的存放路径和文件名称 log_path = constants.log_path filename = log_path + time.strftime('%Y%m%d', time.localtime(time.time())) fh = logging.FileHandler(filename, 'a+', encoding='utf-8') # 获取配置文件中的文件日志输出级别 fh.setLevel(ReadConfig().get('testconfig', 'fh_level')) # 获取配置文件中的日志输出格式 formatter = logging.Formatter(ReadConfig().get('testconfig', 'Formatter')) fh.setFormatter(formatter) # 对接日志收集器 mylog.addHandler(fh)
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import os from common.readconfig import ReadConfig # 项目目录 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # 日志目录 LOG_PATH = os.path.join(BASE_DIR, 'log') # 测试日志 AIRTEST_LOG = os.path.join(BASE_DIR, 'log', 'airtest') # report_path REPORT_PATH = os.path.join(BASE_DIR, "report") apps = {'zhixue': os.path.join(BASE_DIR, 'zhixue')} # config.ini ini = {'zhixue': ReadConfig(os.path.join(apps['zhixue'], 'config.ini'))} # 页面数据 elements = {'zhixue': os.path.join(BASE_DIR, 'zhixue', 'element')} # airtest_img airImg = {'zhixue': os.path.join(BASE_DIR, 'zhixue', 'images')} if __name__ == '__main__': print(ini['zhixue'].package_name)
def __init__(self): self.log_formatter = ReadConfig().log_formatter() self.log_level = ReadConfig().log_level()
def __init__(self): self.readconfig = ReadConfig() self.driver = webdriver.Chrome() self.action = ActionChains(self.driver)
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import os from common.readconfig import ReadConfig # 项目目录 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # 日志目录 LOG_PATH = os.path.join(BASE_DIR, 'log') # 测试日志 AIRTEST_LOG = os.path.join(BASE_DIR, 'log', 'airtest') # report_path REPORT_PATH = os.path.join(BASE_DIR, "report") apps = {'heyolx': os.path.join(BASE_DIR, 'heyolx')} # config.ini ini = {'heyolx': ReadConfig(os.path.join(apps['heyolx'], 'config.ini'))} # 页面数据 elements = {'heyolx': os.path.join(BASE_DIR, 'heyolx', 'element')} # airtest_img airImg = {'heyolx': os.path.join(BASE_DIR, 'heyolx', 'images')} if __name__ == '__main__': print(ini['heyolx'].package_name)
def path_joint(*path): base_path = ReadConfig().base_path return os.path.join(base_path, *path)
def get_file_path(self): cg = ReadConfig() return cg.getvalue('localPath', 'path')
# - * - coding:utf-8 - * - import os from common.readconfig import ReadConfig pro_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.ini") read_config = ReadConfig(pro_path) project_path = read_config.getValue("Project", "project_path") # log日志路径 log_path = os.path.join(project_path, "log") #接口测试路径 test_path = os.path.join(project_path, "tests") # 请求超时 timeout = read_config.getValue("Project", "request_timeout")
import pymysql from common.readconfig import ReadConfig # dbinfo = { # "host": "172.30.3.232", # "user": "******", # "password": "******", # "port": 1521 # } dbinfo = eval(ReadConfig().get_db("dbinfo")) # pymysql.connect('172.30.3.232','srmuat','Qy_srmuat', 1521) class DbConnect(): def __init__(self, db_conf, database=""): self.db_conf = db_conf # 打开数据库 self.db = pymysql.connect(database=database, cursorclass=pymysql.cursors.DictCursor, **db_conf) # 使用cursor()方式获取操作游标 self.cursor = self.db.cursor() def select(self, sql): # sql查询 self.cursor.execute(sql) # 执行sql results = self.cursor.fetchall() return results # def execute(self, sql): # sql 删除 提示 修改 try:
#coding=utf-8 import os from common.readconfig import ReadConfig # 读取配置文件 config_file_path = os.path.split(os.path.realpath(__file__))[0] # print("config_file_path:",config_file_path) read_config = ReadConfig(os.path.join(config_file_path, 'config.ini')) # print("read_config:",read_config) # 项目参数设置 prj_path = read_config.getValue('projectConfig', 'project_path') # print("prj_path:",prj_path) # 日志路径 log_path = os.path.join(prj_path, 'report', 'log') # print("log-path:",log_path) # 截图文件路径 img_path = os.path.join(prj_path, 'report', 'image') # print("img_path:",img_path) # 测试报告路径 report_path = os.path.join(prj_path, 'report', 'testreport') # print("report_path:",report_path) # 默认浏览器 yaml_path = os.path.join(prj_path, 'pages', 'pageelements') # print(yaml_path) browser = 'chrome' # 测试数据路径 data_path = os.path.join(prj_path, 'data', 'testdata') # print("data-path:",data_path)