Beispiel #1
0
 def __init__(self):
     self.con = pymysql.connect(
         host=conf.get('mysql', 'host'),
         port=conf.getint('mysql', 'port'),
         user=conf.get('mysql', 'user'),
         password=conf.get('mysql', 'password'),
         charset='utf8',
         # cursorclass=pymysql.cursors.DictCursor
     )
Beispiel #2
0
class TestLogin(unittest.TestCase):
    excel = HandleExcel(os.path.join(DATA_DIR, "apicases.xlsx"), "login")
    # 读取用例数据
    cases = excel.read_data()
    # 项目的基本地址
    base_url = conf.get('env', 'base_url')
    # 请求头
    headers = eval(conf.get('env', 'headers'))

    @list_data(cases)
    def test_login(self, item):
        # 第一步、准备用例数据
        # 1、接口地址
        url = self.base_url + item['url']
        # 2、接口请求参数
        item['data'] = replace_data(item['data'], TestLogin)

        params = eval(item['data'])
        # 3、请求头
        # 4、获取请求方法 ,并转换为小写
        method = item['method'].lower()
        # 5、用例预期结果
        expected = eval(item['expected'])
        # 第二步:请求接口,获取返回实际结果
        # requests.post(url=url, json=params, headers=self.headers)
        response = requests.request(method,
                                    url,
                                    json=params,
                                    headers=self.headers)
        res = response.json()
        # 第三步:断言
        print("预期结果:", expected)
        print("实际结果:", res)
        try:
            # 断言code和msg字段是否一致
            # self.assertEqual(expected['code'], res['code'])
            # self.assertEqual(expected['msg'], res['msg'])
            # 使用自定义的方法进行断言
            self.assertDictIn(expected, res)
        except AssertionError as e:
            # 记录日志
            my_log.error("用例--【{}】---执行失败".format(item['title']))
            my_log.exception(e)
            # 回写结果到excel(根据公司中实际需求来决定用例结果写不写到excel中) # 注:回写excel需要花费大量的时间
            raise e
        else:
            my_log.info("用例--【{}】---执行通过".format(item['title']))

    def assertDictIn(self, expected, res):
        """字典成员运算的逻辑"""
        for k, v in expected.items():
            if res.get(k) == v:
                pass
            else:
                raise AssertionError("{} not in {}".format(expected, res))
Beispiel #3
0
 def audit(cls):
     """审核"""
     url = conf.get('env', 'base_url') + '/loan/audit'
     params = {"loan_id": cls.loan_id, "approved_or_not": True}
     # 第二步:请求添加项目的接口,对项目进行审核
     res = requests.patch(url=url, json=params, headers=cls.admin_headers)
     print()
Beispiel #4
0
 def user_login(cls):
     url = conf.get('env', 'base_url') + '/member/login'
     # --------------------普通用户登录------------------------
     # 1、准备登录的数据
     params = {
         'mobile_phone': conf.get('test_data', 'mobile'),
         "pwd": conf.get('test_data', 'pwd')
     }
     headers = eval(conf.get('env', 'headers'))
     # 2、请求登录接口
     response = requests.post(url=url, json=params, headers=headers)
     res = response.json()
     # 3、提取token,放到请求头中 给后面的用例使用
     cls.token = jsonpath(res, '$..token')[0]
     headers['Authorization'] = 'Bearer ' + cls.token
     cls.headers = headers
     # 4、提取用户id
     cls.member_id = jsonpath(res, "$..id")[0]
Beispiel #5
0
    def test_invest(self, item):
        # 第一步:准备用例数据
        url = conf.get('env', 'base_url') + item['url']
        item['data'] = replace_data(item['data'], TestInvest)
        params = eval(item['data'])
        expected = eval(item['expected'])
        method = item['method']
        # ----------------投资前查询数据库---------------------------------
        # 查用户表的sql
        sql1 = 'SELECT leave_amount FROM futureloan.member WHERE id="{}"'.format(
            self.member_id)
        # 查投资记录的sql
        sql2 = 'SELECT id FROM futureloan.invest WHERE member_id="{}"'.format(
            self.member_id)
        # 查流水记录的sql
        sql3 = 'SELECT id FROM futureloan.financelog WHERE pay_member_id="{}"'.format(
            self.member_id)
        #
        if item['check_sql']:
            s_amount = self.db.find_one(sql1)[0]
            s_invest = self.db.find_count(sql2)
            s_financelog = self.db.find_count(sql3)

        # 第二步: 发生请求
        response = requests.request(method=method,
                                    url=url,
                                    json=params,
                                    headers=self.headers)
        res = response.json()
        print("预期结果:", expected)
        print("实际结果:", res)

        # -------------------投资后查询数据库--------------------------------
        if item['check_sql']:
            e_amount = self.db.find_one(sql1)[0]
            e_invest = self.db.find_count(sql2)
            e_financelog = self.db.find_count(sql3)

        # 第三步:断言
        try:
            self.assertEqual(expected['code'], res['code'])
            self.assertIn(expected['msg'], res['msg'])
            # 断言实际结果中的msg是否包含 预期结果msg中的内容
            if item['check_sql']:
                # 断言用户余额
                self.assertEqual(params['amount'], float(s_amount - e_amount))
                # 断言投资记录
                self.assertEqual(1, e_invest - s_invest)
                # 断言流水记录
                self.assertEqual(1, e_financelog - s_financelog)

        except AssertionError as e:
            my_log.error("用例--【{}】---执行失败".format(item['title']))
            my_log.exception(e)
            raise e
        else:
            my_log.info("用例--【{}】---执行成功".format(item['title']))
Beispiel #6
0
 def add_project(cls):
     url = conf.get('env', 'base_url') + '/loan/add'
     params = {
         "member_id": cls.member_id,
         "title": "借钱实现财富自由",
         "amount": 2000,
         "loan_rate": 12.0,
         "loan_term": 3,
         "loan_date_type": 1,
         "bidding_days": 5
     }
     # 第二步:请求添加项目的接口
     response = requests.post(url=url, json=params, headers=cls.headers)
     res = response.json()
     # print(res)
     # 第三步:提取项目的id,保存为类属性
     cls.loan_id = jsonpath(res, '$..id')[0]
Beispiel #7
0
def replace_data(data, cls):
    """
    替换数据
    :param data: 要进行替换的用例数据(字符串)
    :param cls: 测试类
    :return:
    """
    while re.search('#(.+?)#', data):
        res2 = re.search('#(.+?)#', data)
        item = res2.group()
        attr = res2.group(1)
        try:
            value = getattr(cls, attr)
        except AttributeError:
            value = conf.get('test_data',attr)
        # 进行替换
        data = data.replace(item, str(value))

    return data
Beispiel #8
0
    def test_add(self, item):
        # 第一步:准备数据
        url = conf.get('env', 'base_url') + item['url']
        item['data'] = replace_data(item['data'], TestAdd)
        params = eval(item['data'])
        expected = eval(item['expected'])
        method = item['method']
        # 调用接口之前:查询数据库该用户的项目数量
        sql = "SELECT * FROM futureloan.loan WHERE member_id={}".format(
            self.member_id)
        start_count = self.db.find_count(sql)
        print("调用接口之前的项目个数:", start_count)
        # 第二步:调用接口,获取实际结果
        response = requests.request(method=method,
                                    url=url,
                                    json=params,
                                    headers=self.headers)
        res = response.json()

        # 调用接口之后:查询数据库该用户的项目数量
        end_count = self.db.find_count(sql)
        print("调用接口之后的项目个数:", end_count)
        # 第三步: 断言
        try:
            self.assertEqual(expected['code'], res['code'])
            self.assertEqual(expected['msg'], res['msg'])
            # 根据添加项目是否成功,来对数据库进分别的校验
            if res['msg'] == 'OK':
                self.assertEqual(end_count - start_count, 1)
            else:
                self.assertEqual(end_count - start_count, 0)
        except AssertionError as e:
            my_log.error("用例--【{}】---执行失败".format(item['title']))
            my_log.exception(e)
            raise e
        else:
            my_log.info("用例--【{}】---执行成功".format(item['title']))
class TestRegister(unittest.TestCase):
    excel = HandleExcel(os.path.join(DATA_DIR, "apicases.xlsx"), "register")
    # 读取用例数据
    cases = excel.read_data()
    # 项目的基本地址
    base_url = conf.get('env', 'base_url')
    # 请求头
    headers = eval(conf.get('env', 'headers'))
    db = HandleDB()

    @list_data(cases)
    def test_register(self, item):
        # 第一步、准备用例数据
        # 1、接口地址
        url = self.base_url + item['url']
        # 2、接口请求参数
        # 判断是否有手机号需要替换
        if '#mobile#' in item['data']:
            setattr(TestRegister, 'mobile', self.random_mobile())
            # TestRegister.mobile = self.random_mobile()

        item['data'] = replace_data(item['data'], TestRegister)
        params = eval(item['data'])
        # 3、请求头
        # 4、获取请求方法 ,并转换为小写
        method = item['method'].lower()
        # 5、用例预期结果
        expected = eval(item['expected'])

        # 第二步:请求接口,获取返回实际结果
        # requests.post(url=url, json=params, headers=self.headers)
        response = requests.request(method, url, json=params, headers=self.headers)
        res = response.json()

        # 查询数据库中该手机对应的账户数量
        sql = 'SELECT * FROM futureloan.member WHERE mobile_phone="{}"'.format(params.get('mobile_phone', ""))
        count = self.db.find_count(sql)

        # if item['check_sql']:
        #     sql = item['check_sql'].format(params.get('mobile_phone', ""))
        #     count = self.db.find_count(sql)

        # 第三步:断言
        print("预期结果:", expected)
        print("实际结果:", res)
        try:
            # 断言code和msg字段是否一致
            self.assertEqual(expected['code'], res['code'])
            self.assertEqual(expected['msg'], res['msg'])
            # 判断该用例是否需要进行数据库校验
            if item['check_sql']:
                print('数据库中查询的的数量为:', count)
                self.assertEqual(1, count)
        except AssertionError as e:
            # 记录日志
            my_log.error("用例--【{}】---执行失败".format(item['title']))
            my_log.exception(e)
            # 回写结果到excel(根据公司中实际需求来决定用例结果写不写到excel中) # 注:回写excel需要花费大量的时间
            raise e
        else:
            my_log.info("用例--【{}】---执行通过".format(item['title']))

    def random_mobile(self):
        """随机生产手机号"""
        phone = str(random.randint(13300000000, 13399999999))
        return phone
Beispiel #10
0
    # 3.1、输出到文件的配置
    fh = logging.FileHandler(filename, encoding="utf-8")
    fh.setLevel(fh_level)
    log.addHandler(fh)

    # 3.2、输出到控制台
    sh = logging.StreamHandler()
    sh.setLevel(sh_level)
    log.addHandler(sh)

    # 第四步:设置日志输出的格式
    # 4、设置日志输出的等级
    formats = '%(asctime)s - [%(filename)s-->line:%(lineno)d] - %(levelname)s: %(message)s'
    # 创建格式对象
    log_format = logging.Formatter(formats)
    # 为输出渠道设置输出格式
    sh.setFormatter(log_format)
    fh.setFormatter(log_format)

    # 返回一个日志收集器
    return log


my_log = create_log(
    name=conf.get("logging", 'name'),
    level=conf.get('logging', 'level'),
    filename=os.path.join(LOG_DIR, conf.get("logging", 'filename')),
    sh_level=conf.get('logging', 'sh_level'),
    fh_level=conf.get('logging', 'fh_level'),
)