def test_auth_GetNodeList(self, data): """获取游戏列表""" r = requests.post(MyYaml().config('url') + data.url, data.datas, timeout=MyYaml().config('timeout'), stream=True) time1 = r.elapsed.total_seconds() self.result = r.json() try: self.assertEqual(self.result['status'], eval(data.expected)['status'], msg="预期结果与实际不符") if self.result['status'] == 0: # self.assertEqual(self.result['data'], (not None), msg='data为空') readExcel().write_xls('case_xy_huawei.xlsx', 'GetNodeList', int(data.id) + 1, str(self.result), 'pass') log.info('用例执行成功') else: log.error('用例执行失败') readExcel().write_xls('case_xy_huawei.xlsx', 'GetNodeList', int(data.id) + 1, str(self.result), 'faled') except: readExcel().write_xls('case_xy_huawei.xlsx', 'GetNodeList', int(data.id), str(self.result), 'faled') log.error('用例支持失败,回写成功') print(time1)
def __init__(self, **kwargs): self.kwargs = kwargs self.ip = yaml.mysql('ip') self.username = yaml.mysql('username') self.pwd = yaml.mysql('pwd') self.TESTDB = yaml.mysql('TESTDB') self.real_sql = yaml.sql('search_results') self.redis_ip = MyYaml().config('redis_ip') self.redis_port = MyYaml().config('port') self.name = MyYaml().config('redis')
def __init__(self): redis_ip = MyYaml().config('redis_ip') redis_port = MyYaml().config('port') pool = redis.ConnectionPool(host=redis_ip, port=redis_port, decode_responses=True, db=0) self.r = redis.Redis(connection_pool=pool) # Loging().info('链接redis成功') self.env = MyYaml().config('env') self.log = Loging()
def test_auth_GetGameList(self): """获取游戏列表""" if case_name == 5: self.data[1]['openID1'] = 'dsgdsgsdg' #需要改变的参数 r = requests.post(self.url, self.data[1], timeout=MyYaml().config('timeout'), stream=True) self.result = r.json() time1 = r.elapsed.total_seconds() self.data[-1] = time1
def case_id(self, className): case_ids = [] for a, b in MyYaml().interface_data.items(): for c in b: if c['className'] in className: for d in c['funName']: for e, f in d.items(): case_ids.append(e) return case_ids #方法名
def test_auth_GetNodeList(self): """获取游戏列表""" r = requests.post(self.url, self.data[1], timeout=MyYaml().config('timeout'), stream=True) self.result = r.json() time1 = r.elapsed.total_seconds() self.data[-1] = time1
def test_auth_GetNodeList(self, data): r = requests.post(MyYaml().config('url') + data.url, data.datas) self.result = r.json() time1 = r.elapsed.total_seconds() print('接口响应时间:' + str(time1)) log.info('第{}条用例执行'.format(data.id)) log.info('用例名称:{}'.format(data.name)) log.info('接口响应时间为:{}'.format(time1)) print(self.result) self.assertEqual(eval(data.expected)['status'], self.result['status'])
def case_data(self, className_list): all_fun_data = [] #所有测试用例的数据 for a, b in MyYaml().interface_data.items(): #返回一个元组对列表 items() for c in b: if c['className'] in className_list: for d in c['funName']: for e, f in d.items(): f['url'] = c['url'] if {e: f} not in all_fun_data: all_fun_data.append({e: f}) return all_fun_data
def moudle_name(): """ 获取可运行模块 :return: moudle list """ moudleName = MyYaml().config('moudleName') project_names = os.path.join(path, '{}'.format(self.projectName)) dir_list = os.listdir( project_names ) #os.listdir(project_names):列出paoject_names下的目录和文件 moudle_list = [] #一级目录, XY all_import_class = [] #所有要导入的测试类 all_moudle = [] #所有的类名 if moudleName is None: #运行所有模块 for i in dir_list: if '.' not in i and '__' not in i: if os.path.exists( project_names + '/{}/__init__.py'.format(i)): #判断路径是否存在 moudle_list.append(i) else: if os.path.exists( project_names + '/{}/__init__.py'.format(moudleName)): #运行指定模块 moudle_list.append(moudleName) for a in moudle_list: #模块 dir_name = project_names + '\\' + a dir_list = os.listdir( dir_name) #os.listdir()用于返回指定文件夹中包含的文件或文件夹列表 for b in dir_list: if self.matching.split('_')[1] in b: #筛选出测试用例 import_name = '{}_{}'.format(b.split('_')[0], a) #类名 all_import_class.append('from.{}.{} import {}'.format( a, b.split('.')[0], import_name)) #所有要导入的测试类 all_import_class.append('\n') all_moudle.append(import_name) init_file_py = project_names + '/__init__.py' if os.path.exists( init_file_py ): #os.path.exists(init_file_py):判断是否存在文件或目录init_file_py os.remove(init_file_py) #os.remove(file):删除一个文件 all_moudle = str(all_moudle) #类名 import re all_moudle = re.sub("'", '', all_moudle) #sub():替换 with open(init_file_py, 'w') as f: #测试类写入__init__.py文件 f.writelines(all_import_class) f.write('moudle_list = {}'.format(all_moudle)) f.write('\n') f.close() return all_moudle, moudle_list #all_moudle=所有类名(模块),moudle_list=ZY包下的所有包
def dmp_data(self): json_data = MyYaml().baseData('data') data = self.r.lrange('{}_dmp'.format(self.env), 0, -1) #返回所有元素 all_cases = [] right_cases = [] fail_cases = [] error_cases = [] untreaded_cases = [] fail_error_cases = [] timeout_cases = [] if len(data) >= 1: for i in data: json_load = json.loads(i) for a in json_load['report_cases']['all_cases']: if a not in all_cases: all_cases.append(a) for b in json_load['report_cases']['right_cases']: if b not in right_cases: right_cases.append(b) for c in json_load['report_cases']['fail_cases']: if c not in fail_cases: fail_cases.append(c) for d in json_load['report_cases']['error_cases']: if d not in error_cases: error_cases.append(d) for e in json_load['report_cases']['untreaded_cases']: if e not in untreaded_cases: untreaded_cases.append(e) for f in json_load['report_cases']['fail_error_cases']: if f not in fail_error_cases: fail_error_cases.append(f) for g in json_load['report_cases']['timeout_cases']: if g not in timeout_cases: timeout_cases.append(g) json_data['report_cases']['all_cases'] = all_cases json_data['report_cases']['right_cases'] = right_cases json_data['report_cases']['fail_cases'] = fail_cases json_data['report_cases']['error_cases'] = error_cases json_data['report_cases']['untreaded_cases'] = untreaded_cases json_data['report_cases']['fail_error_cases'] = fail_error_cases json_data['report_cases']['timeout_cases'] = timeout_cases return json_data, all_cases, right_cases, fail_cases, \ error_cases, untreaded_cases, fail_error_cases, timeout_cases else: return data
def run_class(self): from Case import moudle_list redis.all_module(moudle_list) #存进redis #创建新线程 count = 0 numbers = 0 if len(redis.read_moudle('all_module')) != 0: #计算长度,len长度,所有的测试用例多少个 while True: #循环 log.info('共计{}个测试类'.format(len( redis.read_moudle('all_module')))) if len(redis.read_moudle('all_module')) != 0: threads = [] log.info('添加线程') try: moudle = redis.rpop('all_module', MyYaml().config('thread_count')) moudle_per = ReadYaml().return_module( moudle_list, moudle) for i in moudle_per: threads.append( myThread(count, "Thread-{}".format(count), i, 0)) #一次性开启的线程数量 count += 1 except Exception: pass #开启新线程 for i in threads: try: i.start() #start开启线程 except Exception: pass #等待所有线程完成 for t in threads: try: t.join() #等待线程、子线程完毕后关闭主线程 except Exception: pass log.info('主进程{}结束'.format(numbers)) numbers += 1 #主进程 else: log.info('所有主进程结束!') break else: log.info('测试集为空')
def return_data(self): try: token = read_ini(node='session', child='token') #从配置文件获取token # print(token) except Exception: token = '0' headers = {'token': token} key = self.className.split('_')[1] datas = MyYaml().interface_data[key] data = [] for i in datas: if i['className'] == self.className: data.append(i['url']) # 0 for j in i['funName']: for k in j.keys(): if k == self.case_info: data.append(j[self.case_info]['bar']) #参数 1 data.append(j[self.case_info]['result']) #预期结果 2 data.append(j[self.case_info]['test_data']) #预期结果 3 # print(data[0],data[1],data[2],data[3]) return token, headers, data
def __init__(self): self.url = MyYaml().reptile('url') self.url2 = MyYaml().reptile("url2") self.path = os.path.join(getpath(), 'my_reptile', 'result', MyYaml().reptile('file')) self.re = MyYaml().reptile("matching")
import requests import redis from write_readini import write_ini from write_readini import read_ini from read_writeyaml import MyYaml import os from configpath import getpath path = getpath() projectName = MyYaml().config('projectName') matching = MyYaml().config('matching') # url = "http://twork.zhanye.wallet.openapi.youxin.info:42981" # urladdress = "http://twork.zhanye.wallet.openapi.youxin.info:42981/v1/access_token" # payload = { # 'account': '637A5A9B-13B6-0C9A-D878-A33FE2D988CF', # 'pass': '******' # } # r = requests.post(urladdress, params=payload) # result = r.json() #print(result['token']) #写入ini文件 # write_ini(node='session', child='tokennn', content=result['token']) #读取ini文件 # tokk = read_ini(node='session', child='tokennn') # print(tokk) # a = matching.split('_') # print(a) # # moudleName = MyYaml().config('moudleName')
def __init__(self): self.log_url = MyYaml().config('url') self.log_dress = MyYaml().config('dress')
import time import logging import os import sys from read_writeyaml import MyYaml import configpath yaml = MyYaml() class Loging: """日志""" def __init__(self, level=yaml.log('level'), logger_name='hsc'): self.logger = logging.getLogger( logger_name) # # 获取logger实例,如果参数为空则返回root logger、创建一个logger if not self.logger.handlers: formatter = logging.Formatter( # 指定logger输出格式 '时间:%(asctime)s ' # 时间,默认精确到毫秒 # '文件名:%(filename)s ' # 日志文件名 # '模块名:%(module)s ' #日志模块名 # '方法:%(funcName)s ' # 日志函数名 # '代码行:%(lineno)d ' # 日志模块代码行 '级别:%(levelname) s ' # log级别 # '路径:%(pathname)s ' # 完整路径 '消息:%(message)s' # 打印的消息 ) current_data = time.strftime('%Y-%m-%d', time.localtime(time.time())) # 当前系统日期 log_name = '{}.log'.format(current_data) # 每天一份日志 log_file = os.path.join(configpath.getpath(), 'logs/{}'.format(log_name)) # log路径
def results_collected(self): """ 结果收集 :return: """ all_cases = [] all_times = [] timeout_cases = [] right_cases = [] fail_cases = [] fail_error_cases = [] right_fail_cases = [] error_cases = [] skip_cases = [] case_infos_list = redis.rpop( 'case_data') #移除返回右边最后一个元素,lpop删除返回左边列表第一个,(测试用例数据) case_errors_list = redis.rpop('case_errors') case_failures_list = redis.rpop('case_failures') case_skipped_list = redis.rpop('case_skipped') all_test_fun = ReadYaml().case_info_data(self.all_moudle) for case_ins in all_test_fun: case_info = { 'case_name': case_ins[1]['case_name'], 'mode': case_ins[1]['mode'], 'api_url': case_ins[1]['url'], 'time': 0, 'statues': '', 'info': '' } for e in case_failures_list: e = list(eval(e)) #列表转换 , eval if case_ins[0] == e[0]: case_info['statues'] = 'fail' break for f in case_errors_list: f = list(eval(f)) if case_ins[0] == f[0]: case_info['statues'] = 'error' case_info['info'] = f[1] break for h in case_skipped_list: if case_ins[0] == h[0]: case_info['statues'] = 'skip' case_info['info'] = h[1] # 'No Response' break if case_info['statues'] == '': case_info['statues'] = 'pass' for i in case_infos_list: i = list(eval(i)) if i[0] == case_ins[0]: if case_info['statues'] == 'pass': case_info['info'] = i[1] try: json_data = float(json.loads(i[1])['time_count']) except Exception: json_data = 0 case_info['time'] = float('%.2f' % json_data) all_times.append(json_data) elif case_info['statues'] == 'fail': case_info['info'] = i[1] try: json_data = float(json.loads(i[1])['time_count']) except Exception: json_data = 0 case_info['time'] = float('%.2f' % json_data) all_times.append(json_data) else: break case_infos = [ self.projectName, case_ins[0], case_info['case_name'], case_info['api_url'], case_info['mode'], case_info['time'], # 11-23 case_info['statues'], '详细', case_info['info'], ] all_cases.append(case_infos) for g in all_cases: if g[-3] == 'pass': right_cases.append(g) right_fail_cases.append(g) elif g[-3] == 'fail': fail_cases.append(g) fail_error_cases.append(g) right_fail_cases.append(g) elif g[-3] == 'error': error_cases.append(g) fail_error_cases.append(g) else: skip_cases.append(g) for timeout in right_fail_cases: if timeout[-4] > self.timeout: timeout_cases.append(timeout) dmps = MyYaml().baseData('report_cases') dmps['all_cases'] = all_cases dmps['right_cases'] = right_cases dmps['fail_cases'] = fail_cases dmps['error_cases'] = error_cases dmps['untreaded_cases'] = skip_cases fail_error_cases.sort(key=lambda x: (x[5]), reverse=True) dmps['fail_error_cases'] = fail_error_cases timeout_cases.sort(key=lambda x: (x[5]), reverse=True) dmps['timeout_cases'] = timeout_cases return dmps, all_times
def __init__(self): self.url = MyYaml().reptile('url') self.matching = MyYaml().reptile('matching') self.path_images = os.path.join(getpath(), 'images') self.path_file = os.path.join(getpath(), 'Py_file', 'test.txt') self.method = MyYaml().reptile('method')
class AllResult(object): """所有执行结果""" def __init__(self): redis.remove_redis([ 'all_module', 'case_data', 'case_failures', 'case_errors', #删除数据 'case_skipped', ]) self.timeout = MyYaml().config('timeout') self.projectName = MyYaml().config('projectName') self.EnvName = MyYaml().config('EnvName') #生产环境 self.moudleName = MyYaml().config('moudleName') # all if self.moudleName is None: self.moudleName = '' self.matching = MyYaml().config('matching') #正则 self.ip = MyYaml().config('ip') self.matching = MyYaml().config('matching') #正则表达式匹配*_st.py self.ip = MyYaml().config('ip') # ip: 192.168.8.1 self.domain = MyYaml().config('domain') #本地测试环境 self.app_config = MyYaml().interface_data #获取接口数据 if self.domain is None: self.get_url = 'http://{}/polls/get_report/'.format(self.ip) else: self.get_url = 'http://{}/polls/get_report/'.format(self.domain) self.message = MyYaml().config('message') def moudle_name(): """ 获取可运行模块 :return: moudle list """ moudleName = MyYaml().config('moudleName') project_names = os.path.join(path, '{}'.format(self.projectName)) dir_list = os.listdir( project_names ) #os.listdir(project_names):列出paoject_names下的目录和文件 moudle_list = [] #一级目录, XY all_import_class = [] #所有要导入的测试类 all_moudle = [] #所有的类名 if moudleName is None: #运行所有模块 for i in dir_list: if '.' not in i and '__' not in i: if os.path.exists( project_names + '/{}/__init__.py'.format(i)): #判断路径是否存在 moudle_list.append(i) else: if os.path.exists( project_names + '/{}/__init__.py'.format(moudleName)): #运行指定模块 moudle_list.append(moudleName) for a in moudle_list: #模块 dir_name = project_names + '\\' + a dir_list = os.listdir( dir_name) #os.listdir()用于返回指定文件夹中包含的文件或文件夹列表 for b in dir_list: if self.matching.split('_')[1] in b: #筛选出测试用例 import_name = '{}_{}'.format(b.split('_')[0], a) #类名 all_import_class.append('from.{}.{} import {}'.format( a, b.split('.')[0], import_name)) #所有要导入的测试类 all_import_class.append('\n') all_moudle.append(import_name) init_file_py = project_names + '/__init__.py' if os.path.exists( init_file_py ): #os.path.exists(init_file_py):判断是否存在文件或目录init_file_py os.remove(init_file_py) #os.remove(file):删除一个文件 all_moudle = str(all_moudle) #类名 import re all_moudle = re.sub("'", '', all_moudle) #sub():替换 with open(init_file_py, 'w') as f: #测试类写入__init__.py文件 f.writelines(all_import_class) f.write('moudle_list = {}'.format(all_moudle)) f.write('\n') f.close() return all_moudle, moudle_list #all_moudle=所有类名(模块),moudle_list=ZY包下的所有包 self.all_moudle, self.moudle_list = moudle_name() #调用并赋值 def run_class(self): from Case import moudle_list redis.all_module(moudle_list) #存进redis #创建新线程 count = 0 numbers = 0 if len(redis.read_moudle('all_module')) != 0: #计算长度,len长度,所有的测试用例多少个 while True: #循环 log.info('共计{}个测试类'.format(len( redis.read_moudle('all_module')))) if len(redis.read_moudle('all_module')) != 0: threads = [] log.info('添加线程') try: moudle = redis.rpop('all_module', MyYaml().config('thread_count')) moudle_per = ReadYaml().return_module( moudle_list, moudle) for i in moudle_per: threads.append( myThread(count, "Thread-{}".format(count), i, 0)) #一次性开启的线程数量 count += 1 except Exception: pass #开启新线程 for i in threads: try: i.start() #start开启线程 except Exception: pass #等待所有线程完成 for t in threads: try: t.join() #等待线程、子线程完毕后关闭主线程 except Exception: pass log.info('主进程{}结束'.format(numbers)) numbers += 1 #主进程 else: log.info('所有主进程结束!') break else: log.info('测试集为空') def results_collected(self): """ 结果收集 :return: """ all_cases = [] all_times = [] timeout_cases = [] right_cases = [] fail_cases = [] fail_error_cases = [] right_fail_cases = [] error_cases = [] skip_cases = [] case_infos_list = redis.rpop( 'case_data') #移除返回右边最后一个元素,lpop删除返回左边列表第一个,(测试用例数据) case_errors_list = redis.rpop('case_errors') case_failures_list = redis.rpop('case_failures') case_skipped_list = redis.rpop('case_skipped') all_test_fun = ReadYaml().case_info_data(self.all_moudle) for case_ins in all_test_fun: case_info = { 'case_name': case_ins[1]['case_name'], 'mode': case_ins[1]['mode'], 'api_url': case_ins[1]['url'], 'time': 0, 'statues': '', 'info': '' } for e in case_failures_list: e = list(eval(e)) #列表转换 , eval if case_ins[0] == e[0]: case_info['statues'] = 'fail' break for f in case_errors_list: f = list(eval(f)) if case_ins[0] == f[0]: case_info['statues'] = 'error' case_info['info'] = f[1] break for h in case_skipped_list: if case_ins[0] == h[0]: case_info['statues'] = 'skip' case_info['info'] = h[1] # 'No Response' break if case_info['statues'] == '': case_info['statues'] = 'pass' for i in case_infos_list: i = list(eval(i)) if i[0] == case_ins[0]: if case_info['statues'] == 'pass': case_info['info'] = i[1] try: json_data = float(json.loads(i[1])['time_count']) except Exception: json_data = 0 case_info['time'] = float('%.2f' % json_data) all_times.append(json_data) elif case_info['statues'] == 'fail': case_info['info'] = i[1] try: json_data = float(json.loads(i[1])['time_count']) except Exception: json_data = 0 case_info['time'] = float('%.2f' % json_data) all_times.append(json_data) else: break case_infos = [ self.projectName, case_ins[0], case_info['case_name'], case_info['api_url'], case_info['mode'], case_info['time'], # 11-23 case_info['statues'], '详细', case_info['info'], ] all_cases.append(case_infos) for g in all_cases: if g[-3] == 'pass': right_cases.append(g) right_fail_cases.append(g) elif g[-3] == 'fail': fail_cases.append(g) fail_error_cases.append(g) right_fail_cases.append(g) elif g[-3] == 'error': error_cases.append(g) fail_error_cases.append(g) else: skip_cases.append(g) for timeout in right_fail_cases: if timeout[-4] > self.timeout: timeout_cases.append(timeout) dmps = MyYaml().baseData('report_cases') dmps['all_cases'] = all_cases dmps['right_cases'] = right_cases dmps['fail_cases'] = fail_cases dmps['error_cases'] = error_cases dmps['untreaded_cases'] = skip_cases fail_error_cases.sort(key=lambda x: (x[5]), reverse=True) dmps['fail_error_cases'] = fail_error_cases timeout_cases.sort(key=lambda x: (x[5]), reverse=True) dmps['timeout_cases'] = timeout_cases return dmps, all_times def run_all_case(self): now_time = time.strftime( '%Y-%m-%d %H:%M:%S') #获取时间并转换为易读格式time.strftime log.debug('now_time:{}'.format(now_time)) startTime = time.time() self.run_class() # 运行所有模块 stopTime = time.time() timeTaken = '%d秒' % (stopTime - startTime) end_time = time.strftime('%Y-%m-%d %H:%M:%S') dmps, all_times = self.results_collected() # 收集结果 try: max_times = '%.2f' % max(all_times) except Exception as msg: max_times = '0' log.debug(msg) try: aver_time = '%.2f' % (sum(all_times) / len(all_times)) except Exception as msg: aver_time = '0' log.debug(msg) try: min_time = '%.2f' % min(all_times) except Exception as msg: min_time = '0' log.debug(msg) test_info = [ now_time, end_time, timeTaken, max_times, aver_time, min_time, ] dmps['test_info'] = test_info dmps['env_sign'] = self.EnvName
def __init__(self): redis.remove_redis([ #新一轮测试前删除redis缓存数据 'all_module', 'case_data', 'case_failures', 'case_errors', #删除数据 'case_skipped', ]) self.timeout = MyYaml().config('timeout') self.projectName = MyYaml().config('projectName') self.EnvName = MyYaml().config('EnvName') #测试环境 self.moudleName = MyYaml().config('moudleName') # all if self.moudleName is None: self.moudleName = '' self.matching = MyYaml().config('matching') #正则 # self.ip = MyYaml().config('ip') # self.domain = MyYaml().config('domain') #本地测试环境 # self.app_config = MyYaml().interface_data # if self.domain is None: # self.get_url = 'http://{}/polls/get_report/'.format(self.ip) # else: # self.get_url = 'http://{}/polls/get_report/'.format(self.domain) # self.message = MyYaml().config('message') def moudle_name(): """ 获取可运行模块 :return: moudle list """ moudleName = MyYaml().config('moudleName') project_names = os.path.join(path, '{}'.format(self.projectName)) dir_list = os.listdir(project_names) #os.listdir(project_names):列出paoject_names下的目录和文件 moudle_list = [] #一级目录 all_import_class = [] #所有要导入的测试类 all_moudle = [] if moudleName is None: for i in dir_list: if '.' not in i and '__' not in i: if os.path.exists(project_names + '/{}/__init__.py'.format(i)): moudle_list.append(i) else: if os.path.exists(project_names + '/{}/__init__.py'.format(moudleName)): moudle_list.append(moudleName) for a in moudle_list: dir_name = project_names + '\\' + a dir_list = os.listdir(dir_name) for b in dir_list: if self.matching.split('_')[1] in b: import_name = '{}_{}'.format(b.split('_')[0], a) all_import_class.append('from.{}.{} import {}'.format(a, b.split('.')[0], import_name)) all_import_class.append('\n') all_moudle.append(import_name) init_file_py = project_names + '/__init__.py' if os.path.exists(init_file_py): #os.path.exists(init_file_py):判断是否存在文件或目录init_file_py os.remove(init_file_py) #os.remove(file):删除一个文件 all_moudle = str(all_moudle) import re all_moudle = re.sub("'", '', all_moudle) #sub():替换 with open(init_file_py, 'w') as f: f.writelines(all_import_class) f.write('moudle_list = {}'.format(all_moudle)) f.write('\n') f.close() return all_moudle, moudle_list #all_moudle=所有类名(模块),moudle_list=case包下的所有包 self.all_moudle, self.moudle_list = moudle_name()
def __init__(self): redis.remove_redis([ 'all_module', 'case_data', 'case_failures', 'case_errors', #删除数据 'case_skipped', ]) self.timeout = MyYaml().config('timeout') self.projectName = MyYaml().config('projectName') self.EnvName = MyYaml().config('EnvName') #生产环境 self.moudleName = MyYaml().config('moudleName') # all if self.moudleName is None: self.moudleName = '' self.matching = MyYaml().config('matching') #正则 self.ip = MyYaml().config('ip') self.matching = MyYaml().config('matching') #正则表达式匹配*_st.py self.ip = MyYaml().config('ip') # ip: 192.168.8.1 self.domain = MyYaml().config('domain') #本地测试环境 self.app_config = MyYaml().interface_data #获取接口数据 if self.domain is None: self.get_url = 'http://{}/polls/get_report/'.format(self.ip) else: self.get_url = 'http://{}/polls/get_report/'.format(self.domain) self.message = MyYaml().config('message') def moudle_name(): """ 获取可运行模块 :return: moudle list """ moudleName = MyYaml().config('moudleName') project_names = os.path.join(path, '{}'.format(self.projectName)) dir_list = os.listdir( project_names ) #os.listdir(project_names):列出paoject_names下的目录和文件 moudle_list = [] #一级目录, XY all_import_class = [] #所有要导入的测试类 all_moudle = [] #所有的类名 if moudleName is None: #运行所有模块 for i in dir_list: if '.' not in i and '__' not in i: if os.path.exists( project_names + '/{}/__init__.py'.format(i)): #判断路径是否存在 moudle_list.append(i) else: if os.path.exists( project_names + '/{}/__init__.py'.format(moudleName)): #运行指定模块 moudle_list.append(moudleName) for a in moudle_list: #模块 dir_name = project_names + '\\' + a dir_list = os.listdir( dir_name) #os.listdir()用于返回指定文件夹中包含的文件或文件夹列表 for b in dir_list: if self.matching.split('_')[1] in b: #筛选出测试用例 import_name = '{}_{}'.format(b.split('_')[0], a) #类名 all_import_class.append('from.{}.{} import {}'.format( a, b.split('.')[0], import_name)) #所有要导入的测试类 all_import_class.append('\n') all_moudle.append(import_name) init_file_py = project_names + '/__init__.py' if os.path.exists( init_file_py ): #os.path.exists(init_file_py):判断是否存在文件或目录init_file_py os.remove(init_file_py) #os.remove(file):删除一个文件 all_moudle = str(all_moudle) #类名 import re all_moudle = re.sub("'", '', all_moudle) #sub():替换 with open(init_file_py, 'w') as f: #测试类写入__init__.py文件 f.writelines(all_import_class) f.write('moudle_list = {}'.format(all_moudle)) f.write('\n') f.close() return all_moudle, moudle_list #all_moudle=所有类名(模块),moudle_list=ZY包下的所有包 self.all_moudle, self.moudle_list = moudle_name() #调用并赋值
import urllib.request from configpath import getpath import re import chardet import os from read_writeyaml import MyYaml path = os.path.join(getpath(), 'images') page = urllib.request.urlopen(MyYaml().reptile('url')) htmlCode = page.read() #获取网页源代码 print(chardet.detect(htmlCode)) #打印返回网页的编码方式 # print(htmlCode.decode('utf-8')) #打印网页源代码 data = htmlCode.decode('utf-8') # pageFile = open('pageCode.txt', 'wb')#以写的方式打开pageCode.txt # pageFile.write(htmlCode)#写入 # pageFile.close()#开了记得关 reg = MyYaml().reptile('matching')#正则表达式 ,,匹配以src="开头然后接一个或多个任意字符(非贪婪),以.jpg" 结尾的字符串 reg_img = re.compile(reg)#编译一下,运行更快 imglist = reg_img.findall(data)#进行匹配 x = 0 for img in imglist: print(img) urllib.request.urlretrieve('%s' % img, '%s\\%s.jpg' % (path, x)) #路径加文件名,保存在指定文件夹下 x += 1
class AllResult(object): """所有执行结果""" def __init__(self): redis.remove_redis([ #新一轮测试前删除redis缓存数据 'all_module', 'case_data', 'case_failures', 'case_errors', #删除数据 'case_skipped', ]) self.timeout = MyYaml().config('timeout') self.projectName = MyYaml().config('projectName') self.EnvName = MyYaml().config('EnvName') #测试环境 self.moudleName = MyYaml().config('moudleName') # all if self.moudleName is None: self.moudleName = '' self.matching = MyYaml().config('matching') #正则 # self.ip = MyYaml().config('ip') # self.domain = MyYaml().config('domain') #本地测试环境 # self.app_config = MyYaml().interface_data # if self.domain is None: # self.get_url = 'http://{}/polls/get_report/'.format(self.ip) # else: # self.get_url = 'http://{}/polls/get_report/'.format(self.domain) # self.message = MyYaml().config('message') def moudle_name(): """ 获取可运行模块 :return: moudle list """ moudleName = MyYaml().config('moudleName') project_names = os.path.join(path, '{}'.format(self.projectName)) dir_list = os.listdir(project_names) #os.listdir(project_names):列出paoject_names下的目录和文件 moudle_list = [] #一级目录 all_import_class = [] #所有要导入的测试类 all_moudle = [] if moudleName is None: for i in dir_list: if '.' not in i and '__' not in i: if os.path.exists(project_names + '/{}/__init__.py'.format(i)): moudle_list.append(i) else: if os.path.exists(project_names + '/{}/__init__.py'.format(moudleName)): moudle_list.append(moudleName) for a in moudle_list: dir_name = project_names + '\\' + a dir_list = os.listdir(dir_name) for b in dir_list: if self.matching.split('_')[1] in b: import_name = '{}_{}'.format(b.split('_')[0], a) all_import_class.append('from.{}.{} import {}'.format(a, b.split('.')[0], import_name)) all_import_class.append('\n') all_moudle.append(import_name) init_file_py = project_names + '/__init__.py' if os.path.exists(init_file_py): #os.path.exists(init_file_py):判断是否存在文件或目录init_file_py os.remove(init_file_py) #os.remove(file):删除一个文件 all_moudle = str(all_moudle) import re all_moudle = re.sub("'", '', all_moudle) #sub():替换 with open(init_file_py, 'w') as f: f.writelines(all_import_class) f.write('moudle_list = {}'.format(all_moudle)) f.write('\n') f.close() return all_moudle, moudle_list #all_moudle=所有类名(模块),moudle_list=case包下的所有包 self.all_moudle, self.moudle_list = moudle_name() def run_class(self): from case import moudle_list redis.all_module(moudle_list) #存进redis #创建新线程 count = 0 numbers = 0 if len(redis.read_moudle('all_module')) != 0: #计算长度,len长度 while True: #循环 log.info('共计{}个测试类'.format(len(redis.read_moudle('all_module')))) if len(redis.read_moudle('all_module')) != 0: threads = [] log.info('添加线程') try: moudle = redis.rpop('all_module', MyYaml().config('thread_count')) moudle_per = ReadYaml().return_module(moudle_list, moudle) for i in moudle_per: threads.append(myThread(count, "Thread-{}".format(count), i, 0)) count += 1 except Exception: pass #开启新线程 for i in threads: try: i.start() #start开启线程 except Exception: pass #等待所有线程完成 for t in threads: try: t.join() #等待线程、子线程完毕后关闭主线程 except Exception: pass log.info('主进行{}结束'.format(numbers)) numbers += 1 else: log.info('所有主进程结束!') break else: log.info('测试集为空') def run_all_case(self): now_time = time.strftime('%Y-%m-%d %H:%M:%S') log.debug('now_time:{}'.format(now_time)) self.run_class() # 运行所有模块