def get_class_invitecode_and_id(self, grade=None): method = "get" url = "http://ci.ytesting.com/api/3school/school_classes" if grade != None: data = { "vcode": self.pc.getConfValue(CONFIG_PATH, "vcode", "vcode"), "action": "list_classes_by_schoolgrade", "gradeid": grade } response = self.class_mannge_api(method, url, data=data) bodyDict = response.json() log.info("展示出的班级为{}".format(bodyDict)) last_txt = bodyDict["retlist"][0] print(last_txt) intvitecode = last_txt["invitecode"] id = last_txt["id"] return intvitecode, id else: data = { "vcode": self.pc.getConfValue(CONFIG_PATH, "vcode", "vcode"), "action": "list_classes_by_schoolgrade" } response = self.class_mannge_api(method, url, data=data) bodyDict = response.json() log.info("展示出的班级为{}".format(bodyDict)) return bodyDict
def get_excel_title(self, sheet_name): """获取sheet表头""" title_key = tuple(self.__wb[sheet_name].iter_rows(max_row=1, values_only=True))[0] log.info("解析{}文件表单{}的标题:\n{}".format(self.filename, sheet_name, title_key)) return title_key
def register(reg_name='linux超', pwd='123456'): """注册帐号""" do_mysql = HandleMysql() request = HttpRequests() register_url = do_conf('URL', 'Host_Url') + '/member/register' while 1: phone = do_mysql.get_not_exist_phone() request_data = {"mobilephone": phone, "pwd": pwd, "regname": reg_name} request(method='post', url=register_url, data=request_data ) sql = 'select Id from member where MobilePhone=%s;' member = do_mysql(sql=sql, args=(phone,)) if member: member_id = member['Id'] break user_dic = { reg_name: { 'MemberId': member_id, 'pwd': pwd, 'MobilePhone': phone, 'RegName': reg_name } } do_mysql.close() request.close_session() log.info('注册{}帐号成功\n帐号信息-userId{},userName{},mobilePhone{}'. format(reg_name, member_id, reg_name, phone)) return user_dic
def close_session(self): self.session.close() try: log.info('关闭请求...') del self.session.cookies['JSESSIONID'] except Exception: pass
def register_login_parameters_data(cls, not_exist_phone, data): """注册与登录参数化""" data = cls.replace_not_exist_phone(not_exist_phone, data) log.info("data的值为{}".format(data)) data = cls.replace_exist_phone(data) log.info("data的值为{}".format(data)) return data
def close_session(self): self.session.close() try: log.info("关闭请求。。。") del self.session.cookies["JSESSIONID"] except Exception: pass
def write_config(cls, data, path): """写配置文件""" conf_obj = cls(path) for value in data: conf_obj[value] = data[value] log.info('{}文件写入数据\n{}'.format(path, data)) with open(path, 'w', encoding='utf-8') as f: conf_obj.write(f)
def get_not_exist_phone(self): """生成未注册的手机号""" while 1: phone = self.random_phone_num() if not self.is_exist_phone(phone): break log.info('已获得未注册的手机号码为:{}'.format(phone)) return phone
def setUp(self): method = self.pc_two.getConfValue(CONFIG_PATH, "ClassSetUp", "method") url = self.pc_two.getConfValue(CONFIG_PATH, "ClassSetUp", "url") data = self.pc_two.getConfValue(CONFIG_PATH, "ClassSetUp", "data") try: response = self.request(method, url, data=data) log.info(response.json()) except Exception as e: raise e log.info("添加班级失败")
def delete_add_class(self, classid, exist=None): method = "delete" if exist != None: url = "http://ci.ytesting.com/api/3school/school_classes/" + "9999" log.info("删除的url:{}".format(url)) else: url = "http://ci.ytesting.com/api/3school/school_classes/" + str( classid) data = {"vcode": self.pc.getConfValue(CONFIG_PATH, "vcode", "vcode")} respones = self.class_mannge_api(method, url, data=data) log.info("删除成功,放回的结果为{}".format(respones)) return respones
def random_phone_num(): """随机一个电话号码""" num_start = [ '134', '135', '136', '137', '138', '139', '150', '151', '152', '158', '159', '157', '182', '187', '188', '147', '130', '131', '132', '155', '156', '185', '186', '133', '153', '180', '189' ] start = random.choice(num_start) end = ''.join(random.sample(string.digits, 8)) phone_number = start + end log.info('生成的随机手机号码:{}'.format(phone_number)) return phone_number
def get_all_value(self, sheet_name): """获取指定表单的所有数据(除去表头)""" rows_obj = self.__wb[sheet_name].iter_rows( min_row=2, max_row=self.__wb[sheet_name].max_row, values_only=True) values = [] for row_tuple in rows_obj: values_list = [] for value in row_tuple: values_list.append(value) values.append(values_list) log.info("读取{}文件,表单{}的所有数据\n{}".format(self.filename, sheet_name, values)) return values
def get_option_value(self, section='DEFAULT', option=None, flag_eval=False, flag_bool=False): """获取配置文件指定section的option对应的value""" self.read(self.filename, encoding='utf-8') if option is None: return dict(self[section]) if isinstance(flag_bool, bool): if flag_bool: return self.getboolean(section, option) else: raise ValueError('{} must be type bool'.format(flag_bool)) data = self.get(section, option) if data.isdigit(): data = int(data) log.info("从配置文件{}解析{}信息为{}".format(self.filename, option, data)) return data try: data = float(data) log.info("从配置文件{}解析{}信息为{}".format(self.filename, option, data)) return data except ValueError: pass if isinstance(flag_eval, bool): if flag_eval: data = eval(data) log.info("从配置文件{}解析{}信息为{}".format(self.filename, option, data)) return data else: raise ValueError('{} must be type bool'.format(flag_eval)) log.info("从配置文件{}解析{}信息为{}".format(self.filename, option, data)) return data
def re_replace(re_expression, data, source): """ 替换指定字符串 :param re_expression: 正则表达式 :param data: 被替换字符串如手机号,密码等 :param source: 目标源字符串 :return: """ if isinstance(data, str): pattern = re.compile(re_expression) if re.search(pattern, source): source = re.sub(pattern, data, source) log.info("测试数据{}通过正则匹配为: {}".format(source, source)) return source else: log.error("正则匹配测试数据失败: data '{}' must be string".format(data)) raise TypeError("data '{}' must be string".format(data))
def getConfValue(self, filename, section, name): """ :param filename: :param section: :param name: :return: """ try: self.cf.read(filename, encoding="UTF-8") value = self.cf.get(section, name) except Exception as e: log.info('read file [%s] for [%s] failed , did not get the value' % (filename, section)) raise e else: log.info('read excel value [%s] successed! ' % value) return value
def send_request(self, method, url, params_type='form', data=None, **kwargs): method = method.upper() params_type = params_type.upper() if isinstance(data, str): try: data = json.loads(data) except Exception: data = eval(data) if 'GET' == method: response = self.session.request(method=method, url=url, params=data, **kwargs) elif 'POST' == method: if params_type == 'FORM': log.info("开始发送{}请求,URL为:{},请求数据为:{}".format(method, url, data)) response = self.session.request(method=method, url=url, data=data, **kwargs) elif params_type == 'JSON': response = self.session.request(method=method, url=url, json=data, **kwargs) else: response = self.session.request(method=method, url=url, **kwargs) else: log.error("请求方法错误:request method '{}' error ! please check".format( method)) raise ValueError( 'request method "{}" error ! please check'.format(method)) return response
def get_values(self, sql, args=None, is_all=False): if isinstance(args, Iterable) or args is None: if self._conn: self._cursor.execute(sql, args=args) log.info('执行SQL语句:{}'.format(sql)) self._conn.commit() if isinstance(is_all, bool): if is_all: values = self._cursor.fetchall() log.info("拉取数据库部分数据:\n{}".format(values[0])) else: values = self._cursor.fetchone() log.info("拉取数据库数据:\n{}".format(values)) return values else: log.error( 'got values error: default parameter "{}" must be bool' .format(is_all)) raise TypeError( 'default parameter "{}" must be bool'.format(is_all)) else: log.error('due to the db connect failed, so get values error!') raise ConnectionError('db connect failed get values error!') else: log.error( 'got values error: default parameter args "{}" must be Iterable' .format(args)) raise TypeError( 'default parameter args "{}" must be Iterable'.format(args))
def write_cell(self, sheet_name, row, column, value=None, bold=True, color=BLACK): if isinstance(row, int) and isinstance(column, int): try: log.info("{}文件,表单{},第{}行第{}列写入数据{}".format( self.filename, sheet_name, row, column, value)) cell_obj = self.__wb[sheet_name].cell(row, column) cell_obj.font = Font(color=color, bold=bold) cell_obj.value = value self.__wb.save(self.filename) except Exception as e: log.error("{}文件,表单{},第{}行第{}列写入数据{}失败\n{}".format( self.filename, sheet_name, row, column, value, e)) raise e else: log.error("{}文件写数据失败:row and column must be type int".format( self.filename)) raise TypeError('row and column must be type int')
def test_recharge(self, value): row = value.CaseId + 1 # 用例ID所在行号 precondition = value.Precondition # excel用例的前置条件 title = value.Title # 用例标题 url = do_conf('URL', 'Host_Url') + value.URL # 用例url request_value = value.Data # 请求参数 request_method = value.Method # 请求方法 select_sql = value.Sql # 查询充值结果的sql语句 replace_sql = recharge_parameters(select_sql) recharge_expected = HandleJson.json_to_python(value.Expected) # 期望结果 log.info('执行充值-测试用例"{}"开始'.format(title)) request_value = recharge_parameters(request_value) before_amount = self.mysql(sql=replace_sql)['LeaveAmount'] # 充值前的金额 # 切换会话 if precondition == '用户未登录': response = self.request(request_method, url=url, data=request_value) else: response = request(request_method, url=url, data=request_value) after_amount = self.mysql(sql=replace_sql)['LeaveAmount'] # 充值后的金额 actual_amount = str(after_amount - before_amount) # 实际金额 actual_code = response.json()['code'] # 实际code # 构造个实际结果的字典 actual_result = dict(leaveamount=actual_amount, code=actual_code) do_excel.write_cell( do_conf('SheetName', 'Recharge'), row, do_conf('ExcelNum', 'Actual_Column'), HandleJson.python_to_json(actual_result) ) try: self.assertEqual(recharge_expected, actual_result, msg='测试{}失败'.format(title)) except AssertionError as e: do_excel.write_cell( do_conf('SheetName', 'Recharge'), row, do_conf('ExcelNum', 'Result_Column'), do_conf('Result', 'Fail'), color=RED) log.error('{}-测试[{}] :Failed\nDetails:\n{}'.format(inspect.stack()[0][3], title, e)) raise e else: do_excel.write_cell( do_conf('SheetName', 'Recharge'), row, do_conf('ExcelNum', 'Result_Column'), do_conf('Result', 'Pass'), color=GREEN) log.info('{}-测试[{}] :Passed'.format(inspect.stack()[0][3], title)) log.info('执行登录-测试用例"{}"结束'.format(title))
def __init__(self): log.info('初始化数据库...') try: log.info('start connecting MySQL...') self._conn = pymysql.connect( host=do_conf('MySQL', 'Host'), user=do_conf('MySQL', 'User'), password=do_conf('MySQL', 'PassWord'), db=do_conf('MySQL', 'Db'), port=do_conf('MySQL', 'Port'), charset=do_conf('MySQL', 'Charset'), cursorclass=pymysql.cursors.DictCursor) except Exception as e: log.error('连接数据库失败\n错误信息如下\n'.format(e)) else: log.info('连接数据库成功') self._cursor = self._conn.cursor()
def test_add(self, value): row = value.CaseId + 1 # 用例ID所在行号 precondition = value.Precondition # excel用例的前置条件 title = value.Title # 用例标题 url = do_conf('URL', 'Host_Url') + value.URL # 用例url request_method = value.Method # 请求方法 request_value = value.Data # 请求参数 select_sql = value.Sql # 查询数据库中不存在的member id add_expected = HandleJson.json_to_python(value.Expected) # 期望结果 if precondition == '借款人用户ID不存在': not_exist_loan_member_id = str( int(self.mysql(select_sql)['Id']) - 1) request_value = add_parameters(not_exist_loan_member_id, request_value) else: request_value = add_parameters('', request_value) log.info('执行加标-测试用例"{}"开始'.format(title)) response = request(request_method, url=url, data=request_value) actual_result = response.json() do_excel.write_cell(do_conf('SheetName', 'Add'), row, do_conf('ExcelNum', 'Actual_Column'), response.text) try: self.assertEqual(add_expected, actual_result, msg='测试{}失败'.format(title)) except AssertionError as e: do_excel.write_cell(do_conf('SheetName', 'Add'), row, do_conf('ExcelNum', 'Result_Column'), do_conf('Result', 'Fail'), color=RED) log.error('{}-测试[{}] :Failed\nDetails:\n{}'.format( inspect.stack()[0][3], title, e)) raise e else: do_excel.write_cell(do_conf('SheetName', 'Add'), row, do_conf('ExcelNum', 'Result_Column'), do_conf('Result', 'Pass'), color=GREEN) log.info('{}-测试[{}] :Passed'.format(inspect.stack()[0][3], title)) log.info('执行加标-测试用例"{}"结束'.format(title))
def test_register(self, value): row = value.CaseId + 1 # 用例ID所在行号 title = value.Title # 用例标题 url = do_conf('URL', 'Host_Url') + value.URL # 用例url request_value = value.Data # 请求参数 request_method = value.Method # 请求方法 log.info('开始执行注册-"{}"测试用例'.format(title)) # 转json的目的是防止期望结果和实际结果的字符串形式匹配不上(excel 存储的期望结果有空格) expected = HandleJson.json_to_python(value.Expected) # 期望结果 not_exist_phone = self.mysql.get_not_exist_phone() # 正向用例的注册账号 request_value = register_login_parameters(not_exist_phone, request_value) response = self.request(request_method, url=url, data=request_value) actual_result = response.json() do_excel.write_cell(do_conf('SheetName', 'Register'), row, do_conf('ExcelNum', 'Actual_Column'), response.text) try: self.assertEqual(expected, actual_result, msg='测试{}失败'.format(title)) except AssertionError as e: do_excel.write_cell(do_conf('SheetName', 'Register'), row, do_conf('ExcelNum', 'Result_Column'), do_conf('Result', 'Fail'), color=RED) log.error('{}-测试[{}] :Failed\nDetails:\n{}'.format( inspect.stack()[0][3], title, e)) raise e else: do_excel.write_cell(do_conf('SheetName', 'Register'), row, do_conf('ExcelNum', 'Result_Column'), do_conf('Result', 'Pass'), color=GREEN) log.info('{}-测试[{}] :Passed'.format(inspect.stack()[0][3], title)) log.info('执行注册-测试用例"{}"结束'.format(title))
def close(self): if self._cursor: self._cursor.close() if self._conn: self._conn.close() log.info('关闭数据库...')
def __init__(self): self.session = requests.Session() log.info('建立请求...')
def replace_exist_loan_id(cls, data): exist_loan_id = getattr(DataReplace, 'loan_id') log.info(exist_loan_id) data = cls.re_replace(cls.pattern_exist_loan_id, exist_loan_id, data) return data
def close(self): log.info('关闭添加标的请求...') self.request.close_session()
def setUpClass(cls): cls.request = HttpRequests() cls.mysql = HandleMysql() log.info('------开始执行{}测试用例------'.format(cls.__doc__))
def close(self): log.info("关闭登录请求...") self.request.close_session()
def tearDownClass(cls): cls.mysql.close() cls.request.close_session() log.info('------{}测试用例执行结束------'.format(cls.__doc__))
def __init__(self, filename): try: self.filename = filename self.__wb = load_workbook(self.filename) except FileNotFoundError as e: log.info("解析Excel文件{}失败\n{}".format(self.filename, e))