class GYHandler(): """任务:中间层 common和调用层""" yaml_path = os.path.join(path.config_path, 'config.yaml') yaml_config = read_yaml(yaml_path) user_path = os.path.join(path.config_path, 'security.yaml') user_config = read_yaml(user_path) # logger logger_file = os.path.join(path.logs_path, yaml_config['logger']['file']) logger = get_logger(name=yaml_config['logger']['name'], file=logger_file) # excel excel_file = os.path.join(path.data_path, 'cases.xlsx') excel = ExcelHandler(excel_file) # 数据库 db_class = MidDBHandler @staticmethod def generate_new_phone(): """自动生成手机号码""" fk = Faker(locale="zh_CN") while True: phone = fk.phone_number() db = MidDBHandler() phone_in_db = db.query( 'select * from member where mobile_phone= {}'.format(phone)) db.close() if not phone_in_db: return phone
class Handler(): yaml_path = os.path.join(path.config_path, 'config.yaml') yaml_config = read_yaml(yaml_path) user_path = os.path.join(path.config_path, 'security.yaml') user_config = read_yaml(user_path) log_file = os.path.join(path.logs_path, yaml_config['logger']['file']) logger = get_log(name=yaml_config['logger']['name'], file=log_file) excel_file = os.path.join(path.data_path, 'demo.xlsx') excel = ExcelHandler(excel_file) def generate_random_str(randomlength=16): """ 生成一个指定长度的随机字符串,其中 string.digits=0123456789 string.ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ """ str_list = [ random.choice(string.digits + string.ascii_letters) for i in range(randomlength) ] random_str = ''.join(str_list) return random_str db = MidDBHandler()
class Handler(): """任务:中间层。common 和 调用层。 使用项目得配置数据,填充common模块 """ new_phone = '' inverstor_user_id = '' inverstor_user_token = '' admin_user_id = '' admin_user_token = '' loan_user_id = '' loan_user_token = '' yaml_path = os.path.join(config_path, 'config.yaml') yaml_config = read_yaml(yaml_path) print(yaml_config) user_path = os.path.join(config_path, 'security.yaml') user_config = read_yaml(user_path) # logger log_file = os.path.join(path.logs_path, yaml_config['logger']['file']) logger = get_log(name=yaml_config['logger']['name'], file=log_file) # excel对象 excel_file = os.path.join(path.data_path, 'demo.xlsx') excel = ExcelHandler(excel_file) # 新手机号码 new_phone = '' @classmethod def generate_new_phone(cls): """自动生成手机号""" fk = faker.Faker(locale='zh-CN') while True: phone = fk.phone_number() db2 = Handler.db phone_in_db = db2.query( 'select mobile_phone from member where mobile_phone={}'.format( phone)) # 查询数据库 # 如果数据库里面有这条记录,重新生成新的手机号码,循环,不知道什么时候结束,用while #db2.db_colse() if not phone_in_db: cls.new_phone = phone return phone return phone # 数据库 # db = DBHandler(host=user_config['db']['host'], # port=user_config['db']['port'], # user=user_config['db']['user'], # password=user_config['db']['password'], # # 不要写成utf-8 # charset=user_config['db']['charset'], # database=user_config['db']['database'], # cursorclass=DictCursor) # 数据库 db = MidDBHanlder() db_class = MidDBHanlder
class Handler(): """任务:中间层。 common 和 调用层。 使用项目的配置数据,填充common模块 """ env_path = os.path.join(path.config_path, 'env_config.yaml') env_config = read_yaml(env_path) user_path = os.path.join(path.config_path, 'user_config.yaml') user_config = read_yaml(user_path) db_path = os.path.join(path.config_path, 'db_config.yaml') db_config = read_yaml(db_path) # excel对象 excel_file = os.path.join(path.data_path, 'case_datas.xlsx') excel = ExcelHandler(excel_file) # 数据库 db_class = MidDBHandler() # 需要动态替换#...# 的数据 investor_phone = user_config['investor_user']['phone'] investor_pwd = user_config['investor_user']['pwd'] loan_phone = user_config['loan_user']['phone'] loan_pwd = user_config['loan_user']['pwd'] admin_phone = user_config['admin_user']['phone'] admin_pwd = user_config['admin_user']['pwd'] wrong_member_id = '888888' wrong_loan_id = '888888' @classmethod def replace_data(cls, string, pattern='#(.*?)#'): """数据动态替换""" # pattern = '#(.*?)#' results = re.finditer(pattern=pattern, string=string) for result in results: # old= '#investor_phone#' old = result.group() # key = 'investor_phone' key = result.group(1) new = str(getattr(cls, key, '')) string = string.replace(old, new) return string # 生成手机号 @classmethod def generate_new_phone(cls): while True: phone = '1' + random.choice(['3', '5', '8']) for i in range(9): num = random.randint(0, 9) phone += str(num) db = MidDBHandler() phone_in_db = db.query('SELECT * FROM member WHERE mobile_phone = {}'.format(phone)) db.close() if not phone_in_db: cls.new_phone = phone return phone
def __init__(self): yaml_path = os.path.join(path.GetPath('config'), 'config.yaml') yaml_config = read_yaml(yaml_path) user_path = os.path.join(path.GetPath('config'), 'security.yaml') user_config = read_yaml(user_path) super().__init__(host=user_config['db']['host'], port=user_config['db']['port'], user=user_config['db']['user'], password=user_config['db']['password'], charset=user_config['db']['charset'], database=user_config['db']['database'], cursorclass=DictCursor)
class YZHandler(): """任务:中间层。 common 和 调用层。 使用项目的配置数据,填充common模块 """ # 替换数据 # 新手机号码 new_phone = '' investor_user_id = '' investor_user_token = '' admin_user_id = '' admin_user_token = '' loan_user_id = '' loan_user_token = '' yaml_path = os.path.join(path.config_path, 'config.yaml') yaml_config = read_yaml(yaml_path) user_path = os.path.join(path.config_path, 'security.yaml') user_config = read_yaml(user_path) # logger logger_file = os.path.join(path.logs_path, yaml_config['logger']['file']) logger = get_logger(name=yaml_config['logger']['name'], file=logger_file) # excel对象 excel_file = os.path.join(path.data_path, 'cases.xlsx') excel = ExcelHandler(excel_file) # 辅助函数 # help_funcs = helper # 数据库 db_class = MidDBHandler @classmethod def generate_new_phone(cls): """自动生成手机号""" fk = Faker(locale='zh_CN') while True: phone = fk.phone_number() db = MidDBHandler() phone_in_db = db.query( 'SELECT * FROM member WHERE mobile_phone = {}'.format(phone)) db.close() if not phone_in_db: cls.new_phone = phone return phone
def __init__(self): # 获取账户信息 security_data = read_yaml(os.path.join(CONF_DIR, "security.yaml")) super().__init__( host=security_data["MYSQL"]["HOST"], port=security_data["MYSQL"]["PORT"], user=security_data["MYSQL"]["USER"], password=security_data["MYSQL"]["PWD"], database=security_data["MYSQL"]["NAME"], charset="utf8", cursorclass=pymysql.cursors.DictCursor )
def __init__(self): db_path = os.path.join(path.config_path, 'db_config.yaml') db_config = read_yaml(db_path) super().__init__(host=db_config['db']['host'], port=db_config['db']['port'], user=db_config['db']['user'], password=db_config['db']['password'], # 不要写成utf-8 charset=db_config['db']['charset'], # 指定数据库 database=db_config['db']['database'], cursorclass=DictCursor)
class Handler: #获取yaml路径 yaml = yaml_handler.read_yaml(yaml_path) # logger logger_config = yaml["logger"] logger = logging_handler.get_logger( name=logger_config["name"], file=os.path.join(log_path, logger_config["file"]), logger_level=logger_config["logger_level"], stream_level=logger_config["stream_level"], file_level=logger_config["file_level"]) #excel excel_config = yaml["excel"] excel_path = os.path.join(data_path, excel_config["file"])
class Handler: conf = config # YAML 数据 yaml = yaml_handler.read_yaml( os.path.join(config.CONFIG_PATH, "config.yml")) # excel 数据 __excel_path = conf.DATA_PATH __excel_file = yaml["excel"]["file"] excel = excel_handler.ExcelHandler(os.path.join(__excel_path, __excel_file)) # logger __logger_config = yaml["logger"] logger = logging_handler.get_logger( name=__logger_config["name"], file=os.path.join(config.LOG_PATH, __logger_config["file"]), logger_level=__logger_config["logger_level"], stream_level=__logger_config["stream_level"], file_level=__logger_config["file_level"])
# -*- coding: utf-8 -*- # @Time : 2020/6/11 23:38 # @Author : 深圳-烧烤-29期 # @File : db_handler.py import pymysql from pymysql.cursors import DictCursor from common import yaml_handler conf_info = yaml_handler.read_yaml() db_conf = conf_info['db'] class dbHandler: def __init__(self, host='120.78.128.25', port=3306, user='******', password='******', database='futureloan', charset='utf8', cursorclass=DictCursor): self.conn = pymysql.connect(host=host, port=port, user=user, password=password, database=database, charset=charset, cursorclass=cursorclass) self.cursor = self.conn.cursor()
import os import faker from pymysql.cursors import DictCursor #from common import helper from common.logger_hander import get_log from common.yaml_handler import read_yaml from config import path from config.path import config_path from common.excel_handler import ExcelHandler from common.db_handler import DBHandler yaml_path = os.path.join(config_path, 'config.yaml') yaml_config = read_yaml(yaml_path) print(yaml_config) user_path = os.path.join(config_path, 'security.yaml') user_config = read_yaml(user_path) # class MidDBHanlder(DBHandler): # def __init__(self, host=user_config['db']['host'], # port=user_config['db']['port'], # user=user_config['db']['user'], # password=user_config['db']['password'], # # 不要写成utf-8 # charset=user_config['db']['charset'], # database=user_config['db']['database'], # cursorclass=DictCursor): # super.__init__(host=host, # port=port, # user=user, # password=password,
class Handler: '''初始化所有的数据,方便调用''' # 加载 python 的配置项 conf = config # yaml 数据 yaml = read_yaml(os.path.join(config.CONFIG_PATH, 'config.yml')) # excel 数据 __excel_path = conf.DATA_PATH __excel_file = yaml['excel']['file'] excel = ExcelHandler(os.path.join(__excel_path, __excel_file)) # logger __logger_config = yaml['logger'] logger = logging_handler.get_logger( name=__logger_config['name'], file=os.path.join(config.LOG_PATH, __logger_config['file']), logger_level=__logger_config['logger_level'], stream_level=__logger_config['stream_level'], file_level=__logger_config['file_level']) ''' 初始化一个存储数据库的类,方便调用, 每次都是使用新的游标,使用同一个游标会导致查不到数据 ''' db_class = MysqlHandlerMiddleware @property def L0_token(self): return self.login(self.yaml['L0_user_info'])['token'] @property def L0_user_id(self): return self.login(self.yaml['L0_user_info'])['user_id'] @property def L0_mobile(self): return self.login(self.yaml['L3_user_info'])['mobile'] @property def L1_token(self): return self.login(self.yaml['L1_user_info'])['token'] @property def L1_user_id(self): return self.login(self.yaml['L1_user_info'])['user_id'] @property def L1_mobile(self): return self.login(self.yaml['L3_user_info'])['mobile'] @property def L2_token(self): return self.login(self.yaml['L2_user_info']) @property def L2_user_id(self): return self.login(self.yaml['L2_user_info'])['user_id'] @property def L2_mobile(self): return self.login(self.yaml['L3_user_info'])['mobile'] @property def L3_token(self): return self.login(self.yaml['L3_user_info']) @property def L3_user_id(self): return self.login(self.yaml['L3_user_info'])['user_id'] @property def L3_mobile(self): return self.login(self.yaml['L3_user_info'])['mobile'] @property def sys_token(self): return self.sys_login() def login(self, user_info): ''' 账号登录,提取用户的token :return: ''' res = visit(url=self.yaml['http']['base_url1'] + '/member/passwordLogin', method='post', headers={ "appDevice": "1", "deviceNumber": "52836374-4aa3-45fd-9291-45386072224e" }, data=user_info) token = jsonpath(res, '$..userToken')[0] user_id = jsonpath(res, '$..userId')[0] mobile = jsonpath(res, '$..mobile') member_info = {'token': token, 'user_id': user_id, 'mobile': mobile} return member_info # def login1(self): # ''' # 账号登录,提取用户的token # :return: # ''' # users = hd.yaml['users'] # for user in users: # print(user) # res = visit( # url= self.yaml['http']['base_url1'] + '/member/passwordLogin', # method= 'post', # headers= {"appDevice":"1","deviceNumber":"52836374-4aa3-45fd-9291-45386072224e"}, # data= user # ) # # print(res) # # token = jsonpath(res,'$..userToken')[0] # user_id = jsonpath(res,'$..userId')[0] # member_info = {'token':token, 'user_id':user_id} # print(member_info) def sys_login(self): '''后台登陆''' data = {"username": "******", "password": "******"} res = visit(url=self.yaml['http']['base_url3'] + '/admin/sys/login', method='post', json=data) sys_token = jsonpath(res, '$..token')[0] return sys_token def add_coupon(self, phone, coupon_id): '''发送优惠券''' data = { "userMobile": phone, "couponId": coupon_id, "couponCnt": 1, "memo": "" } res = visit(url=self.yaml['http']['base_url3'] + '/admin/userCoupon/addCouponMember', method='post', headers={'token': self.sys_token}, json=data) def replace_data(self, target): ''' 替换测试用例中的数据 ''' pattern = r'#(.*?)#' while re.search(pattern, target): key = re.search(pattern, target).group(1) value = getattr(self, key, '') target = re.sub(pattern, str(value), target, 1) return target
class YZHandler(): """任务:中间层。 common 和 调用层。 使用项目的配置数据,填充common模块 """ # 替换数据 # 新手机号码 new_phone = '' investor_user_id = '' investor_user_token = '' admin_user_id = '' admin_user_token = '' loan_user_id = '' loan_user_token = '' yaml_path = os.path.join(path.config_path, 'config.yaml') yaml_config = read_yaml(yaml_path) user_path = os.path.join(path.config_path, 'security.yaml') user_config = read_yaml(user_path) # logger logger_file = os.path.join(path.logs_path, yaml_config['logger']['file']) logger = get_logger(name=yaml_config['logger']['name'], file=logger_file) # excel对象 excel_file = os.path.join(path.data_path, 'cases.xlsx') excel = ExcelHandler(excel_file) # 辅助函数 # help_funcs = helper # 数据库 db_class = MidDBHandler # 需要动态替换#...# 的数据 investor_phone = user_config['investor_user']['phone'] investor_pwd = user_config['investor_user']['pwd'] loan_phone = user_config['loan_user']['phone'] loan_pwd = user_config['loan_user']['pwd'] admin_phone = user_config['admin_user']['phone'] admin_pwd = user_config['admin_user']['pwd'] @classmethod def replace_data(cls, string, pattern='#(.*?)#'): """数据动态替换""" # pattern = '#(.*?)#' results = re.finditer(pattern=pattern, string=string) for result in results: # old= '#investor_phone#' old = result.group() # key = 'investor_phone' key = result.group(1) new = str(getattr(cls, key, '')) string = string.replace(old, new) return string @classmethod def generate_new_phone(cls): """自动生成手机号""" fk = Faker(locale='zh_CN') while True: phone = fk.phone_number() db = MidDBHandler() phone_in_db = db.query('SELECT * FROM member WHERE mobile_phone = {}'.format(phone)) db.close() if not phone_in_db: cls.new_phone = phone return phone
class Handler: """初始化所有的数据。 在其他的模块当中重复使用。 是从 common 当中实例化对象。 """ # 加载 python 配置项 conf = config # YAML 数据 yaml = yaml_handler.read_yaml( os.path.join(config.CONFIG_PATH, "config.yml")) # excel 数据 __excel_path = conf.DATA_PATH __excel_file = yaml["excel"]["file"] excel = excel_handler.ExcelHandler(os.path.join(__excel_path, __excel_file)) # logger __logger_config = yaml["logger"] logger = logging_handler.get_logger( name=__logger_config["name"], file=os.path.join(config.LOG_PATH, __logger_config["file"]), logger_level=__logger_config["logger_level"], stream_level=__logger_config["stream_level"], file_level=__logger_config["file_level"]) # mysql 应不应该放到Handler, 不行。 db 对象。 # 不存储对象,我存储类. TODO: 没有听明白的可以不用这一行,使用的时候直接导入 # MysqlHandlerMid db_class = MysqlHandlerMid @property def token(self): return self.login(self.yaml["user"])["token"] @property def member_id(self): return self.login(self.yaml["user"])["member_id"] @property def admin_token(self): return self.login(self.yaml["admin_user"])["token"] @property def loan_id(self): return self.add_loan() def login(self, user): """登录测试账号""" res = requests_handler.visit( url=Handler.yaml["host"] + "/member/login", method="post", headers={"X-Lemonban-Media-Type": "lemonban.v2"}, # json=Handler.yaml["user"] json=user) # 提取 token # jsonpath token_str = jsonpath(res, "$..token")[0] token_type = jsonpath(res, "$..token_type")[0] member_id = jsonpath(res, "$..id")[0] token = " ".join([token_type, token_str]) # 提取 member_id return {"token": token, "member_id": member_id} # def login_admin(self): # """登录admin测试账号""" # res = requests_handler.visit( # url=Handler.yaml["host"] + "/member/login", # method="post", # headers={"X-Lemonban-Media-Type": "lemonban.v2"}, # json=Handler.yaml["admin_user"] # ) # # # 提取 token # # jsonpath # token_str = jsonpath(res, "$..token")[0] # token_type = jsonpath(res, "$..token_type")[0] # token = " ".join([token_type, token_str]) # # 提取 member_id # return token def add_loan(self): data = { "member_id": self.member_id, "title": "木森借钱买飞机", "amount": 2000, "loan_rate": 12.0, "loan_term": 3, "loan_date_type": 1, "bidding_days": 5 } # 发送请求,添加项目 res = requests_handler.visit(url=Handler.yaml["host"] + "/loan/add", method="post", headers={ "X-Lemonban-Media-Type": "lemonban.v2", "Authorization": self.token }, json=data) # 提取项目的id给审核的用例使用 return jsonpath(res, "$..id")[0] def audit_loan(self): data = {"loan_id": self.loan_id, "approved_or_not": True} resp = requests_handler.visit(url=Handler.yaml["host"] + "/loan/audit", method="post", headers={ "X-Lemonban-Media-Type": "lemonban.v2", "Authorization": self.admin_token }, json=data) return self.loan_id def recharge(self): data = {"member_id": self.member_id, "amount": 500000} resp = requests_handler.visit( url=Handler.yaml["host"] + "/member/recharge", method="post", headers={ "X-Lemonban-Media-Type": "lemonban.v2", "Authorization": self.token }, json=data) def replace_data(self, data): import re patten = r"#(.*?)#" while re.search(patten, data): key = re.search(patten, data).group(1) value = getattr(self, key, "") data = re.sub(patten, str(value), data, 1) return data
class MidHandler: """ 中间层。common和调用的中间层。 使用项目的配置数据, 填充common模块。 作用: 1. 隔离代码,让common更通用 2. 使用common代码更加简单,少调用 """ # 获取配置文件中的数据 conf_data = read_yaml(os.path.join(CONF_DIR, "conf.yaml")) # 获取账户信息 security_data = read_yaml(os.path.join(CONF_DIR, "security.yaml")) # 初始化log log = get_logger(file=os.path.join(LOG_DIR, conf_data["LOG"]["FILENAME"]), name=conf_data["LOG"]["NAME"], level=conf_data["LOG"]["LEVEL"], handler_level=conf_data["LOG"]["HANDLER_LEVEL"], file_level=conf_data["LOG"]["FILE_LEVEL"], fmt=conf_data["LOG"]["FMT"]) # excel对象 # 获取excel的路径 excel_file = os.path.join(DATA_DIR, "case.xlsx") excel = ExcelHandler(excel_file) """ # 数据库 db = DBHandler(host = security_data["MYSQL"]["HOST"], port = security_data["MYSQL"]["PORT"], user = security_data["MYSQL"]["USER"], password = security_data["MYSQL"]["PWD"], database = security_data["MYSQL"]["NAME"] ) """ # 数据库 下面这种写法是重命名 db_class = MidDBHandler # --- 需要动态替换的数据 --- # 新手机号码 new_phone = "" # 投资人信息 investor_member_id = "" investor_token = "" investor_phone = security_data["investor_phone"] investor_pwd = security_data["investor_pwd"] # 借款人信息 loan_member_id = "" loan_token = "" loan_phone = security_data["loan_phone"] loan_pwd = security_data["loan_pwd"] # 管理员信息 admin_member_id = "" admin_token = "" admin_phone = security_data["admin_phone"] admin_pwd = security_data["admin_pwd"] # --- ---- --- @classmethod def replace_data(cls, string, pattern=r"#(.*?)#"): """ 动态替换数据的方法 :param string: 需要替换的字符串 :param pattern: 正则表达式匹配规则 :return: 替换后的字符串 """ res = re.finditer(pattern=pattern, string=string) for i in res: string = string.replace(i.group(), str(getattr(cls, i.group(1)))) return string @classmethod def generate_new_phone(cls): """ 获取一个数据库中未注册过的手机号码 :return: 未注册的手机号码 """ while True: phone = helper.generate_phone() db = MidDBHandler() result = db.query_all("SELECT mobile_phone from member where mobile_phone={};".format(phone)) db.close() if not result: cls.new_phone = phone return phone
class Handler(): """任务:中间层。common 和 调用层。 使用项目得配置数据,填充common模块 """ new_phone = '' inverstor_user_id = '' inverstor_user_token = '' admin_user_id = '' admin_user_token = '' loan_user_id = '' loan_user_token = '' yaml_path = os.path.join(config_path, 'config.yaml') yaml_config = read_yaml(yaml_path) print(yaml_config) user_path = os.path.join(config_path, 'security.yaml') user_config = read_yaml(user_path) # logger log_file = os.path.join(path.logs_path, yaml_config['logger']['file']) logger = get_log(name=yaml_config['logger']['name'], file=log_file) # excel对象 excel_file = os.path.join(path.data_path, 'demo.xlsx') excel = ExcelHandler(excel_file) # 数据 需要动态替换 #。。。#的数据 investor_phone = user_config['investor_user']['phone'] investor_pwd = user_config['investor_user']['pwd'] loan_phone = user_config['loan_user']['phone'] loan_pwd = user_config['loan_user']['pwd'] admin_phone = user_config['admin_user']['phone'] admin_pwd = user_config['admin_user']['pwd'] phone = user_config['investor_user']['phone'] pwd = user_config['investor_user']['pwd'] # def replace_data(self,string): # import re # res = re.finditer(r'#(.*?)#',string) # for i in res: # string = string.replace(i.group(),str(getattr(self,i.group(1)))) # return string @classmethod def replace_data(cls,string,pattern = '#(.*?)#'): """数据动态替换""" results = re.finditer(pattern=pattern, string=string) for result in results: print(result) # old='#investor_phone#' old_data = result.group() # key = 'investor_phone' key = result.group(1) new_data = str(getattr(cls, key, '')) string = string.replace(old_data, new_data) return string # 新手机号码 new_phone = '' @classmethod def generate_new_phone(cls): """自动生成手机号""" fk = faker.Faker(locale='zh-CN') while True: phone = fk.phone_number() db2 = Handler.db phone_in_db = db2.query('select mobile_phone from member where mobile_phone={}'.format(phone)) # 查询数据库 # 如果数据库里面有这条记录,重新生成新的手机号码,循环,不知道什么时候结束,用while #db2.db_colse() if not phone_in_db: cls.new_phone = phone return phone return phone # 数据库 # db = DBHandler(host=user_config['db']['host'], # port=user_config['db']['port'], # user=user_config['db']['user'], # password=user_config['db']['password'], # # 不要写成utf-8 # charset=user_config['db']['charset'], # database=user_config['db']['database'], # cursorclass=DictCursor) # 数据库 db = MidDBHanlder() db_class = MidDBHanlder
class Handler(object): # 加载配置文件 config = config # 加载yml配置 __yaml_file = os.path.join(config.CONFIG_PATH, 'config.yml') yaml_data = yaml_handler.read_yaml(__yaml_file) # 初始化日志管理器 __log_file = os.path.join(config.LOG_PATH, yaml_data["log"]["filename"]) logger = get_logger.get_logger( logger_name=yaml_data["log"]["logger_name"][1], level=yaml_data["log"]["level"], filemode=yaml_data["log"]["filemode"], filename=__log_file) # 初始化excel数据 __excel_file = os.path.join(config.DATA_PATH, yaml_data["excel"]["filename"]) excel = ExcelHandler(__excel_file) # 加载数据库类,方便管理。不要实例化数据库--->因为有很多不同的对象去访问数据库。 db_class = MysqlHandlerMid # 加载响应类 res_class = Response # 获取随机手机号 # mobile_phone = get_random_phone() # 登陆获取member_id和token # @property # def member_id(self): # return login()[0] # @property # def token(self): # return login()[1] # @property # def member_id(self): # return self.login(self.yaml_data["user"])[0] member_id = None token = None # @property # def token(self): # return self.login(self.yaml_data["user"])[1] # 管理员登陆 admin_token = None # def admin_token(self): # return self.login(self.yaml_data["admin_user"])[1] def login(self, user): headers = { "X-Lemonban-Media-Type": "lemonban.v2", "Content-Type": "application/json" } res = Response(self.yaml_data["url"] + "/member/login", 'post').get_response(headers=headers, json=user) member_id = jsonpath(res, "$..id")[0] token_type = jsonpath(res, "$..token_type")[0] token = token_type + ' ' + jsonpath(res, "$..token")[0] return member_id, token loan_id = None def get_loan_id(self): headers = { "X-Lemonban-Media-Type": "lemonban.v2", "Content-Type": "application/json", "Authorization": self.token } data = { "member_id": self.member_id, "title": "xx借钱买手机", "amount": 1000.00, "loan_rate": 10.11, "loan_term": 2, "loan_date_type": 1, "bidding_days": 1 } res = Response(self.yaml_data["url"] + "/loan/add", 'post').get_response(headers=headers, json=data) loan_id = jsonpath(res, "$..id")[0] return loan_id def data_replace(self, string): import re pattern = r"#(.*?)#" while re.search(pattern, string): key = re.search(pattern, string).group(1) value = getattr(self, key, '') string = re.sub(pattern, str(value), string, count=1) return string
class Handler(object): """初始化所有的数据。 在其他的模块当中重复使用。 是从 common 当中实例化对象。 """ # 加载 python 配置项 conf = config # YAML 数据 yaml = yaml_handler.read_yaml( os.path.join(config.CONFIG_PATH, "config.yml")) # excel 数据 __excel_path = conf.DATA_PATH __excel_file = yaml["excel"]["file"] excel = excel_handler.ExcelHandler(os.path.join(__excel_path, __excel_file)) # logger __logger_config = yaml["default_logger"] logger = logging_handler.Logger(__logger_config) # mysql 应不应该放到Handler, 不行。 db 对象。 # 不存储对象,我存储类. TODO: 没有听明白的可以不用这一行,使用的时候直接导入 # MysqlHandlerMid MysqlDbClient = MysqlHandlerMid RedisDbClient = RedisHandlerMid def request_to_login(self, session, url, data, method="get", headers=None): """登录结果判断""" web_aft_login = session.request(url=url, data=data, method=method, headers=headers) if web_aft_login.json()["success"] is None: self.logger.error("登录账号时出现意料之外的情况, user:{}".format(data["phone"])) raise Exception(format(web_aft_login.json())) if web_aft_login.status_code == 200 and web_aft_login.json( )["success"] is True: self.logger.info("登录成功, 账号:{}".format(data["phone"])) return session if web_aft_login.json()["success"] is False: self.logger.warning("登录失败, 账号:{}".format(data["phone"])) raise Exception(format(web_aft_login.json())) else: self.logger.error("登录账号时出现意料之外的情况") raise Exception("unknown error: {}".format(web_aft_login.json())) def login_backend(self, user_to_login=None): """登录后台测试账号""" session = requests.Session() # def backend_switch_shop(session: requests.Session(), sp_id: int): # """后台切换店铺""" # res = session.post( # url='http://centertest.senguo.me/api/shop?method=set_shop_cookie', # data={"shop_type": "pf", "shop_id": sp_id} # ) # return res # # def switch_shop(s_self, sp_id): # """用于切换店铺: session.backend_switch_shop()""" # return backend_switch_shop(session=session, sp_id=sp_id) def switch_shop(s_self, sp_id): res = session.request(url=self.yaml["host"]["center"] + '/api/shop?method=set_shop_cookie', method="post", data={ "shop_type": "pf", "shop_id": sp_id }) return res session.switch_shop = types.MethodType(switch_shop, session) url = self.yaml["host"]["pf"] + "/login" # request_data web_to_login = session.request(url=url, method="get") default_user = copy.deepcopy(self.yaml["users"]["default_user"]) data = user_to_login if user_to_login else default_user data["password"] = tran_pwd(data["password"]) data["_xsrf"] = web_to_login.cookies.get("_xsrf") data["action"] = "phone_password" return self.request_to_login(session=session, url=url, data=data, method="post") def login_easy(self, user_to_login=None): """登录批发易""" session = requests.Session() # def boss_switch_shop(session: requests.Session(), sp_id: int): # """老板助手切换店铺""" # res = session.request( # url="http://pftest.senguo.me/boss/home", # method="post", # data={"action": "shop_change", "shop_id": sp_id} # ) # return res # # def switch_shop(s_self, sp_id): # """用于切换店铺: session.boss_switch_shop()""" # return boss_switch_shop(session=session, sp_id=sp_id) def switch_shop(s_self, sp_id): res = session.request(url=self.yaml["host"]["pf"] + "/boss/home", method="post", data={ "action": "shop_change", "shop_id": sp_id }) return res session.switch_shop = types.MethodType(switch_shop, session) url = self.yaml["host"]["pf"] + "/api/easy/login/password/" # request_headers # headers = {"Content-Type": "application/json"} # request_data default_user = copy.deepcopy(self.yaml["users"]["default_user"]) data = user_to_login if user_to_login else default_user data["password"] = tran_pwd(data["password"]) return self.request_to_login(session=session, url=url, data=data, method="post") def replace_data(self, data): """用于将用例data中pattern匹配的字符串修改为handler()中以该字符串为名属性的值""" import re patten = r"#(.*?)#" while re.search(patten, data): key = re.search(patten, data).group(1) value = getattr(self, key, "") data = re.sub(patten, str(value), data, 1) return data def p2u(self, path: str): """拼接项目host和接口路径""" return "".join((self.yaml["host"]["pf"], path))
# -*- coding: utf-8 -*- # @Time : 2020/6/9 22:22 # @Author : 深圳-烧烤-29期 # @File : path_config.py import os from common import yaml_handler data = yaml_handler.read_yaml() config_path = os.path.dirname(os.path.abspath(__file__)) root_path = os.path.dirname(config_path) #测试用例路径 exl_path = os.path.join(root_path, data['excel']['file']) #日志路径 logs_path = os.path.join(root_path, data['log']['file']) #测试报告路径 repors_path = os.path.join(root_path, data['report']['file']) #测试模块路径 test_path = os.path.join(root_path, 'tests')
class LccHandler(): '''任务:中间层。common和调用层,隔离代码,使得common模块更加通用,使用common里面的代码更加简单。 使用项目的配置数据,填充common模块 ''' #替换数据 #新手机号码 new_phone = ' ' investor_member_id = '' investor_token = ' ' admin_member_id = ' ' admin_token = ' ' loan_id = ' ' loan_token = ' ' yaml_path = os.path.join(path.GetPath('config'), 'config.yaml') yaml_config = read_yaml(yaml_path) user_path = os.path.join(path.GetPath('config'), 'security.yaml') user_config = read_yaml(user_path) #logger logger_file = os.path.join(path.GetPath('logs'), yaml_config['logger']['file']) logger = get_logger(name=yaml_config['logger']['name'], file=logger_file) #excel对象 excel_file = os.path.join(path.GetPath('data'), 'cekai_cases.xlsx') excel = ExcelHandler(excel_file) #辅助函数,导入模块,其实就是重命名,把helper保存到help_funcs里面作为类属性 # help_funcs=helper #数据库 # db=DBHandle( # host=user_config['db']['host'], # port=user_config['db']['port'], # user=user_config['db']['user'], # password=user_config['db']['password'], # charset=user_config['db']['charset'], # database=user_config['db']['database'], # cursorclass=DictCursor # ) db = MidDBHandler() # new_phone=' ' @classmethod def generate_new_phone(cls): # '''自动生成手机号码''' fk = Faker(locale="zh_CN") while True: phone = fk.phone_number() db = DBHandle(host='8.129.91.152', port=3306, user='******', password='******', charset='utf8', database='futureloan', cursorclass=DictCursor) phone_in_db = db.query( 'select * from member where mobile_phone={};'.format(phone)) db.close() if not phone_in_db: cls.new_phone = phone return phone #需要动态替换#...#的数据 username = user_config['user_register']['username'] email = user_config['user_register']['email'] pwd = user_config['user_register']['pwd'] user_id = user_config['user_register']['user_id'] @classmethod def replace_data(cls, string, pattern='#(.*?)#'): """数据动态替换""" #pattern='#(.*?)#' results = re.finditer(pattern=pattern, string=string) for result in results: old = result.group() key = result.group(1) new = str(getattr(cls, key, '')) string = string.replace(old, new) return string
class MiddleHandler: """初始化所有的数据, 在其他的模块中可以重复使用 """ # 加载配置文件 config = config # 获取yaml数据 yaml_data = yaml_handler.read_yaml(os.path.join(config.CONFIG_PATH, "config.yml")) # 读取excel数据 excel_path = config.DATA_PATH excel_filename = yaml_data["excel"]["file"] excel = ExcelHandler(os.path.join(excel_path, excel_filename)) # 初始化logger logger_config = yaml_data["log"] logger = logging_handler( logger_name=logger_config["loggername"], file=os.path.join(config.LOG_PATH, logger_config["file"]), logger_level=logger_config["logger_level"], stream_level=logger_config["stream_level"], file_level=logger_config["file_level"], ) db_class = MysqlMiddle def login(self, user): """登录测试账号""" res = requests_handler.visit( url=MiddleHandler.yaml_data["host"] + "/member/login", method="post", headers={"X-Lemonban-Media-Type": "lemonban.v2"}, json=user ) # 提取token # jsonpath token_type = jsonpath(res, "$..token_type")[0] token_str = jsonpath(res, "$..token")[0] token = " ".join([token_type, token_str]) member_id = jsonpath(res, "$..id")[0] return {"token": token, "member_id": member_id} def recharge(self): data = {"member_id": self.member_id, "amount": 500000} resp = requests_handler.visit( url=MiddleHandler.yaml_data["host"] + "/member/recharge", method="post", headers={"X-Lemonban-Media-Type": "lemonban.v2", "Authorization": self.token}, json=data ) def withdraw(self): data = {"member_id": self.member_id, "amount": 500000} resp = requests_handler.visit( url=MiddleHandler.yaml_data["host"] + "/member/withdraw", method="post", headers={"X-Lemonban-Media-Type": "lemonban.v2", "Authorization": self.token}, json=data ) def add_project(self): data = {"member_id":self.member_id, "title":"借钱去月球看星星", "amount":100000, "loan_rate":12.0, "loan_term":3, "loan_date_type":1, "bidding_days":5} resp = requests_handler.visit( url=MiddleHandler.yaml_data["host"] + "/loan/add", method="post", headers={"X-Lemonban-Media-Type":"lemonban.v2", "Authorization": self.token}, json=data ) return jsonpath(resp,"$..id")[0] def audit(self): data = {"loan_id":self.loan_id,"approved_or_not":True} resp = requests_handler.visit( url=MiddleHandler.yaml_data["host"] + "/loan/audit", method="patch", headers={"X-Lemonban-Media-Type":"lemonban.v2", "Authorization": self.admin_token}, json=data ) return data["loan_id"] def replace_data(self, data): import re patten = r"#(.+?)#" while re.search(patten, data): key = re.search(patten, data).group(1) value = getattr(self, key, "") data = re.sub(patten, str(value) , data, 1) return data @property def token(self): return self.login(self.yaml_data["user"])["token"] @property def member_id(self): return self.login(self.yaml_data["user"])["member_id"] @property def admin_token(self): return self.login(self.yaml_data["admin_user"])["token"] @property def loan_id(self): return self.add_project() @property def pass_loan_id(self): return self.audit()
class ConfHandler: # 获取配置文件内容 conf_info = yaml_handler.read_yaml() # excel配置信息 __excel_data = conf_info['excel'] regist_sheet = __excel_data['sheet_name_reg'] login_sheet = __excel_data['sheet_name_lgn'] recharge_sheet = __excel_data['sheet_name_chrg'] withdraw_sheet = __excel_data['sheet_name_wthdr'] update_sheet = __excel_data['sheet_name_name'] info_sheet = __excel_data['sheet_name_info'] add_sheet = __excel_data['sheet_name_add'] audit_sheet = __excel_data['sheet_name_audit'] inv_sheet = __excel_data['sheet_name_inv'] loans_sheet = __excel_data['sheet_name_loans'] # excel路径 excel_file = path_config.exl_path # 初始化excel数据读取 exl_handler = excel_read.ExcelHandler(excel_file) # log配置信息 __log_conf = conf_info['log'] # 配置日志存放路径 __lg_mk = datetime.datetime.now().strftime("%y%m%d") __lg_fl = datetime.datetime.now().strftime("%y-%m-%d-%H-%M-%S") __lg_path = os.path.join(path_config.logs_path, __lg_mk) # 判断文件夹是否存在 if not os.path.exists(__lg_path): os.mkdir(__lg_path) __logs_file = os.path.join(__lg_path, "futureloan-{}.log".format(__lg_fl)) # 初始化日志收集器 logger = logging_handler.get_logger( name=__log_conf['name'], logger_level=__log_conf['logger_level'], stream_level=__log_conf['stream_level'], file_level=__log_conf['file_level'], file=__logs_file) # 测试报告配置信息 rpt_conf = conf_info['report'] __rp_mk = datetime.datetime.now().strftime("%y%m%d") __rp_fl = datetime.datetime.now().strftime("%y-%m-%d-%H-%M-%S") __rp_path = os.path.join(path_config.repors_path, __rp_mk) # 判断文件夹是否存在 if not os.path.exists(__rp_path): os.mkdir(__rp_path) # 测试报告存放路径 rpt_file = os.path.join(__rp_path, "report-{}.html".format(__rp_fl)) # host地址 host = conf_info['host'] # 封装数据库类名 db_class = dbHandlerMid @property def token(self): return self.login(self.conf_info["user"])['token'] @property def member_id(self): return self.login(self.conf_info["user"])['member_id'] @property def admin_token(self): return self.login(self.conf_info["admin_user"])["token"] @property def invest_token(self): return self.login(self.conf_info["invest_user"])["token"] @property def invest_member_id(self): return self.login(self.conf_info["invest_user"])["member_id"] @property def loan_id(self): return self.add_loan() def login(self, user): res = request_handler.visit( url="".join([ConfHandler.host, "/member/login"]), method="POST", json=user, headers={"X-Lemonban-Media-Type": "lemonban.v2"}) # 取token的前缀 token_type = jsonpath(res, "$..token_type")[0] # 取token后半部分 token_str = jsonpath(res, "$..token")[0] # 拼接token token = " ".join([token_type, token_str]) # 获取登录用户的id id = jsonpath(res, "$..id")[0] return {"token": token, "member_id": id} # 新增项目 def add_loan(self): data = { "member_id": self.invest_member_id, "title": "烧烤投资{}".format(datetime.datetime.now().strftime("%y%m%d%H%M%S")), "amount": 80000.00, "loan_rate": 12.0, "loan_term": 12, "loan_date_type": 1, "bidding_days": 10 } res = request_handler.visit(url="".join([self.host, "/loan/add"]), method="POST", json=data, headers={ "X-Lemonban-Media-Type": "lemonban.v2", "Authorization": self.invest_token }) # 返回新增项目的loan_id return jsonpath(res, "$..id")[0] # 审核项目 def audit_loan(self): data = {"loan_id": self.loan_id, "approved_or_not": "true"} res = request_handler.visit(url="".join([self.host, "/loan/audit"]), method="PATCH", json=data, headers={ "X-Lemonban-Media-Type": "lemonban.v2", "Authorization": self.admin_token }) return jsonpath(data, "$.loan_id")[0] def replace_data(self, data): import re patten = r"#(.*?)#" while re.search(patten, data): key = re.search(patten, data).group(1) value = getattr(self, key, "") data = re.sub(patten, str(value), data, 1) return data
class MidHandler(): """任务:中间层。 common 和 调用层。 使用项目的配置数据,填充common模块 """ # 替换数据 # 新手机号码 new_phone = '' investor_user_id = '' investor_user_token = '' admin_user_id = '' admin_user_token = '' loan_user_id = '' loan_user_token = '' # yaml 读取 yaml_path = os.path.join(path.config_path, 'config.yaml') yaml_config = read_yaml(yaml_path) user_path = os.path.join(path.config_path, 'security.yaml') user_config = read_yaml(user_path) # token turing_token_yaml_path = os.path.join(path.config_path, 'turing_token.yaml') # logger # logger_file = os.path.join(path.logs_path, yaml_config['logger']['file'] + '_' + time_now + '.log') # logger = get_logger(name=yaml_config['logger']['name'], # file=logger_file) folder_name = os.path.dirname(os.path.dirname(__file__)) folder_base_name = os.path.basename(folder_name) log_path = path.logs_path logger_file = '{}/{}_{}.log'.format(log_path, folder_base_name, time_now) logger = get_logger(name=yaml_config['logger']['name'], file=logger_file, logger_level=yaml_config['logger']['logger_level'], stream_handler_level=yaml_config['logger']['stream_handler_level'], file_handler_level=yaml_config['logger']['file_handler_level'], fmt_str=yaml_config['logger']['fmt_str'] ) # logger.debug('debug message') # excel对象 excel_file = os.path.join(path.data_path, 'cases.xlsx') excel = ExcelHandler(excel_file) # 辅助函数 # help_funcs = helper # 数据库 db_class = MidDBHandler # 需要动态替换#...# 的数据 investor_phone = user_config['investor_user']['phone'] investor_pwd = user_config['investor_user']['pwd'] loan_phone = user_config['loan_user']['phone'] loan_pwd = user_config['loan_user']['pwd'] admin_phone = user_config['admin_user']['phone'] admin_pwd = user_config['admin_user']['pwd'] # 类方法,前面用cls,代表类本身 @classmethod def replace_data(cls, my_string, pattern='#(.*?)#'): """数据动态替换""" # pattern = '#(.*?)#' results = re.finditer(pattern=pattern, string=my_string) for result in results: # old= '#investor_phone#' old = result.group() # key = 'investor_phone' key = result.group(1) if old == "#new_phone#": new = MidHandler.generate_new_phone() else: new = str(getattr(cls, key, '')) my_string = my_string.replace(old, new) return my_string @classmethod def get_token(cls): data = MidHandler.excel.read('login') url = MidHandler.yaml_config['host'] content_type = eval(data[0]['paras'])['Content-Type'] ak = MidHandler.user_config['ak'] uid = MidHandler.user_config['uid'] parameter = json.dumps({"ak": ak, "uid": uid, "token": "", "asr": 4, "tts": 3, "tone": 20}) payload = {'Content-Type': content_type, 'parameters': parameter} files = [ ('speech', ('apple.opus', open('E:/Hannto/Automation/Github/Chameleon/Audio/apple.opus', 'rb'), 'application/octet-stream')) ] headers = {} response = requests.request("POST", url, headers=headers, data=payload, files=files) res_token = response.json()['token'] rec_token = {'token': res_token} write_yaml(MidHandler.turing_token_yaml_path, rec_token) return res_token @classmethod def update_tests_data(cls): data = MidHandler.excel.read('login') case_range = len(data) index_num: int new_token = MidHandler.get_token() for index_num in range(case_range): new_parameters = eval(eval(data[index_num]['paras'])['parameters']) new_parameters["ak"] = MidHandler.user_config['ak'] new_parameters["uid"] = MidHandler.user_config['uid'] new_parameters["token"] = new_token new_paras = {"parameters": json.dumps(new_parameters)} str_new_paras = json.dumps(new_paras) data[index_num]['paras'] = str_new_paras return data @classmethod def generate_new_phone(cls): """自动生成手机号""" fk = Faker(locale='zh_CN') while True: phone = fk.phone_number() db = MidDBHandler() phone_in_db = db.query('SELECT * FROM member WHERE mobile_phone = {}'.format(phone)) db.close() if not phone_in_db: cls.new_phone = phone return phone