コード例 #1
0
def test_recharge(info, login):
    """充值"""
    """先要替换"""
    if "#member_id#" in info['json']:
        info["json"] = info["json"].replace('#member_id#', str(login['id']))
    if "#wrong_member_id#" in info['json']:
        info["json"] = info["json"].replace('#wrong_member_id#',
                                            str(login['id'] + 1))

    # # token组装方式1:通过excel替换
    # if "#token#" in info['headers']:
    #     info["headers"] = info["headers"].replace("#token#",login['token'])

    # token 组装2:通过headers 添加,excel 表格里面不需要Authorization
    headers = json.loads(info["headers"])
    headers['Authorization'] = login['token']
    res = requests.request(url=yaml_config['host'] + info['url'],
                           method=info['method'],
                           headers=headers,
                           json=json.loads(info['json']))
    res_body = res.json()
    print(res_body)
    try:
        assert res_body['code'] == info["expected"]
    except AssertionError as e:
        logger.error("用例失败:{}".format(e))
        raise e
    finally:
        excel = ExcelHandler(excel_file)
        excel.write('recharge',
                    str(res_body),
                    row=int(info['case_id'] + 1),
                    column=9)

        after_recharge_money = db.query(sql)
        if json.loads(info["json"])['amount']:
            money = json.loads(info["json"])['amount']
        if res_body['code'] == info["expected"]:
            excel.write('recharge',
                        True,
                        row=int(info['case_id'] + 1),
                        column=8)
            if str(money).isdigit():
                if after_recharge_money[
                        'leave_amount'] == before_recharge_money[
                            'leave_amount'] + decimal.Decimal(money):
                    # float(after_recharge_money['leave_amount']) == float(before_recharge_money['leave_amount']) + float(money)
                    excel.write('recharge',
                                "充值成功",
                                row=int(info['case_id'] + 1),
                                column=8)
        else:
            excel.write('recharge',
                        False,
                        row=int(info['case_id'] + 1),
                        column=8)
コード例 #2
0
def test_login (test_info):
    actual_url = test_info['url']
    actual_method = test_info['method']
    actual_json = test_info['json']
    actual_headers = test_info['headers']
    expected = test_info['expected']

    if '*phone*' in actual_json:
        mobile_phone =generate_new_phone()
        actual_json = actual_json.replace('*phone*',mobile_phone)
    if '#phone#' in actual_json:
        mobile_phone =user_config['investor_user']['phone']
        actual_json = actual_json.replace('#phone#',mobile_phone)
    if '#pwd#' in actual_json:
        pwd =user_config['investor_user']['pwd']
        actual_json = actual_json.replace('#pwd#',pwd)
    print(actual_json)
    res = requests.request(method=actual_method,
                           url=yaml_config['host'] + actual_url,
                           headers=eval(actual_headers),
                           json=eval(actual_json))
    res_body = res.json()

    try:
        assert res_body['code'] == expected
    except AssertionError as e:
        logger.error("用例失败:{}".format(e))
        raise e
    finally:
        excel = ExcelHandler(excel_file)
        excel.write('login',str(res_body),row=int(test_info['case_id']+1),column=9)
        if res_body['code']== expected:
            excel.write('login',True,row=int(test_info['case_id']+1),column=8)
        else:
            excel.write('login',False,row=int(test_info['case_id']+1),column=8)
コード例 #3
0
def test_withdraw(info, login):
    if "#member_id#" in info['json']:
        info["json"] = info["json"].replace("#member_id#", str(login['id']))
    if "#wrong_member_id#" in info['json']:
        info["json"] = info["json"].replace('#wrong_member_id#',
                                            str(login['id'] + 10))
    if "#amount#" in info["json"]:
        info["json"] = info["json"].replace('#amount#',
                                            str(before_recharge_money + 1))

    headers = json.loads(info['headers'])
    headers['Authorization'] = login['token']
    res = requests.request(method=info['method'],
                           url=yaml_config['host'] + info['url'],
                           headers=headers,
                           json=json.loads(info['json']))
    res_body = res.json()
    try:
        assert res_body['code'] == info["expected"]
    except AssertionError as e:
        logger.error("用例失败:{}".format(e))
        raise e
    finally:
        excel = ExcelHandler(excel_file)
        excel.write('withdraw',
                    str(res_body),
                    row=int(info['case_id'] + 1),
                    column=9)
        after_recharge_money = db.query(sql)['leave_amount']
        if json.loads(info["json"])['amount']:
            money = json.loads(info["json"])['amount']
        if res_body['code'] == info["expected"]:
            excel.write('withdraw',
                        True,
                        row=int(info['case_id'] + 1),
                        column=8)
            if str(money).isdigit():
                # if after_recharge_money == before_recharge_money - decimal.Decimal(money):
                if float(after_recharge_money
                         ) == float(before_recharge_money) - float(money):
                    excel.write('withdraw',
                                "充值成功",
                                row=int(info['case_id'] + 1),
                                column=8)
        else:
            excel.write('withdraw',
                        False,
                        row=int(info['case_id'] + 1),
                        column=8)
コード例 #4
0
ファイル: handler.py プロジェクト: zengcong1314/python1205
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()
コード例 #5
0
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
コード例 #6
0
ファイル: handler.py プロジェクト: zengcong1314/python1205
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
コード例 #7
0
    def test_recharge(self, case_info):
        """测试充值接口"""

        # data = case_info["data"]
        # if "#member_id#" in data:
        #     data = data.replace("#member_id#", str(self.member_id))
        # data = eval(data)
        #
        # headers = case_info["headers"]
        # if "#token#" in headers:
        #     headers = headers.replace("#token#", self.token)

        data = env_data.replace_data(case_info["data"])
        print(data)
        headers = env_data.replace_data(case_info["headers"])
        print(headers)

        # 充值之前查余额
        user_money = self.db.query(
            "SELECT leave_amount FROM member WHERE id ={}".format(
                self.member_id))
        before_amount = user_money["leave_amount"]
        # 金额大于500000调用提现接口
        if before_amount >= 500000:
            env_data.withdraw()
        logger.info("正在执行第{}条用例:{}".format(case_info["case_id"],
                                           case_info["title"]))
        data = json.loads(data)
        resp = requests_handler.visit(url=env_data.yaml_data["host"] +
                                      case_info["url"],
                                      method=case_info["method"],
                                      headers=json.loads(headers),
                                      json=data)
        print(resp)
        data_path = os.path.join(env_data.config.DATA_PATH, "testcases.xlsx")
        try:
            expected = eval(case_info["expected"])
            self.assertTrue(expected["code"] == resp["code"])
            self.assertTrue(expected["msg"] == resp["msg"])

            if resp["code"] == 0:
                user_money = self.db.query(
                    "SELECT leave_amount FROM member WHERE id ={}".format(
                        self.member_id))
                after_amount = user_money["leave_amount"]
                self.assertTrue(
                    Decimal(str(before_amount)) +
                    Decimal(str(data["amount"])) == Decimal(str(after_amount)))
            self.result = "PASS"
            logger.info("第{}条测试用例通过".format(case_info["case_id"]))
        except AssertionError as e:
            self.result = "FAIL"
            logger.error("第{}条测试用例无法通过:{}".format(case_info["case_id"], e))
            raise e
        finally:
            ExcelHandler(data_path).write(sheet_name="recharge",
                                          row=case_info["case_id"] + 1,
                                          column=9,
                                          data=self.result)
コード例 #8
0
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
コード例 #9
0
def test_register_01(test_info):
    # actual_url = 'http://api.lemonban.com/futureloan/member/register'
    # actual_method = 'POST'
    # actual_json = {"mobile_phone":"","pwd":""}
    # actual_headers = {"X-Lemonban-Media-Type":"lemonban.v2"}
    # expected = 2
    # 元组要控制索引
    # actual_url = test_info[3]
    # actual_method = test_info[6]
    # actual_json = test_info[4]
    # actual_headers = test_info[5]
    # expected = test_info[7]
    # 字典取值
    actual_url = test_info['url']
    actual_method = test_info['method']
    actual_json = test_info['json']
    actual_headers = test_info['headers']
    expected = test_info['expected']
    # 读取 test_info['json'],
    # 如果存在 # new_phone,
    if '#new_phone#' in actual_json:
        # 生成手机号码 13789456789 generate_new_phone
        mobile_phone = generate_new_phone()
        # 替换为new_phone
        actual_json = actual_json.replace('#new_phone#', mobile_phone)
    # 传入都是字符串
    res = requests.request(method=actual_method,
                           url=yaml_config['host'] + actual_url,
                           headers=eval(actual_headers),
                           json=eval(actual_json))
    res_body = res.json()
    print(res_body)
    try:
        assert res_body['code'] == expected
    except AssertionError as e:
        logger.error("用例失败:{}".format(e))
        raise e
    finally:
        excel = ExcelHandler(excel_file)
        excel.write('register',
                    str(res_body),
                    row=int(test_info['case_id']) + 1,
                    column=9)
        if res_body['code'] == expected:
            excel.write('register',
                        'True',
                        row=int(test_info['case_id']) + 1,
                        column=8)
        else:
            excel.write('register',
                        'False',
                        row=int(test_info['case_id']) + 1,
                        column=8)
コード例 #10
0
def test_recharge(info,login):
    """充值"""
    """先要替换"""
    if "#member_id#" in info['json']:
        info["json"] = info["json"].replace('#member_id#',str(login['id']))
    if "#wrong_member_id#" in info['json']:
        info["json"] = info["json"].replace('#wrong_member_id#', str(login['id'] + 1))

    # # token组装方式1:通过excel替换
    # if "#token#" in info['headers']:
    #     info["headers"] = info["headers"].replace("#token#",login['token'])

    # token 组装2:通过headers 添加,excel 表格里面不需要Authorization
    headers = json.loads(info["headers"])
    headers['Authorization'] = login['token']

    # 数据库访问,充值之前的余额
    db = DBHandler()
    sql = 'select leave_amount from member where id={}'.format(login['id'])
    result = db.query(sql)
    before_recharge_money =result['leave_amount']
    db.db_colse()

    data = json.loads(info['json'])
    res= requests.request(url= yaml_config['host'] + info['url'],
                     method=info['method'],
                     headers=headers,
                     json= data)
    res_body = res.json()
    print(res_body)
    try:
        assert res_body['code'] == info["expected"]
    except AssertionError as e:
        logger.error("用例失败:{}".format(e))
        raise e
    finally:
        excel = ExcelHandler(excel_file)
        excel.write('recharge',str(res_body),row=int(info['case_id']+1),column=9)
        if res_body['code'] == 0:
            db = DBHandler()
            sql = 'select leave_amount from member where id={}'.format(login['id'])
            result = db.query(sql)
            after_recharge_money = result['leave_amount']
            db.db_colse()
            money = Decimal(str(data['amount']))
            assert before_recharge_money + money == after_recharge_money
        if res_body['code'] == info["expected"]:
            excel.write('recharge',True,row=int(info['case_id']+1),column=8)
        else:
            excel.write('recharge',False,row=int(info['case_id']+1),column=8)
コード例 #11
0
class MiddleHandler:
    """中间层处理"""

    # yaml模块
    yaml_data = get_yaml_data(file_name=config_file_path)

    # 需要替换的数据
    admin_user_name = yaml_data["admin_user"]["user_name"]
    admin_user_pwd = yaml_data["admin_user"]["password"]
    loan_user_name = yaml_data["loan_user"]["user_name"]
    loan_user_pwd = yaml_data["loan_user"]["password"]
    invest_user_name = yaml_data["invest_user"]["user_name"]
    invest_user_pwd = yaml_data["invest_user"]["password"]
    phone_number = ""

    @classmethod
    def replace_data(cls, string, pattern="#(.*?)#"):
        """替换数据"""
        replace_data = re.finditer(pattern=pattern, string=string)
        for data in replace_data:
            old_data = data.group()
            new_data = str(getattr(cls, data.group(1)))
            string = string.replace(old_data, new_data)
        return string

    # logger模块
    my_logger = get_logger(logger_name=yaml_data["logger"]["logger_name"],
                           logger_level=yaml_data["logger"]["logger_level"],
                           stream_handler_level=yaml_data["logger"]["stream_handler_level"],
                           file_handler_level=yaml_data["logger"]["file_handler_level"],
                           file_name=logs_file_path,
                           format_data=yaml_data["logger"]["format_data"])

    # excel模块
    my_excel = ExcelHandler(file_path=data_file_path)

    # db模块
    db_class = MiddleDb

    # support模块
    @classmethod
    def get_random_phone_num(cls):
        """获取任意手机号"""
        fake = faker.Faker(locale="zh_CN")
        while True:
            phone_num = fake.phone_number()
            my_db = MiddleHandler.db_class()
            phone_num_db = my_db.query_db(sql="select * from member where mobile_phone = {};".format(phone_num))
            my_db.close_db()
            if not phone_num_db:
                cls.phone_number = phone_num
                return phone_num
コード例 #12
0
ファイル: test_audit.py プロジェクト: huangke888/future_loan
    def test_audit(self, case_info):
        """测试提现接口"""
        logger.info("正在执行第{}条用例:{}".format(case_info["case_id"],
                                           case_info["title"]))
        data = case_info["data"]
        if "#loan_id#" in data:
            data = data.replace("#loan_id#", str(self.loan_id))

        if "#pass_loan_id#" in data:
            loan_info = self.db.query("SELECT * FROM loan WHERE status != 1")
            data = data.replace("#pass_loan_id#", str(loan_info["id"]))

        headers = case_info["headers"]
        if "#admin_token#" in headers:
            headers = headers.replace("#admin_token#", self.admin_token)

        if "#token#" in headers:
            headers = headers.replace("#token#", self.token)

        resp = visit(url=env_data.yaml_data["host"] + case_info["url"],
                     method=case_info["method"],
                     headers=eval(headers),
                     json=eval(data))
        print(resp)
        data_path = os.path.join(env_data.config.DATA_PATH, "testcases.xlsx")
        try:
            expected = json.loads(case_info["expected"])
            self.assertTrue(expected["code"] == resp["code"])
            self.assertTrue(expected["msg"] == resp["msg"])

            if resp["code"] == 0:
                # 验证数据库状态
                loan_info_after = self.db.query(
                    "SELECT * FROM loan WHERE id={}".format(self.loan_id))
                # a = loan_info_after["status"]
                # b = eval(case_info["expected"])["status"]
                # print(a)
                # print(b)
                self.assertTrue(
                    loan_info_after["status"] == expected["status"])
            self.result = "PASS"
            logger.info("第{}条测试用例通过".format(case_info["case_id"]))
        except AssertionError as e:
            self.result = "FAIL"
            logger.error("第{}条测试用例无法通过:{}".format(case_info["case_id"], e))
            raise e
        finally:
            ExcelHandler(data_path).write(sheet_name="audit",
                                          row=case_info["case_id"] + 1,
                                          column=9,
                                          data=self.result)
コード例 #13
0
ファイル: handler.py プロジェクト: gaoyang1224/mysite
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
コード例 #14
0
    def test_invest(self, case_info):
        """测试投资接口"""
        # before_data = self.db.query(
        #     "SELECT COUNT(*) as berfore_num FROM loan WHERE member_id={};".format(self.member_id))
        # before_num = before_data["berfore_num"]
        logger.info("正在执行第{}条用例:{}".format(case_info["case_id"],
                                           case_info["title"]))
        data = case_info["data"]
        if "#member_id#" in data:
            data = data.replace("#member_id#", str(self.member_id))

        headers = case_info["headers"]
        if "#token#" in headers:
            headers = headers.replace("#token#", self.token)

        if "#loan_id#" in data:
            data = data.replace("#loan_id#", str(self.pass_loan_id))

        # 访问接口
        data_1 = self.db.query("SELECT * FROM loan WHERE id = {}".format(
            self.pass_loan_id))
        resp = visit(url=env_data.yaml_data["host"] + case_info["url"],
                     method=case_info["method"],
                     json=eval(data),
                     headers=eval(headers))
        print(resp)
        data_path = os.path.join(env_data.config.DATA_PATH, "testcases.xlsx")
        try:
            for k, v in json.loads(case_info["expected"]).items():
                self.assertTrue(v == resp[k])
            # if resp["code"] == 0:
            #     after_data = self.db.query(
            #         "SELECT COUNT(*) as after_num FROM loan WHERE member_id={};".format(self.member_id))
            #     after_num = after_data["after_num"]
            #     self.assertTrue(before_num + 1 == after_num)
            self.result = "PASS"
            logger.info("第{}条测试用例通过".format(case_info["case_id"]))

        except AssertionError as e:
            self.result = "FAIL"
            logger.error("第{}条测试用例无法通过:{}".format(case_info["case_id"], e))
            raise e
        finally:
            ExcelHandler(data_path).write(sheet_name="add",
                                          row=case_info["case_id"] + 1,
                                          column=9,
                                          data=self.result)
コード例 #15
0
class Handler():
    # 环境地址
    host = "http://120.78.128.25:8766/"

    # 获取yaml文件内容
    yaml_data = red_config(config.CONF_PATH)
    # 初始化logger
    logger = get_logging(**yaml_data["log"], file_name=config.LOG_PATH)
    # 读取Excel表格
    excel = ExcelHandler(
        os.path.join(config.DATA_PATH, yaml_data["excel"]["file_name"]))

    # 发送邮件
    # send_mail = send_mail(**yaml_data["email_address"], file_name="")

    @property
    def token(self):
        return login(Handler.yaml_data["user"])["token"]

    @property
    def other_token(self):
        return login(Handler.yaml_data["other_user"])["token"]

    @property
    def member_id(self):
        return login(Handler.yaml_data["user"])["member_id"]

    @property
    def other_member_id(self):
        return login(Handler.yaml_data["other_user"])["member_id"]

    @property
    def admin_token(self):
        return login(Handler.yaml_data["admin_user"])["token"]

    @property
    def loan_id(self):
        return loan_id()

    @property
    def loan_id_pass(self):
        return loan_id_pass()

    @property
    def audit_loan_id(self):
        return audit_loan_id()
コード例 #16
0
def test_recharge(info, login):
    """充值"""
    """先要替换"""
    if "#member_id#" in info['json']:
        info["json"] = info["json"].replace('#member_id#', str(login['id']))
    if "#wrong_member_id#" in info['json']:
        info["json"] = info["json"].replace('#wrong_member_id#',
                                            str(login['id'] + 1))

    # token组装方式1:通过excel替换
    if "#token#" in info['headers']:
        info["headers"] = info["headers"].replace("#token#", login['token'])

    res = requests.request(url=yaml_config['host'] + info['url'],
                           method=info['method'],
                           headers=json.loads(info['headers']),
                           json=json.loads(info['json']))
    res_body = res.json()
    print(res_body)
    try:
        assert res_body['code'] == info["expected"]
    except AssertionError as e:
        logger.error("用例失败:{}".format(e))
        raise e
    finally:
        excel = ExcelHandler(excel_file)
        excel.write('recharge',
                    str(res_body),
                    row=int(info['case_id'] + 1),
                    column=9)
        if res_body['code'] == info["expected"]:
            excel.write('recharge',
                        True,
                        row=int(info['case_id'] + 1),
                        column=8)
        else:
            excel.write('recharge',
                        False,
                        row=int(info['case_id'] + 1),
                        column=8)
コード例 #17
0
class Handler():
    # 环境地址
    host = ""

    # 获取yaml文件内容
    yaml_data = red_config(config.CONF_PATH)
    # 初始化logger
    logger = get_logging(**yaml_data["log"], file_name=config.LOG_PATH)
    # 读取Excel表格
    excel = ExcelHandler(
        os.path.join(config.DATA_PATH, yaml_data["excel"]["file_name"]))

    # 发送邮件
    # send_mail = send_mail(**yaml_data["email_address"], file_name="")

    @property
    def plate(self):
        return random_plate()

    @property
    def no_bind_sn(self):
        return no_bind_sn()

    @property
    def bind_sn(self):
        return bind_sn()

    @property
    def self_bind_sn(self):
        return self_bind_sn(1)

    @property
    def self_bind_carid(self):
        return self_bind_carid(1)

    @property
    def attention_carid(self):
        return attention_carid(1)
コード例 #18
0
class TestRecharge(unittest.TestCase):
    # def setUp(self) -> None:
    # 读取Excel里数据
    excel_handler = ExcelHandler(config.data_path)
    data = excel_handler.total_test("recharge")
    # 读取yaml里的数据
    # yaml_data =YamlHandler(config.yaml_config_path).yaml_read()
    logger = LoggerHandler(
        name=yaml_data["logger"]["name"],
        level=yaml_data["logger"]["level"],
        file=yaml_data["logger"]["file"],
    )

    def setUp(self) -> None:
        # 实例化
        self.req = RequestHandler()
        # 一次操作用的是一个db对象,所以放前置条件当中
        self.db = DBhandler(host=yaml_data["database"]["host"],
                            port=yaml_data["database"]["port"],
                            password=yaml_data["database"]["password"],
                            user=yaml_data["database"]["user"],
                            charset=yaml_data["database"]["charset"],
                            database=yaml_data["database"]["database"])
        # 登录
        # save_token()
        # self.token=Context.token
        # self.member_id=Context.member_id

    def tearDown(self) -> None:
        # 关闭浏览器
        self.req.close_session()
        self.db.close()

    @ddt.data(*data)
    def test_recharge(self, test_data):
        """充值接口
        1、替换json数据当中member_id
        2、访问接口,得到实际结果
        3、断言实际结果,同时需要查数据库里面充值金额是否正确"""
        # 进行充值时候member_id是动态变化的,amount是规定好的可以写死,headers里需要用登陆时候返回的token:
        # 处理token第一种:在Excel里的headers里,用## 动态生成,然后用replace替换;第二种是在前置条件登陆中拿到token,然后再发送requests请求中的headers上拼接上token
        # 充值之前,查询数据库,获取充值之前的余额
        member_id = Context().member_id
        token = Context().token

        sql = "select * from member where id=%s;"
        user = self.db.query(sql, args=[member_id])
        before_money = user["leave_amount"]

        if "#member_id#" in test_data["json"]:
            test_data["json"] = test_data["json"].replace(
                "#member_id#", str(member_id))
        # 错误的用户名用例,只要不要等于当前登录的id就行,可以id+1 +2 都行
        if "#other_id#" in test_data["json"]:
            test_data["json"] = test_data["json"].replace(
                "#other_id#", str(member_id + 1))
        # 读取Excel中headers,这个得到的是字典
        headers = json.loads(test_data["headers"])
        # 得到Authorization信息头
        headers["Authorization"] = token
        res = self.req.visit(test_data["method"],
                             config.host + test_data["url"],
                             json=json.loads(test_data["json"]),
                             headers=headers)
        print(res)

        # 获得expected,然后断言
        try:
            self.assertEqual(test_data["expected"], res["code"])
            # 第二次断言,充值成功的用例需要进行数据库校验,金额
            # 判断是否为成功用例,通过返回码判断,如果没有code可以用msg 或者在Excel新增一列tag ,success
            if res["code"] == 0:
                # 查看数据库结果,充值之前的金额+ 充值的金额=充值后的金额
                money = json.loads(test_data["json"])["amount"]
                # 获取充值之前的金额:第一种办法是通过save_token返回的leave_amount,这个方法如果是多次充值的时候,会获取失败,为此应该把save_token()放前置条件中,保证每次用例之前都获取一次

                sql = "select * from member where id=%s;"
                after_user = self.db.query(sql, args=[member_id])
                after_money = after_user["leave_amount"]
                self.assertEqual(before_money + Decimal(money), after_money)

            # 写入Excel 中实际结果
            self.excel_handler.write_cell("recharge", config.data_path,
                                          test_data["case_id"] + 1, 9, "用例通过")
        except AssertionError as e:
            # 记录logger
            self.logger.error("测试用例失败".format(e))
            # 手动抛出异常,否则测试用例会自动通过,写入Excel
            self.excel_handler.write_cell("recharge", config.data_path,
                                          test_data["case_id"] + 1, 9, "用例失败")
            raise e
コード例 #19
0
# @Time     : 2020/2/1 16:21
# @Author   : zky_wind
# @Email    : [email protected]
# @File     : test_login.py
# @Software : PyCharm
import json
import unittest

from common.excel_handler import ExcelHandler
from common.logger_handler import logger
from common.request_handler import RequestHandler
from config.setting import config
from libs import ddt

# 读取数据
excel_handler = ExcelHandler(config.data_path)
data = excel_handler.get_data('case_login')


@ddt.ddt
class TestRegister(unittest.TestCase):
    def setUp(self) -> None:
        # 初始化一个session会话
        self.request = RequestHandler()
        # 定义一个测试结果
        self.result = 'NT'

    def tearDown(self) -> None:
        # 关闭session会话
        self.request.close_session()
コード例 #20
0
ファイル: test_recharge.py プロジェクト: gaoyang1224/mysite
"""充值接口测试"""

import pytest
import os
import json

import requests

from common.logger_handler import logger
from config import path
from common.excel_handler import ExcelHandler
from common.yaml_handler import yaml_config, user_config
from common.helper import generate_new_phone

excel_file = os.path.join(path.data_path, 'cases.xlsx')
data = ExcelHandler(excel_file).read('recharge')


@pytest.mark.parametrize('info', data)
def test_recharge(info, login):
    """充值"""
    # 先要替换
    if "#member_id#" in info['data']:
        info["data"] = info["data"].replace('#member_id#', str(login['id']))

    # token 组装方式 1:通过excel 替换
    # if "#token#" in info['headers']:
    #     info["headers"] = info["headers"].replace('#token#', login['token'])

    # token 组装2: 通过 headers 添加
    headers = json.loads(info["headers"])
コード例 #21
0
ファイル: middle.py プロジェクト: davypython/py36_tests
class MidHandler():
    """任务:中间层。common和调用层,使用项目的配置数据,填充common模块"""
    # 设置属性
    new_phone = ''
    investor_user_id = ''
    investor_user_token = ''
    admin_user_id = ''
    admin_user_token = ''
    load_id = ''
    load_token = ''

    yaml_config = YamlHandler('config.yaml').yaml_load()
    safe_config = YamlHandler('safe.yaml').yaml_load()
    # logger获取
    log_file = os.path.join(logs_path, yaml_config['logger']['File'])
    logger = LoggerHandler(
        Logger_Name=yaml_config['logger']['Logger_Name'],
        File=log_file,
        Logger_Level=yaml_config['logger']['Logger_Level'],
        Hand_Level=yaml_config['logger']['Hand_Level'],
        File_Hand_Level=yaml_config['logger']['File_Hand_Level'])

    # 需要替换的数据
    investor_phone = safe_config['investor_user']['mobile_phone']
    investor_pwd = safe_config['investor_user']['pwd']
    admin_phone = safe_config['admin_user']['mobile_phone']
    admin_pwd = safe_config['admin_user']['pwd']
    loan_phone = safe_config['loan_user']['mobile_phone']
    loan_pwd = safe_config['loan_user']['pwd']

    @classmethod
    def replace_data(cls, string):
        '''替换表格数据函数'''
        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

    # excel对象
    excel_file = os.path.join(data_path, 'cases.xlsx')
    excel = ExcelHandler(excel_file)
    # excelwrite = ExcelHandler(excel_file).write('', '哈哈', row='', column='')
    # 数据库
    db_class = MidDBHandler

    @classmethod
    def random_number_1(cls):
        '''随机生成电话'''
        while True:
            mobile_number = '1' + random.choice(['3', '5'])
            for i in range(9):
                mobile_number += str(random.randint(1, 9))
            sql = 'SELECT mobile_phone FROM member WHRER mobile_phone={};'.format(
                str(mobile_number))
            db = MidDBHandler()
            db_num = db.connect(sql, fetchone=True)
            if not db_num:
                # cls.new_phone = mobile_number
                return mobile_number
コード例 #22
0
"""测试注册功能。

"""
import requests
import pytest
from common.logger_handler import logger
from common.excel_handler import ExcelHandler

import os
from config import path
from common.yaml_handler import yaml_config
from common.helper import generate_new_phone

# 获取excel文件的路径
excel_file = os.path.join(path.data_path, 'cases.xlsx')
data = ExcelHandler(excel_file).read('register')


@pytest.mark.parametrize("test_info", data)
def test_register_01(test_info):
    """注册用例。"""
    actual_url = test_info['url']
    actual_method = test_info['method']
    actual_json = test_info['json']
    actual_headers = test_info['headers']
    expected = test_info['expected']

    # 读取 test_info['json']
    # 如果存在#new_phone#
    if '#new_phone#' in actual_json:
        # 生成手机号码 generate_new_phone
コード例 #23
0
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
コード例 #24
0
class TestInvest(unittest.TestCase):
    # 读取Excel里数据
    excel_handler = ExcelHandler(config.data_path)
    data = excel_handler.total_test("invest")
    logger = LoggerHandler(
        name=yaml_data["logger"]["name"],
        level=yaml_data["logger"]["level"],
        file=yaml_data["logger"]["file"],
    )

    def setUp(self) -> None:
        # 实例化
        self.req = RequestHandler()
        # 一次操作用的是一个db对象,所以放前置条件当中
        self.db = DBhandler(host=yaml_data["database"]["host"],
                            port=yaml_data["database"]["port"],
                            password=yaml_data["database"]["password"],
                            user=yaml_data["database"]["user"],
                            charset=yaml_data["database"]["charset"],
                            database=yaml_data["database"]["database"])
        # 登录
        # save_token()
        # self.token=Context.token
        # self.member_id=Context.member_id

    def tearDown(self) -> None:
        # 关闭浏览器
        self.req.close_session()
        self.db.close()

    @ddt.data(*data)
    def test_invest(self, test_data):
        # 获取member_id token  loan_id
        member_id = Context().member_id
        token = Context().token
        loan_id = Context().loan_id
        # 从数据库中查找id用户的原可用余额
        sql = "select * from member where id=%s;"
        user = self.db.query(sql, args=[member_id])
        before_money = user["leave_amount"]
        # 替换,把Excel里#member_id#  #loan_id# 替换成对应的id
        test_data["json"] = replace_label(test_data["json"])
        print(test_data)

        # if "%amount%" in test_data["json"]:
        #     test_data["json"]=test_data["json"].replace("%amount%",str(before_money+Decimal(100)))
        #
        # if "*amount*" in test_data["json"]:
        #     test_data["json"]=test_data["json"].replace("*amount*",str(before_money+Decimal(100)))
        if "*other_loan_id*" in test_data["json"]:
            oth_loan = self.db.query(
                "select * from loan where id=%s limit 100;", args=[1])
            test_data["json"] = test_data["json"].replace(
                "*other_loan_id*", str(oth_loan))

        headers = json.loads(test_data["headers"])
        headers["Authorization"] = token
        res = self.req.visit(test_data["method"],
                             config.host + test_data["url"],
                             json=json.loads(test_data["json"]),
                             headers=headers)
        print(res)

        try:
            self.assertEqual(test_data["expected"], res["code"])
            #  数据库断言
            if res["code"] == 0:
                money = json.loads(test_data["json"])["amount"]
                sql = "select * from member where id=%s;"
                after_user = self.db.query(sql, args=[member_id])
                after_money = after_user["leave_amount"]
                self.assertEqual(before_money - Decimal(money), after_money)

            # 写入Excel 中实际结果
            self.excel_handler.write_cell("invest", config.data_path,
                                          test_data["case_id"] + 1, 9, "用例通过")

        except AssertionError as e:
            # 记录logger
            self.logger.error("测试用例失败".format(e))
            # 手动抛出异常,否则测试用例会自动通过,写入Excel
            self.excel_handler.write_cell("invest", config.data_path,
                                          test_data["case_id"] + 1, 9, "用例失败")
            raise e
コード例 #25
0
# @Time     : 2020/1/31 19:40
# @Author   : zky_wind
# @Email    : [email protected]
# @File     : test_register.py
# @Software : PyCharm
import json
import unittest

from common.excel_handler import ExcelHandler
from common.logger_handler import logger
from common.request_handler import RequestHandler
from config.setting import config
from libs import ddt

# 读取数据
excel_handler = ExcelHandler(config.data_path)
data = excel_handler.get_data('case_register')


@ddt.ddt
class TestRegister(unittest.TestCase):
    def setUp(self) -> None:
        # 初始化一个session会话
        self.request = RequestHandler()
        # 定义一个测试结果
        self.result = 'NT'

    def tearDown(self) -> None:
        # 关闭session会话
        self.request.close_session()
コード例 #26
0
ファイル: test_invest.py プロジェクト: ybsgithup/Code
"""测试登录功能"""
import logging
import os
import unittest
import ddt
from selenium import webdriver
from config import config
from pages.home_page import HomePage
from pages.login_page import LoginPage
from common.excel_handler import ExcelHandler
# from data.login_data import cases_error, cases_invalid, cases_success


cases_error = ExcelHandler(os.path.join(config.DATA_PATH, 'cases.xlsx')).read_data("login_error")
cases_invalid = ExcelHandler(os.path.join(config.DATA_PATH, 'cases.xlsx')).read_data("login_invalid")
cases_success = ExcelHandler(os.path.join(config.DATA_PATH, 'cases.xlsx')).read_data("login_success")


@ddt.ddt
class TestLogin(unittest.TestCase):

    def setUp(self) -> None:
        """前置条件"""
        # 初始化浏览器
        # 访问被测试的网址
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(config.IMPLICTLY_WAIT_TIMEOUT)
        self.driver.maximize_window()

        self.login_page = LoginPage(self.driver)
        self.login_page.get()
コード例 #27
0
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
コード例 #28
0
ファイル: handler.py プロジェクト: zengcong1314/python1205
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
コード例 #29
0
class TestRegister(unittest.TestCase):
    # def setUp(self) -> None:
    # 读取Excel里数据
    excel_handler = ExcelHandler(config.data_path)
    data = excel_handler.total_test("register")
    # 读取yaml里的数据

    logger = LoggerHandler(
        name=yaml_data["logger"]["name"],
        level=yaml_data["logger"]["level"],
        file=yaml_data["logger"]["file"],
    )

    def setUp(self) -> None:
        # 实例化
        self.req = RequestHandler()
        # 一次操作用的是一个db对象,所以放前置条件当中
        self.db = DBhandler(host=yaml_data["database"]["host"],
                            port=yaml_data["database"]["port"],
                            password=yaml_data["database"]["password"],
                            user=yaml_data["database"]["user"],
                            charset=yaml_data["database"]["charset"],
                            database=yaml_data["database"]["database"])

    def tearDown(self) -> None:
        # 关闭浏览器
        self.req.close_session()
        self.db.close()

    @ddt.data(*data)
    def test_register(self, test_data):
        print(test_data)
        # 先判断test_data["json"]里如果出现了#exist# 就使用get_mobile随机生成手机号码
        # 查询数据库,如果数据库存在该号码,就使用整个号码,但是整个存在的概率很低,查询不到这个号码,那么Excel中这个用例就有问题
        # 所以先不生成手机号码,先随机从数据库中拿一个已经存在的号码,直接使用该号码替换
        # 然后再用replace替换"#exist#"
        if "#exist#" in test_data["json"]:
            mobile = self.db.query("select * from member limit 1 ;")
            # 判断:如果从数据库中能查到一条记录就替换,如果数据库是空数据库就会执行else
            # 上面的mobile得到的是一个字典,我们需要的是字典里的mobile_phone值
            if mobile:
                # 注意replace替换的一定是一个字符串,如果是数字需要转化
                test_data["json"] = test_data["json"].replace(
                    "#exist#", mobile["mobile_phone"])
            else:
                # 随机生成一个 13311112222,如果在库中还是不存在这条用例就会不通过
                # 解决办法:写个注册成功步骤,放到help函数当中,直接调用对应的方法进行注册
                # 先随机生成一个手机号码然后去用request发送注册成功的请求,或者通过db对象往数据库中插入一个手机号码也行,但是不提倡
                pass

        if "#new#" in test_data["json"]:
            # 先判断test_data["json"]里如果出现了#new# 就使用get_mobile随机生成手机号码
            # 查询数据库,如果数据库存在该号码,就再随机生成一个新号码,直到数据库中不存在为止
            while True:
                mobilephone = get_mobile()
                mobile = self.db.query(
                    "select * from member where mobile_phone=%s;",
                    args=[mobilephone])
                # 判断:如果随机生成的号码在数据库中就再次循环随机生成一个号码,如果随机生成的号码不在数据库就跳出循环,执行后面的替换语句
                if not mobile:
                    break
            test_data["json"] = test_data["json"].replace("#new#", mobilephone)

        # 访问接口,得到实际结果,res返回的是字典类型,Python里字典,json在Python里是字符串的形式
        res = self.req.visit(test_data["method"],
                             config.host + test_data["url"],
                             json=json.loads(test_data["json"]),
                             headers=json.loads(test_data["headers"]))
        # 获得expected,然后断言
        try:
            self.assertEqual(test_data["expected"], res["code"])
            # 写入Excel 中实际结果
            a = self.excel_handler.write_cell("register", config.data_path,
                                              test_data["case_id"] + 1, 9,
                                              "用例通过")
            print(a)

        except AssertionError as e:
            # 记录logger
            self.logger.error("测试用例失败".format(e))
            # 手动抛出异常,否则测试用例会自动通过,写入Excel
            self.excel_handler.write_cell("register", config.data_path,
                                          test_data["case_id"] + 1, 9, "用例失败")
            raise e
コード例 #30
0
import json
import os
import pytest
import requests
import decimal
from common.excel_handler import ExcelHandler
from config.path import data_path
from common.yaml_handler import yaml_config, user_config
from common.logger_hander import logger
from common.db_handler import DBHandler
from middleware.handler import Handler

excel_file = os.path.join(data_path, 'demo.xlsx')
data = ExcelHandler(excel_file).read_dict('withdraw')
db = DBHandler()
sql = 'select leave_amount from member where id={}'.format(
    user_config['investor_user']['member_id'])
before_recharge_money = db.query(sql)['leave_amount']


@pytest.mark.parametrize("info", data)
def test_withdraw(info, login):
    if "#member_id#" in info['json']:
        info["json"] = info["json"].replace("#member_id#", str(login['id']))
    if "#wrong_member_id#" in info['json']:
        info["json"] = info["json"].replace('#wrong_member_id#',
                                            str(login['id'] + 10))
    if "#amount#" in info["json"]:
        info["json"] = info["json"].replace('#amount#',
                                            str(before_recharge_money + 1))