def getCasePro(self): """ 获取用例基本信息 :return: desc """ data_ini = GetDataIni(f"{root_path}{sep}conf{sep}data.ini") if self.projectName: self.projectName = data_ini.normal_data("Name", self.projectName) else: self.projectName = "None" return self.projectName, self.api_name, self.desc
def get_env_name_url_form(): dataIni = GetDataIni() method = request.method.lower() if method == "get": param = request.args.get("envId") else: param = str(request.form.get("envId")) if dataIni.cfgB.options("Env_name").__contains__(param): env_name = eval(dataIni.normal_data("Env_name", param))[-1] res = {"msg": True, "options": param, "env_name": env_name} else: res = {"msg": f"The <envId={param}> is invalid!"} response = json.dumps(res, ensure_ascii=False) return Response(response, mimetype="application/json")
def start(cases_dir, env, reg_str): if not env: sss["env"] = "prod" elif env and env.lower() in ["dev", "test", "pre", "prod"]: sss["env"] = env # 判断是否有指定用例文件夹 if cases_dir: project_dir = cases_dir # test_xxxx project_name = project_dir.split("test_")[-1] # xxxx # 获取指定项目 json 数据中的 robot_url 的地址 robot_url = get_project_robot_URL(project_name)[project_name]["robot_data"]["robot_url"] suites_dir = root_path + f'{sep}src{sep}testProject{sep}{project_dir}' else: # 这里需要补充测试组机器人URL robot_url = 'https://oapi.dingtalk.com/robot/send?access_token=d852c17cf61d26bfbaf8d0d8d4927632f9b1712cb9aa1' \ '45342159f8fd0065fc4' project_name = "All" suites_dir = root_path + f'{sep}src{sep}testProject' if not reg_str: reg_str = "*test.py" suites = unittest.defaultTestLoader.discover(start_dir=suites_dir, pattern=f'{reg_str}') # print(suite.countTestCases()) get_INI = GetDataIni() Name = get_INI.normal_data("Name", project_name) # 脚本运行当前时间 now = time.strftime("%Y_%m_%d-%H_%M_%S") now_day = time.strftime("%Y_%m_%d") # 根据执行用例项目参数给测试报告命名 reportFileName = f'{project_name}' + f'_{now}_result.html' # 测试报告存放文件夹地址 # reportDirName = os.path.abspath(os.path.join(os.getcwd(), "..%s.." % sep)) + sep + 'output' + sep + 'report' + sep reportDirName = root_path + sep + 'output' + sep + 'report' + sep # 以天为维度生成对应文件夹 report_dir = 'report_{_now}'.format(_now=now_day) reportDir = reportDirName + report_dir while not os.path.exists(reportDir): try: os.makedirs(reportDir) break except OSError as e: if e.errno != os.errno.EEXIST: raise # time.sleep might help here pass # 根据第三方库 BeautifulReport 执行用例并生成报告 with open(reportDir + sep + reportFileName, "wb"): beaRep = BeautifulReport(suites) res = beaRep.report(filename=reportFileName, description=f'{Name}项目 {env} 环境接口自动化测试报告', report_dir=reportDir) result_dict = beaRep.stopTestRun() casesAll = result_dict.get("testAll") casesPass = result_dict.get("testPass") casesFail = result_dict.get("testFail") # casesError = result_dict.get("testError") casesSkip = result_dict.get("testSkip") if not casesSkip: _pass_rate = ("%.2f%%" % (casesPass / casesAll * 100)) else: _pass_rate = ("%.2f%%" % (casesPass / (casesAll - casesSkip) * 100)) sleep(3) _platform = platform.platform() if _platform == 'Linux-2.6.32-754.18.2.el6.x86_64-x86_64-with-centos-6.10-Final': ip = '10.0.6.56' link_url = "http://" + ip + f':8686{sep}report{sep}{report_dir}{sep}{reportFileName}' elif _platform.startswith("Windows") or _platform.startswith('Darwin'): # 获取本机计算机名称 hostname = socket.gethostname() # 获取本机ip ip = socket.gethostbyname(hostname) link_url = "http://" + ip + f':8686{sep}report{sep}{report_dir}{sep}{reportFileName}' robot_url = None else: ip = '10.50.255.253' output_dir = '/report/' link_url = "http://" + ip + f':1323{output_dir}{report_dir}{sep}{reportFileName}' if robot_url: send_link(robot_url, link_url, f'房多多接口自动化测试报告(通过率:{_pass_rate}) \n 用例总数:{casesAll}, ' f'通过:{casesPass},失败:{casesFail},跳过:{casesSkip}') return res
def start(cases_dir=None, env=None, reg_str=None): if not env: env = "prod" sss["env"] = env # 配置文件实例化 get_INI = GetDataIni() env_name = get_INI.normal_data("Env", env) sss["env_name"] = env_name if not reg_str: reg_str = "*test.py" # 新房项目列表 xf_list = ["test_ddxfapp", "test_shop", "test_shopapp", "test_commiss"] # 巡检测试群机器人地址 test_robot = 'https://oapi.dingtalk.com/robot/send?access_token=d852c17cf61d26bfbaf8d0d8d4927632f9b1712' \ 'cb9aa145342159f8fd0065fc4' # 判断项目是属于新房项目 if cases_dir in xf_list: project_dir = cases_dir # test_xxxx project_name = project_dir.split("test_")[-1] # xxxx # 获取指定项目 json 数据中的 robot_url 的地址 robot_url = [get_project_robot_URL(project_name)[project_name]["robot_data"]["robot_url"]] suites_dir = root_path + f'{sep}src{sep}testProject{sep}test_ddxf{sep}{project_dir}' # 判断项目是否是新房 elif cases_dir == "test_ddxf": robot_url = [] for i in xf_list: project_name = i.split("test_")[-1] robot_url.append(get_project_robot_URL(project_name)[project_name]["robot_data"]["robot_url"]) robot_url = list(set(robot_url)) # 去重处理 project_name = "ddxf" suites_dir = root_path + f'{sep}src{sep}testProject{sep}test_ddxf' # 判断是否是所有项目 elif not cases_dir or cases_dir == "ALL": # 这里需要补充测试组机器人URL robot_url = [test_robot] # robot_url = ['https://oapi.dingtalk.com/robot/send?access_token=d852c17cf61d26bfbaf8d0d8d4927632f9b1712cb9aa' # '145342159f8fd0065fc4'] project_name = "All" suites_dir = root_path + f'{sep}src{sep}testProject' # 指定普通单个项目 else: project_dir = cases_dir # test_xxxx project_name = project_dir.split("test_")[-1] # xxxx # 获取指定项目 json 数据中的 robot_url 的地址 robot_url = [get_project_robot_URL(project_name)[project_name]["robot_data"]["robot_url"]] suites_dir = root_path + f'{sep}src{sep}testProject{sep}{project_dir}' suites = unittest.defaultTestLoader.discover(start_dir=suites_dir, pattern=f'{reg_str}') # # print(suite.countTestCases()) Name = get_INI.normal_data("Name", project_name) # 脚本运行当前时间 now = time.strftime("%Y_%m_%d-%H_%M_%S") now_day = time.strftime("%Y_%m_%d") # 根据执行用例项目参数给测试报告命名 reportFileName = f'{project_name}' + f'_{now}_result.html' # 测试报告存放文件夹地址 # reportDirName = os.path.abspath(os.path.join(os.getcwd(), "..%s.." % sep)) + sep + 'output' + sep + 'report' + sep reportDirName = root_path + sep + 'output' + sep + 'report' + sep # 以天为维度生成对应文件夹 report_dir = 'report_{_now}'.format(_now=now_day) reportDir = reportDirName + report_dir while not os.path.exists(reportDir): try: os.makedirs(reportDir) break except OSError as e: if e.errno != os.errno.EEXIST: raise # time.sleep might help here pass # 根据第三方库 BeautifulReport 执行用例并生成报告 with open(reportDir + sep + reportFileName, "wb"): beaRep = BeautifulReport(suites) title = f'{Name}{env_name}自动化测试报告' res = beaRep.report(filename=reportFileName, description=title, report_dir=reportDir) result_dict = beaRep.stopTestRun() casesAll = result_dict.get("testAll") casesPass = result_dict.get("testPass") casesSkip = result_dict.get("testSkip") # casesFail = result_dict.get("testFail") casesFail = result_dict.get("testAll") - result_dict.get("testPass") - result_dict.get("testSkip") # casesError = result_dict.get("testError") if not casesSkip: _pass_rate = ("%.2f%%" % (casesPass / casesAll * 100)) else: _pass_rate = ("%.2f%%" % (casesPass / (casesAll - casesSkip) * 100)) content = f'{title}(通过率:{_pass_rate}) \n 用例总数:{casesAll}, 通过:{casesPass},失败:{casesFail},跳过:{casesSkip}' sleep(3) _platform = platform.platform() if _platform == 'Linux-2.6.32-754.18.2.el6.x86_64-x86_64-with-centos-6.10-Final': ip = '10.0.6.56' link_url = "http://" + ip + f':8686{sep}report{sep}{report_dir}{sep}{reportFileName}' elif _platform.startswith("Windows") or _platform.startswith('Darwin'): # 获取本机计算机名称 hostname = socket.gethostname() # 获取本机ip ip = socket.gethostbyname(hostname) link_url = "http://" + ip + f':8686{sep}report{sep}{report_dir}{sep}{reportFileName}' robot_url = None else: ip = 'https://apitest.fangdd.net/' link_url = ip + f'report{sep}{report_dir}{sep}{reportFileName}' if robot_url: # 单个项目非正式环境只会发送到单个项目群 if project_name != "All" and env != "prod": for url in robot_url: send_link(url, link_url, content) # 单个项目正式环境会发到巡检群和各自项目群 elif project_name != "All" and env == "prod": robot_url.append(test_robot) for url in robot_url: send_link(url, link_url, content) # 所有项目 不区分环境,均会发送到巡检群 elif project_name == "All": send_link(test_robot, link_url, content) return res
def run_test(): try: data_dict = json.loads(request.get_data()) # 从请求中获取请求参数 cases_names = data_dict.get('cases') # "多多商服/全部/多多新房" env_num = data_dict.get('env') # 1 ->int reg_str = data_dict.get("reg_str") dataIni = GetDataIni() # 检查必填参数是否填写 if cases_names and env_num: cases = dataIni.normal_data("Project_name", cases_names) # test_ddsf/ALL # 前端传过来的是 int 类型,INI配置文件中是默认为字符串的,需要处理下 env_data = eval(dataIni.normal_data( "Env_name", str(env_num))) # ["prod", "正式环境"] -> list if cases == "test_ddxf": # check = True check_shop = CheckCases("test_shop", env_data[0]).check_cases() check_shopapp = CheckCases("test_shopapp", env_data[0]).check_cases() check_ddxfapp = CheckCases("test_ddxfapp", env_data[0]).check_cases() check = check_shop or check_ddxfapp or check_shopapp else: check = CheckCases(cases, env_data[0]).check_cases() if not check: res = jsonify({ "code": 201, "success": False, "cases_count": 0, "msg": "请确认参数,获取用例失败!" }) else: # start.delay(cases_dir=cases, env=env_data[0], reg_str=reg_str) # 尝试修复环境参数经过函数 delay 丢失的bug start.apply_async(args=[cases, env_data[0], reg_str]) res = jsonify({ "code": 200, "success": True, "msg": f"{cases_names}项目{env_data[1]}环境 " f"自动化测试正在执行,请注意查收钉钉推送消息" }) else: res = jsonify({"code": 10000, "success": False, "msg": "缺少必填参数!"}) except NoOptionError: res = jsonify({ "code": 10001, "success": False, "msg": "自动化测试执行失败!请求参数解析出错!" }) except Exception: res = jsonify({ "code": 10002, "success": False, "msg": "自动化测试执行失败! 出现未知错误!" }) return res
def get_env(): dataIni = GetDataIni() names_list = dataIni.cfgB.options("Env_name") res = json.dumps(names_list, ensure_ascii=False) return Response(res, mimetype="application/json")