Ejemplo n.º 1
0
class TestLoans(unittest.TestCase):
    excel = HandleExcel(case_file, "loans")
    cases = excel.read_data()
    db = HandleMysql()
    @data(*cases)
    def test_loans(self, case):
        # 第一步:准备用例数据
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        data = eval(replace_data(case["data"]))
        # 替换参数中的用户id
        headers = eval(conf.get("env", "headers"))
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        # 第二步:发送请求,获取结果
        response = request(url=url, method=method, params=data, headers=headers)
        res = response.json()
        print(response.url)
        # 第三步:断言(比对预期结果和实际结果)
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 断言返回的数据的条数
            self.assertEqual(expected["len"],len(res["data"]))
        except AssertionError as e:
            # print("预期结果:", expected)
            # print("实际结果:", res)
            self.excel.write_data(row=row, column=8, value="未通过")
            log.error("用例:{},执行未通过".format(case["title"]))
            log.exception(e)
            raise e
        else:
            self.excel.write_data(row=row, column=8, value="通过")
            log.info("用例:{},执行通过".format(case["title"]))
Ejemplo n.º 2
0
class TestUpdate(unittest.TestCase):
    excel = HandleExcel(case_file, "update")
    cases = excel.read_data()
    db = HandleMysql()

    @classmethod
    def setUpClass(cls):
        # 1、准备登录的数据
        url = conf.get("env", "url") + "/member/login"
        data = {
            "mobile_phone": conf.get("test_data", "phone"),
            "pwd": conf.get("test_data", "pwd")
        }
        headers = eval(conf.get("env", "headers"))
        # 3、发送请求,进行登录
        response = request(url=url, method="post", json=data, headers=headers)
        # 获取返回的数据
        res = response.json()
        # 3、提取token,保存为类属性
        token = jsonpath.jsonpath(res, "$..token")[0]
        token_type = jsonpath.jsonpath(res, "$..token_type")[0]
        # 将提取到的token设为类属性
        EnvData.token_value = token_type + " " + token
        # 提取用户的id,保存为类属性
        EnvData.member_id = str(jsonpath.jsonpath(res, "$..id")[0])

    @data(*cases)
    def test_update(self, case):
        # 第一步:准备用例数据
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        data = eval(replace_data(case["data"]))
        # 替换参数中的用户id
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = getattr(EnvData, "token_value")
        # 在请求头中加入setupclass中提取出来的token
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        # 第二步:发送请求,获取结果
        print("请求参数为:", data, type(data))
        response = request(url=url, method=method, json=data, headers=headers)
        res = response.json()
        # 第三步:断言(比对预期结果和实际结果)
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
        except AssertionError as e:
            print("预期结果:", expected)
            print("实际结果:", res)
            self.excel.write_data(row=row, column=8, value="未通过")
            log.error("用例:{},执行未通过".format(case["title"]))
            log.exception(e)
            raise e
        else:
            self.excel.write_data(row=row, column=8, value="通过")
            log.info("用例:{},执行通过".format(case["title"]))
Ejemplo n.º 3
0
class Test_Projects(unittest.TestCase):
    excel=Handle_Excel(os.path.join(DATA_DIR,"cases.xlsx"),"projects")
    cases=excel.read_excle()
    db=HandleMysql()

    @classmethod
    def setUpClass(cls):
        # 调用登录获取token
        cls.token=TestLogin.testlogin()
    @data(*cases)
    def test_projects(self,case):
        #准备数据
        url=conf.get("env","url")+case["url"]
        method=case["method"]
        # 随机生成一个项目名称替换
        name=self.random_name()
        setattr(EnvData,"name",name)
        data=eval(replace_data(case["data"]))
        headers = {"Authorization":self.token}
        excepted=eval(replace_data(case["expected"]))
        row_id=case["case_id"]+1
        #发送请求
        response=request(method=method,url=url,json=data,headers=headers)
        res=response.json()
        #断言
        try:
            # 调用断言的方法进行断言
            assert_dict(excepted,res)
            # 判断是否需要进行sql校验,如果有sql语句,需要去数据库查询一下是否有一条该项目的数据
            if case["check_sql"]:
                sql = replace_data(case["check_sql"])
                res_namecount = self.db.find_count(sql)
                self.assertEqual(1, res_namecount)
        except AssertionError as e:
            self.excel.wirte_excel(row=row_id, column=8, value="不通过")
            my_log.error("用例{},{},不通过".format(case["case_id"], case["title"]))
            my_log.debug("预期结果:{}".format(excepted))
            my_log.debug("实际结果:{}".format(res))
            my_log.exception(e)
            # exception将捕获到异常记录到日志中(对应的等级是error)
            # 主动抛出异常
            raise e
        else:
            self.excel.wirte_excel(row=row_id, column=8, value="通过")
            my_log.info("用例{},{},通过".format(case["case_id"], case["title"]))

    #  随机生成一个数据库未注册的项目名称
    @classmethod
    def random_name(cls):
        while True:
            randomnum = str(random.randint(0, 10000))
            name = "微信小程序项目"+randomnum
            sql = 'SELECT * FROM test.tb_projects WHERE name="{}"'.format(name,encoding='utf-8')
            res=cls.db.find_count(sql)
            if res==0:
                return name
Ejemplo n.º 4
0
class Test_Register_login(unittest.TestCase):
    excel = Handle_Excel(os.path.join(DATA_DIR, "cases.xlsx"),
                         "register_login")
    cases = excel.read_excle()
    db = HandleMysql()

    @data(*cases)
    def test_register_login(self, case):
        # 准备数据
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        # 随机生成一个用户名和邮箱,保存为类属性
        username = self.random_username()
        email = self.random_email()
        # 登录成功的用例直接用上一条注册成功的用户名登录,登录成功的那条用例不需要新生成用户名
        if case["title"] != "登录成功":
            setattr(EnvData, "username", username)
            setattr(EnvData, "email", email)
        case["data"] = replace_data(case["data"])
        data = eval(case["data"])
        # 注册成功的预期结果比对了username,这个username是随机生成的,所以设置了动态参数获取
        case["expected"] = replace_data(case["expected"])
        excepted = eval(case["expected"])
        row_id = case["case_id"] + 1
        # 发送请求
        response = request(method=method, url=url, json=data)
        res = response.json()
        # 断言
        try:
            # 调用断言的方法进行断言
            assert_dict(excepted, res)
            # 判断是否需要进行sql校验,如果有sql语句,需要去数据库查询一下是否有一条该用户名的数据
            if case["check_sql"]:
                sql = replace_data(case["check_sql"])
                res_namecount = self.db.find_count(sql)
                self.assertEqual(1, res_namecount)
        except AssertionError as e:
            self.excel.wirte_excel(row=row_id, column=8, value="不通过")
            my_log.error("用例{},{},不通过".format(case["case_id"], case["title"]))
            my_log.debug("预期结果:{}".format(excepted))
            my_log.debug("实际结果:{}".format(res))
            my_log.exception(e)
            # exception将捕获到异常记录到日志中(对应的等级是error)
            # 主动抛出异常
            raise e
        else:
            self.excel.wirte_excel(row=row_id, column=8, value="通过")
            my_log.info("用例{},{},通过".format(case["case_id"], case["title"]))

    #  随机生成一个数据库未注册的用户名
    @classmethod
    def random_username(cls):
        while True:
            randomname = str(random.randint(0, 10000000))
            name = "dingqin" + randomname
            sql = 'SELECT * FROM test.auth_user WHERE username="******"'.format(
                name, encoding='utf-8')
            res = cls.db.find_count(sql)
            if res == 0:
                return name

    #  随机生成一个数据库未注册的邮箱
    @classmethod
    def random_email(cls):
        while True:
            randomemail = str(random.randint(0, 999999999))
            add_email = ["@qq.com", "@163.com", "@sina.com"]
            lenth = len(add_email)
            randomname = random.randint(0, lenth - 1)
            reg_name = add_email[randomname]
            email = randomemail + reg_name
            sql = 'SELECT * FROM test.auth_user WHERE email="{}"'.format(
                email, encoding='utf-8')
            res = cls.db.find_count(sql)
            if res == 0:
                return email
Ejemplo n.º 5
0
"""
============================
Author:柠檬班-木森
Time:2020/3/26   21:44
E-mail:[email protected]
Company:湖南零檬信息技术有限公司
============================
"""

import random
from common.handle_db import HandleMysql

db = HandleMysql()


def random_phone():
    """生成一个数据库里面未注册的手机号码"""

    while True:
        phone = "155"
        for i in range(8):
            r = random.randint(0, 9)
            phone += str(r)
        sql = "SELECT * FROM futureloan.member WHERE mobile_phone={}".format(
            phone)
        res = db.find_count(sql)
        if res == 0:
            return phone


res = random_phone()
Ejemplo n.º 6
0
class TestAudit(unittest.TestCase):
    excel = HandleExcel(os.path.join(DATA_DIR, "apicases.xlsx"), "audit")
    cases = excel.read_excel()
    db = HandleMysql()

    @classmethod
    def setUpClass(cls):
        """普通用户和管理员用户登录"""
        # 普通用户登录
        # 数据准备
        url = conf.get("env", "BASE_URL") + "member/login"
        data = {"mobile_phone": conf.get("test_phone", "phone"), "pwd": conf.get("test_phone", "pwd")}
        headers = eval(conf.get("env", "headers"))
        response = requests.request(method="post", url=url, json=data, headers=headers)
        res1 = response.json()
        # 普通用户member_id和token获取
        user_member_id = jsonpath.jsonpath(res1, "$..id")[0]
        user_token = "Bearer" + " " + jsonpath.jsonpath(res1, "$..token")[0]
        # 管理员用户登录
        data2 = {"mobile_phone": conf.get("test_phone", "admin_phone"), "pwd": conf.get("test_phone", "admin_pwd")}
        response2 = requests.request(method="post", url=url, json=data2, headers=headers)
        res2 = response2.json()
        print(res2)
        # 管理员member_id和token获取
        admin_member_id = jsonpath.jsonpath(res2, "$..id")[0]
        admin_token = "Bearer" + " " + jsonpath.jsonpath(res2, "$..token")[0]
        # member_id和token存储
        setattr(EnvData, "user_member_id", user_member_id)
        setattr(EnvData, "user_token", user_token)
        setattr(EnvData, "admin_member_id", admin_member_id)
        setattr(EnvData, "admin_token", admin_token)

    def setUp(self):
        # 每条用例之前的前置条件:添加一个新的项目
        url = conf.get("env", "BASE_URL") + "/loan/add"
        data = {"member_id": getattr(EnvData, "user_member_id"), "title": "借钱实现财富自由", "amount": 2000, "loan_rate": 12.0,
                "loan_term": 3, "loan_date_type": 1, "bidding_days": 5}
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = getattr(EnvData, "user_token")
        response = requests.request(method="post", url=url, json=data, headers=headers)
        res = response.json()
        # 项目的id存储为环境变量
        setattr(EnvData, "loan_id", str(jsonpath.jsonpath(res, "$..id")[0]))

    @data(*cases)
    def test_audit(self, case):
        # 第一步:准备测试数据
        # 调用方法
        method = case["method"]
        # 调用地址
        url = conf.get("env", "BASE_URL") + case["url"]
        # 调用参数
        data = eval(replace_data(case["data"]))
        # 调用信息头
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = getattr(EnvData, "admin_token")
        # 预期结果
        expected = eval(case["expected"])
        # 是否有数据库校验
        if case["check_sql"]:
            sql = replace_data(case["check_sql"])
            start_count = self.db.find_count(sql)
        # 回写的行
        row = case["case_id"] + 1
        # 第二步:接口调用
        response = requests.request(method=method, url=url, json=data, headers=headers)
        res = response.json()
        if case["title"] == "审核通过" and res["msg"] == "OK":
            # 判断有“审核通过”的案例,已经审核通过,保存项目id
            setattr(EnvData, "pass_loan_id", str(data["loan_id"]))
            print("------------------------",EnvData.pass_loan_id)
        # 第三步:断言和回写
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 是否需要数据库校验
            if case["check_sql"]:
                sql = replace_data(case["check_sql"])
                status = self.db.find_one(sql)["status"]
                self.assertEqual(expected["status"], status)
        except AssertionError as e:
            # 结果回写excel中
            log.error("用例--{}--执行未通过".format(case["title"]))
            log.debug("预期结果:{}".format(expected))
            log.debug("实际结果:{}".format(res))
            log.exception(e)
            self.excel.write_excel(row=row, column=8, value="未通过")
            raise e
        else:
            # 结果回写excel中
            log.info("用例--{}--执行通过".format(case["title"]))
            self.excel.write_excel(row=row, column=8, value="通过")
Ejemplo n.º 7
0
class Test_Name_email_exist(unittest.TestCase):
    excel = Handle_Excel(os.path.join(DATA_DIR, "cases.xlsx"),
                         "name_email_exist")
    cases = excel.read_excle()
    db = HandleMysql()

    @data(*cases)
    def test_name_email_exist(self, case):
        # 准备数据
        # 随机生成一个用户名,保存为类属性
        username = self.random_username()
        setattr(EnvData, "username", username)
        # 随机生成一个email,保存为类属性
        email = self.random_email()
        setattr(EnvData, "email", email)
        url = conf.get("env", "url") + replace_data(case["url"])
        method = case["method"]
        # 随机生成的用户名去数据库查询,如果能查到count为1.否则为0,然后替换掉expected中的count
        if case["check_sql"]:
            sql = replace_data(case["check_sql"])
            namecount = self.db.find_count(sql)
            if namecount == 0:
                count = 0
                setattr(EnvData, "count", str(count))
            else:
                count = 1
                setattr(EnvData, "count", str(count))
        # 注册成功的预期结果比对了username,这个username是随机生成的,所以设置了动态参数获取
        case["expected"] = replace_data(case["expected"])
        excepted = eval(case["expected"])
        row_id = case["case_id"] + 1

        # 发送请求
        response = request(method=method, url=url)
        res = response.json()

        # 断言
        try:
            # 调用断言的方法进行断言
            assert_dict(excepted, res)
        except AssertionError as e:
            self.excel.wirte_excel(row=row_id, column=7, value="不通过")
            my_log.error("用例{},{},不通过".format(case["case_id"], case["title"]))
            my_log.debug("预期结果:{}".format(excepted))
            my_log.debug("实际结果:{}".format(res))
            my_log.exception(e)
            # exception将捕获到异常记录到日志中(对应的等级是error)
            # 主动抛出异常
            raise e
        else:
            self.excel.wirte_excel(row=row_id, column=7, value="通过")
            my_log.info("用例{},{},通过".format(case["case_id"], case["title"]))

    #  随机生成一用户名
    @classmethod
    def random_username(cls):
        while True:
            randomname = str(random.randint(0, 6000000))
            name = "dingqin" + randomname
            return name

    #  随机生成一个数据库未注册的邮箱
    @classmethod
    def random_email(cls):
        while True:
            randomemail = str(random.randint(0, 999999999))
            add_email = ["@qq.com", "@163.com", "@sina.com"]
            lenth = len(add_email)
            randomname = random.randint(0, lenth - 1)
            reg_name = add_email[randomname]
            email = randomemail + reg_name
            sql = 'SELECT * FROM test.auth_user WHERE email="{}"'.format(
                email, encoding='utf-8')
            res = cls.db.find_count(sql)
            if res == 0:
                return email
Ejemplo n.º 8
0
class TestLogin(unittest.TestCase):
    excel = HandleExcel(case_file, "invest")
    cases = excel.read_data()
    db = HandleMysql()

    @data(*cases)
    def test_login(self, case):
        # 第一步:准备用例数据
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        case["data"] = replace_data(case["data"])
        data = eval(case["data"])
        headers = eval(conf.get("env", "headers"))
        # 判断是否是登录接口,不是登录接口则需要添加token
        if case["interface"] != "login":
            headers["Authorization"] = getattr(EnvData, "token_value")

        expected = eval(case["expected"])
        row = case["case_id"] + 1
        # 获取需要sql校验的数据:
        if case["check_sql"]:
            sql1 = "SELECT * FROM futureloan.member where id={}".format(
                EnvData.member_id)
            sql2 = "SELECT * FROM futureloan.invest WHERE member_id={} and loan_id={}".format(
                EnvData.member_id, EnvData.loan_id)
            sql3 = "SELECT * FROM futureloan.financelog WHERE pay_member_id={}".format(
                EnvData.member_id)
            # 获取开始的用户余额
            start_amount = self.db.find_one(sql1)["leave_amount"]
            # 获取开始的投资记录条数
            start_invest = self.db.find_count(sql2)
            # 获取用户开始的流水记录条数
            start_fin = self.db.find_count(sql3)

        # 第二步:发送请求,获取结果
        response = request(url=url, method=method, json=data, headers=headers)
        res = response.json()
        # 发送请求后,判断是否是登陆接口
        if case["interface"].lower() == "login":
            # 提取用户id保存为类属性
            EnvData.member_id = str(jsonpath.jsonpath(res, "$..id")[0])
            token = jsonpath.jsonpath(res, "$..token")[0]
            token_type = jsonpath.jsonpath(res, "$..token_type")[0]
            # 提取token,保存为类属性
            EnvData.token_value = token_type + " " + token
        # 判断是否是加标的用例,如果是的则请求标id
        if case["interface"] == "add":
            EnvData.loan_id = str(jsonpath.jsonpath(res, "$..id")[0])
        # 第三步:断言(比对预期结果和实际结果)
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertIn(expected["msg"], res["msg"])
            # 判断是否需要进行数据库校验
            if case["check_sql"]:
                sql1 = "SELECT * FROM futureloan.member where id={}".format(
                    EnvData.member_id)
                sql2 = "SELECT * FROM futureloan.invest WHERE member_id={} and loan_id={}".format(
                    EnvData.member_id, EnvData.loan_id)
                sql3 = "SELECT * FROM futureloan.financelog WHERE pay_member_id={}".format(
                    EnvData.member_id)
                # 获取投资后的用户余额
                end_amount = self.db.find_one(sql1)["leave_amount"]
                self.assertEqual(start_amount - end_amount,
                                 Decimal(str(data["amount"])))
                # 获取投资后投资记录条数
                end_invest = self.db.find_count(sql2)
                self.assertEqual(end_invest - start_invest, 1)
                # 获取用户投资后的流水记录条数
                end_fin = self.db.find_count(sql3)
                self.assertEqual(end_fin - start_fin, 1)
                # 在这里可以再判断是否是满标的投资用例,如果是满标的用例,再去校验该标的每一条投资记录有没有生成对应的回款计划表
                if "满标" in case["title"]:
                    # 获取当前标所有的投资记录id
                    sql4 = "SELECT id FROM futureloan.invest WHERE loan_id={}".format(
                        EnvData.loan_id)
                    invest_ids = self.db.find_all(sql4)
                    # 遍历该标所有的投资记录的id
                    for invest in invest_ids:
                        sql5 = "SELECT * FROM futureloan.repayment WHERE invest_id={}".format(
                            invest["id"])
                        # 获取当前这条投资记录,生成对应的回款计划
                        count = self.db.find_count(sql5)
                        # 断言查询到的条数的布尔值是否为True(0的布尔值是False,只要不是0条,这个断言就会通过)
                        self.assertTrue(count)
        except AssertionError as e:
            self.excel.write_data(row=row, column=8, value="未通过")
            log.error("用例:{},执行未通过".format(case["title"]))
            log.exception(e)
            raise e
        else:
            self.excel.write_data(row=row, column=8, value="通过")
            log.info("用例:{},执行通过".format(case["title"]))
class TestWithdraw(unittest.TestCase):
    excel = HandleExcel(os.path.join(DATA_DIR, "apicases.xlsx"), "withdraw")
    cases = excel.read_excel()
    db = HandleMysql()

    @classmethod
    def setUpClass(cls):
        # 第一步:准备用例数据
        # 请求方法
        method = "post"
        # 请求地址
        url = conf.get("env", "BASE_URL") + "/member/login"
        # 请求参数
        data = {
            "mobile_phone": conf.get("test_phone", "phone"),
            "pwd": conf.get("test_phone", "pwd")
        }
        # 请求头
        headers = eval(conf.get("env", "headers"))
        response = requests.request(method=method,
                                    url=url,
                                    json=data,
                                    headers=headers)
        res = response.json()
        print("登录出参:", res)
        cls.member_id = str(jsonpath.jsonpath(res, "$..id")[0])
        cls.token = "Bearer" + " " + jsonpath.jsonpath(res, "$..token")[0]
        print("提取到的用户id", cls.member_id)
        print("提取到token", cls.token)

    @data(*cases)
    def test_withdraw(self, case):
        # 第一步:准备用例数据
        # 请求方法
        method = case["method"]
        # 请求地址
        url = conf.get("env", "BASE_URL") + case["url"]
        # 请求参数,替换用例中#member_id#
        data = eval(case["data"].replace("#member_id#", self.member_id))
        # 请求头
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = self.token
        # 期望结果
        expected = eval(case["expected"])
        # 数据库前置查询
        if case["check_sql"]:
            sql = case["check_sql"].format(self.member_id)
            start_money = self.db.find_one(sql)["leave_amount"]
        # 需要回写的行
        row = case["case_id"] + 1

        # 第二步:接口调用
        response = requests.request(method=method,
                                    url=url,
                                    json=data,
                                    headers=headers)
        res = response.json()
        print("预期结果:", expected)
        print("实际结果:", res)

        # 数据库后置查询
        if case["check_sql"]:
            sql = case["check_sql"].format(self.member_id)
            end_money = self.db.find_one(sql)["leave_amount"]

        # 第三步:数据断言和数据库断言
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 数据库断言
            if case["check_sql"]:
                recharge_money = decimal.Decimal(str(data["amount"]))
                self.assertEqual(recharge_money, start_money - end_money)
        except AssertionError as e:
            # 结果回写到excel中
            log.error("用例{}执行未通过".format(case["title"]))
            log.debug("预期结果:{}".format(expected))
            log.debug("实际结果:{}".format(res))
            log.exception(e)
            self.excel.write_excel(row=row, column=8, value="未通过")
            raise e
        else:
            log.info("用例--{}--执行通过".format(case["title"]))
            self.excel.write_excel(row=row, column=8, value="通过")
class TestRecharge(unittest.TestCase):
    excel = HandleExcel(filename, "recharge")
    cases = excel.read_excel()
    db = HandleMysql()

    @classmethod
    def setUpClass(cls):
        # 用例的前置条件,进行登录操作
        # 准备登录所用的相关数据
        url = conf.get("env", "BASE_URL") + "/member/login"
        data = {
            "mobile_phone": conf.get("test_phone", "phone"),
            "pwd": conf.get("test_phone", "pwd")
        }
        headers = eval(conf.get("env", "headers"))
        response = request(method="post", url=url, json=data, headers=headers)
        res = response.json()
        cls.member_id = str(jsonpath(res, "$..id")[0])
        cls.token = "Bearer" + " " + jsonpath(res, "$..token")[0]
        print("member_id为", cls.member_id)
        print("token为", cls.token, type(cls.token))

    @data(*cases)
    def test_recharge(self, case):
        # 第一步:准备测试数据
        # 请求方法
        method = case["method"]
        # 请求url
        url = conf.get("env", "BASE_URL") + case["url"]
        # 请求数据
        case["data"] = case["data"].replace("#member_id#", self.member_id)
        data = eval(case["data"])
        # 请求头
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = self.token
        print(headers)
        # 期望结果
        expected = eval(case["expected"])
        # 用例回写行数
        row = case["case_id"] + 1
        # 数据库前置查询
        if case["check_sql"]:
            sql = case["check_sql"].format(self.member_id)
            print(sql)
            start_money = self.db.find_one(sql)["leave_amount"]
            print("充值前的金额为:", start_money)

        # 第二步:接口调用
        response = request(method=method, url=url, json=data, headers=headers)
        # 调用接口
        res = response.json()
        print("预期结果:{}".format(expected))
        print("实际结果:{}".format(res))
        # 数据库后置查询
        if case["check_sql"]:
            sql = case["check_sql"].format(self.member_id)
            end_money = self.db.find_one(sql)["leave_amount"]

        # 第三步:断言
        try:
            # 数据断言
            self.assertEqual(expected["code"], jsonpath(res, "$..code")[0])
            self.assertEqual(expected["msg"], jsonpath(res, "$..msg")[0])
            # 数据库断言
            if case["check_sql"]:
                # 将充值金额转换为decimal类型(数据库中的金额为decimal类型)
                recharge_money = decimal.Decimal(str(data["amount"]))
                self.assertEqual(recharge_money, end_money - start_money)
        except AssertionError as e:
            # 结果回写到excel中
            log.debug("----用例{}执行完成-------".format(case["title"]))
            log.exception(e)
            self.excel.write_excel(row=row, column=8, value="未通过")
            raise e
        else:
            # 结果回写到excel中
            log.info("---用例{}执行完成---------".format(case["title"]))
            self.excel.write_excel(row=row, column=8, value="通过")
Ejemplo n.º 11
0
class TestRecharge(unittest.TestCase, TestBase):
    excel = HandleExcel(os.path.join(DATA_DIR, "apicases.xlsx"), "recharge")
    cases = excel.read_data()
    db = HandleMysql()

    @classmethod
    def setUpClass(cls):
        TestBase.login()

    @data(*cases)
    def test_recharge(self, case):

        # 第一步:准备用例数据
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        # 准备用例参数
        # 替换参数中的用户id
        data = eval(replace_data(case["data"]))
        # 准备请求头
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = getattr(EnvData, "token")
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        # 判断该用例是否需要数据库校验,获取充值之前的账户余额
        if case["check_sql"]:
            sql = case["check_sql"].format(getattr(EnvData, "member_id"))
            start_money = self.db.find_one(sql)["leave_amount"]
            print("充值之前的金额:", start_money)

        # 第二步: 发送请求获取实际结果
        response = request(url=url, method=method, json=data, headers=headers)
        res = response.json()
        print("预期结果:", expected)
        print("实际结果:", res)

        # 判断该用例是否需要数据库校验,获取充值之后的账户余额
        if case["check_sql"]:
            sql = case["check_sql"].format(getattr(EnvData, "member_id"))
            end_money = self.db.find_one(sql)["leave_amount"]
            print("充值之后的金额:", end_money)

        # 第三步:断言预期结果和实际结果
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 判断是否需要进行sql校验
            if case["check_sql"]:
                # 将充值金额转换为decimal类型(因为数据库中的金额是decimal类型的)
                recharge_money = decimal.Decimal(str(data["amount"]))
                self.assertEqual(recharge_money, end_money - start_money)
        except AssertionError as e:
            # 结果回写excel中
            log.error("用例--{}--执行未通过".format(case["title"]))
            log.debug("预期结果:{}".format(expected))
            log.debug("实际结果:{}".format(res))
            log.exception(e)
            self.excel.write_data(row=row, column=8, value="未通过")
            raise e
        else:
            # 结果回写excel中
            log.info("用例--{}--执行通过".format(case["title"]))
            self.excel.write_data(row=row, column=8, value="通过")
Ejemplo n.º 12
0
class RechargeTestCase(unittest.TestCase):
    # 创建一个操作excel的对象
    excel = HandleExcel(os.path.join(DATA_DIR, "apicases.xlsx"), "recharge")
    cases = excel.read_data()
    db = HandleMysql()

    @classmethod
    def setUpClass(cls):
        """
        用例执行的前置条件,登录
        :return:
        """
        # 准备登录的相关数据
        url = conf.get("env", "url") + "/member/login"
        data = {
            "mobile_phone": conf.get("test_data", "phone"),
            "pwd": conf.get("test_data", "pwd")
        }
        headers = eval(conf.get("env", "headers"))
        response = request(method="post", url=url, json=data, headers=headers)
        res = response.json()
        member_id = str(jsonpath.jsonpath(res, "$..id")[0])  # 下标取值
        # print("提取到的用户id为:",cls.member_id)
        # print(type(cls.member_id))

        # token_type = jsonpath.jsonpath(res,"$..token_type")   # 获取到的是Bearer
        # # print(token_type,type(token_type))

        token = "Bearer" + " " + jsonpath.jsonpath(res, "$..token")[0]
        setattr(EnvData, "member_id", member_id)
        setattr(EnvData, "token", token)

    @data(*cases)
    def test_recharge(self, case):
        # 第一步 ,准备用例
        url = conf.get("env", "url") + case["url"]
        method = case["method"]

        # 准备用例参数
        # 替换参数中用户的ID
        # case["data"] = case["data"].replace("#member_id#",self.member_id)

        # 转换为字典
        data = eval(replace_data(case["data"]))
        headers = eval(conf.get("env", "headers"))
        # 准备请求头
        headers["Authorization"] = getattr(EnvData, "token")
        expected = eval(case["expected"])
        row = case["case_id"] + 1

        # 判断该用例是否需要数据库校验,获取充值之前的账户余额
        if case["check_sql"]:
            # sql = case["check_sql"].format(self.member_id)
            sql = replace_data(case["check_sql"])
            start_money = self.db.find_one(sql)["leave_amount"]
            print("充值之前的金额:", start_money)

        # 第二步, 发送请求,获取实际结果
        response = request(method=method, url=url, json=data, headers=headers)
        res = response.json()
        print("预期结果:", expected)
        print("实际结果:", res)

        # 获取充值后的账户余额
        if case["check_sql"]:
            # sql = case["check_sql"].format(self.member_id)
            sql = replace_data(case["check_sql"])

            end_money = self.db.find_one(sql)["leave_amount"]
            print("充值后的金额:", end_money)

        # 第三步,断言预期结果和实际结果
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 判断是否需要sql校验:
            if case["check_sql"]:
                recharge_money = decimal.Decimal(str(data["amount"]))
                self.assertEqual(recharge_money, end_money - start_money)
        except AssertionError as e:
            # 将结果回写excel  中
            log.error("用例-- {}--执行未通过".format(case["title"]))
            # log.debug("预期结果:".format(expected))
            # log.debug("实际结果:".format(res))
            log.exception(e)  # 这样可以异常情况打印到日志文件中!
            self.excel.write_data(row=row, column=8, value="未通过")
            raise e
        else:
            # 将结果回写excel  中
            log.error("用例--{}--执行通过".format(case["title"]))

            self.excel.write_data(row=row, column=8, value="通过")
Ejemplo n.º 13
0
class RegisterTestCase(unittest.TestCase):
    excel = HandleExcel(filename, "register")
    cases = excel.read_data()
    db = HandleMysql()

    @data(*cases)
    def test_register(self, case):
        # 第一步,准备用例数据  (请求方法,请求地址,请求参数,请求头
        # 请求方法
        method = case["method"]
        # 请求url
        url = case["url"]
        # 请求参数是否有手机号需要替换
        # 判断
        if "#phone#" in case["data"]:
            phone = self.random_phone()
            case["data"] = case["data"].replace("#phone#", phone)

        data = eval(case["data"])
        headers = eval(conf.get("env", "headers"))
        expected = eval(case["expected"])
        # 用例所在行
        row = case["case_id"] + 1

        # 第二步,发送请求获取实际结果
        response = request(method=method, url=url, json=data, headers=headers)
        res = response.json()
        # print("实际结果:",res)

        print("预期结果:", expected)
        print("实际结果:", res)

        # 第三步,断言
        try:

            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 判断是否需要进行sql校验
            if case["check_sql"]:
                sql = case["check_sql"].replace("#phong#",
                                                data["mobile_phone"])

                res = self.db.find_count(sql)
                self.assertTrue(1, res)

        except AssertionError as e:
            # ---------------------将结果回写excel  中
            log.error("用例---- {}----执行未通过".format(case["title"]))
            log.info("预期结果:", expected)
            log.info("实际结果:", res)
            log.exception(e)
            # log.error(e)
            log.exception(e)  # 这样可以异常情况打印到日志文件中!
            self.excel.write_data(row=row, column=8, value="未通过")
            raise e
        else:
            # ----------------------将结果回写excel  中
            log.error("用例---- {}----执行通过".format(case["title"]))

            self.excel.write_data(row=row, column=8, value="通过")

    @classmethod
    def random_phone(self):
        """
        生成一个数据里里面未注册的手机号
        :return:
        """
        while True:
            phone = "155"
            for i in range(8):
                r = random.randint(0, 9)
                phone += str(r)
            sql = "select * from futureloan.member where mobile_phone = {}".format(
                phone)
            res = self.db.find_count(sql)
            if res == 0:
                return phone
Ejemplo n.º 14
0
class TestAdd(unittest.TestCase):
    excel = HandleExcel(os.path.join(DATA_DIR, "apicases.xlsx"), "add")
    cases = excel.read_data()
    db = HandleMysql()

    @classmethod
    def setUpClass(cls):
        """用例执行的前置条件:登录"""
        # 准备登录的相关数据
        url = conf.get("env", "url") + "/member/login"
        data = {
            "mobile_phone": conf.get("test_data", "phone"),
            "pwd": conf.get("test_data", "pwd")
        }
        headers = eval(conf.get("env", "headers"))
        response = request(method="post", url=url, json=data, headers=headers)
        res = response.json()
        member_id = str(jsonpath.jsonpath(res, "$..id")[0])
        token = "Bearer" + " " + jsonpath.jsonpath(res, "$..token")[0]
        # 将提取出来的数据保存为EnvData这个类的属性(环境变量)
        setattr(EnvData, "member_id", member_id)
        setattr(EnvData, "token", token)

    @data(*cases)
    def test_add(self, case):

        # 第一步:准备用例数据
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        # 替换参数中的用户id,
        # case["data"] = case["data"].replace("#member_id#", self.member_id)
        # 替换用例中的动态数据
        data = eval(replace_data(case["data"]))
        # 准备请求头
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = getattr(EnvData, "token")
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        # 加标之前,查询数据库中该用户标的数量
        if case["check_sql"]:
            sql = replace_data(case["check_sql"])
            start_count = self.db.find_count(sql)

        # 第二步: 发送请求获取实际结果
        response = request(url=url, method=method, json=data, headers=headers)
        res = response.json()
        print("预期结果:", expected)
        print("实际结果:", res)

        # 第三步:断言预期结果和实际结果
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            if case["check_sql"]:
                # 加标之后
                sql = replace_data(case["check_sql"])
                end_count = self.db.find_count(sql)
                self.assertEqual(1, end_count - start_count)
        except AssertionError as e:
            # 结果回写excel中
            log.error("用例--{}--执行未通过".format(case["title"]))
            log.debug("预期结果:{}".format(expected))
            log.debug("实际结果:{}".format(res))
            log.exception(e)
            self.excel.write_data(row=row, column=8, value="未通过")
            raise e
        else:
            # 结果回写excel中
            log.info("用例--{}--执行通过".format(case["title"]))
            self.excel.write_data(row=row, column=8, value="通过")
Ejemplo n.º 15
0
class RegisterTestCase(unittest.TestCase):
    excel = HandleExcel(filename, "register")
    cases = excel.read_data()
    db = HandleMysql()

    @data(*cases)
    def test_register(self, case):
        # 第一步:准备用例数据
        # 请求方法
        method = case["method"]
        # 请求地址
        url = case["url"]
        # 请求参数
        # 判断是否有手机号码需要替换
        if "#phone#" in case["data"]:
            # 随机生成一个手机号码
            phone = self.random_phone()
            # 将参数中的#phone# 替换成随机生成的手机号
            case["data"] = case["data"].replace("#phone#", phone)
        data = eval(case["data"])
        # 请求头
        headers = eval(conf.get("env", "headers"))
        # 预期结果
        expected = eval(case["expected"])
        # 用例所在行
        row = case["case_id"] + 1

        # 第二步:发送请求获取实际结果
        response = request(method=method, url=url, json=data, headers=headers)
        # 获取实际结果
        res = response.json()
        print("预期结果:", expected)
        print("实际结果:", res)

        # 第三步:断言
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 判断是否需要进行sql校验
            if case["check_sql"]:
                sql = case["check_sql"].replace("#phone#",
                                                data["mobile_phone"])
                res = self.db.find_count(sql)
                self.assertEqual(1, res)
        except AssertionError as e:
            # 结果回写excel中
            log.error("用例--{}--执行未通过".format(case["title"]))
            log.debug("预期结果:{}".format(expected))
            log.debug("实际结果:{}".format(res))
            log.exception(e)
            self.excel.write_data(row=row, column=8, value="未通过")
            raise e
        else:
            # 结果回写excel中
            log.info("用例--{}--执行通过".format(case["title"]))
            self.excel.write_data(row=row, column=8, value="通过")

    @classmethod
    def random_phone(cls):
        """生成一个数据库里面未注册的手机号码"""
        while True:
            phone = "155"
            for i in range(8):
                r = random.randint(0, 9)
                phone += str(r)

            # 数据库中查询该手机号是否存在
            sql = "SELECT * FROM futureloan.member WHERE mobile_phone={}".format(
                phone)
            res = cls.db.find_count(sql)
            # 如果不存在,则返回该手机号
            if res == 0:
                return phone
Ejemplo n.º 16
0
class TestAudit(unittest.TestCase):
    excel = HandleExcel(os.path.join(DATA_DIR, "apicases.xlsx"), "audit")
    cases = excel.read_data()
    db = HandleMysql()

    @classmethod
    def setUpClass(cls):
        # 该用例类所有用例执行之前的前置条件:管理员要登录,普通用户登录
        url = conf.get("env", "url") + "/member/login"
        headers = eval(conf.get("env", "headers"))
        # 前置条件一:管理员登录
        admin_data = {
            "mobile_phone": conf.get("test_data", "admin_phone"),
            "pwd": conf.get("test_data", "admin_pwd")
        }
        response1 = request(method="post",
                            url=url,
                            json=admin_data,
                            headers=headers)
        res1 = response1.json()
        # 提取管理员的token
        cls.admin_token = "Bearer" + " " + jsonpath.jsonpath(res1,
                                                             "$..token")[0]

        # 前置条件二:普通用户登录
        user_data = {
            "mobile_phone": conf.get("test_data", "phone"),
            "pwd": conf.get("test_data", "pwd")
        }
        response2 = request(method="post",
                            url=url,
                            json=user_data,
                            headers=headers)
        res2 = response2.json()
        # 提取用户id和token
        cls.user_member_id = jsonpath.jsonpath(res2, "$..id")[0]
        cls.user_token = "Bearer" + " " + jsonpath.jsonpath(res2,
                                                            "$..token")[0]

        # print("管理员token:", cls.admin_token)
        # print("用户token:", cls.user_token)
        # print("用户id:", cls.user_member_id)

    def setUp(self):
        # 每条用例之前的前置条件:添加一个新的项目
        url = conf.get("env", "url") + "/loan/add"
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = self.user_token
        data = {
            "member_id": self.user_member_id,
            "title": "大胖借钱打打打",
            "amount": 2000,
            "loan_rate": 12.0,
            "loan_term": 3,
            "loan_date_type": 1,
            "bidding_days": 5
        }
        # 发送请求,添加项目
        response = request(method="post", url=url, json=data, headers=headers)
        res = response.json()
        # 提取项目的id给审核的用例使用
        self.loan_id = jsonpath.jsonpath(res, "$..id")[0]
        # print("项目id:",loan_id)

    @data(*cases)
    def test_audit(self, case):
        # 第一步:准备数据
        url = conf.get("env", "url") + case["url"]

        #  >>>>>>>>>>>判断是否需要替换审核通过的标id >>>>>>>>>>>
        if "#pass_loan_id#" in case["data"]:
            #  >>>>>>>>>>>  将之前保存的审核通过的标ID 类属性的地方,替换到该用例中 >>>>>>>>>>>
            case["data"] = case["data"].replace("#pass_loan_id#",
                                                str(self.pass_loan_id))

        data = eval(case["data"].replace("#loan_id#", str(self.loan_id)))
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = self.admin_token
        if case["title"] == "普通用户进行审核":
            headers["Authorization"] = self.user_token

        method = case["method"]
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        # 第二步:调用接口,获取实际结果
        response = request(url=url, method=method, json=data, headers=headers)
        res = response.json()
        # (-------判断是否是审核通过的用例,并且审核成功---------------)
        if case["title"] == "审核通过" and res["msg"] == "OK":
            # >>>>>>>>>>>(------将执行通过的标ID保存为类属性------------)
            TestAudit.pass_loan_id = data["loan_id"]

        # 第三步:断言
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # ( >>>>>>>>>>>-----对需要进行数据库校验的用例,进行校验)
            if case["check_sql"]:
                sql = case["check_sql"].replace("#loan_id#", str(self.loan_id))
                status = self.db.find_one(sql)["status"]
                self.assertEqual(expected["status"], status)

        except AssertionError as e:
            # 结果回写excel中
            log.error("用例--{}--执行未通过".format(case["title"]))
            log.debug("预期结果:{}".format(expected))
            log.debug("实际结果:{}".format(res))
            log.exception(e)
            self.excel.write_data(row=row, column=8, value="未通过")
            raise e
        else:
            # 结果回写excel中
            log.info("用例--{}--执行通过".format(case["title"]))
            self.excel.write_data(row=row, column=8, value="通过")
Ejemplo n.º 17
0
class TestWithdraw(unittest.TestCase):
    excel = HandleExcel(os.path.join(DATA_DIR, "apicases.xlsx"), "withdraw")
    cases = excel.read_data()
    db = HandleMysql()

    @classmethod
    def setUpClass(cls):
        """用例执行的前置条件:登录"""
        # 准备登录的相关数据
        url = conf.get("env", "url") + "/member/login"
        data = {
            "mobile_phone": conf.get("test_data", "phone"),
            "pwd": conf.get("test_data", "pwd")
        }
        headers = eval(conf.get("env", "headers"))
        response = request(method="post", url=url, json=data, headers=headers)
        res = response.json()
        cls.member_id = str(jsonpath.jsonpath(res, "$..id")[0])
        cls.token = "Bearer" + " " + jsonpath.jsonpath(res, "$..token")[0]
        # print("提取到的用户id为:", cls.member_id)
        # print("提取到的用户token为:", cls.token)

    @data(*cases)
    def test_withdraw(self, case):

        # 第一步:准备用例数据
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        # 准备用例参数
        # 替换参数中的用户id,
        case["data"] = case["data"].replace("#member_id#", self.member_id)
        data = eval(case["data"])
        # 准备请求头
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = self.token
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        # 判断该用例是否需要数据库校验,获取取现之前的账户余额
        if case["check_sql"]:
            sql = case["check_sql"].format(self.member_id)
            start_money = self.db.find_one(sql)["leave_amount"]
            print("取现之前的金额:", start_money)

        # 第二步: 发送请求获取实际结果
        response = request(url=url, method=method, json=data, headers=headers)
        res = response.json()
        print("预期结果:", expected)
        print("实际结果:", res)

        # 判断该用例是否需要数据库校验,获取取现之后的账户余额
        if case["check_sql"]:
            sql = case["check_sql"].format(self.member_id)
            end_money = self.db.find_one(sql)["leave_amount"]
            print("取现之后的金额:", end_money)
        # 第三步:断言预期结果和实际结果
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 判断是否需要进行sql校验
            if case["check_sql"]:
                # 将取现金额转换为decimal类型(因为数据库中的金额是decimal类型的)
                recharge_money = decimal.Decimal(str(data["amount"]))
                self.assertEqual(recharge_money, start_money - end_money)
        except AssertionError as e:
            # 结果回写excel中
            log.error("用例--{}--执行未通过".format(case["title"]))
            log.debug("预期结果:{}".format(expected))
            log.debug("实际结果:{}".format(res))
            log.exception(e)
            self.excel.write_data(row=row, column=8, value="未通过")
            raise e
        else:
            # 结果回写excel中
            log.info("用例--{}--执行通过".format(case["title"]))
            self.excel.write_data(row=row, column=8, value="通过")
Ejemplo n.º 18
0
class TestAdd(unittest.TestCase):
    excel = HandleExcel(os.path.join(DATA_DIR, "apicases.xlsx"), "add")
    cases = excel.read_excel()
    db = HandleMysql()

    @classmethod
    def setUpClass(cls):
        """先用普通用户登录"""
        headers = eval(conf.get("env", "headers"))
        url = conf.get("env", "BASE_URL") + "member/login"
        data = {
            "mobile_phone": conf.get("test_phone", "phone"),
            "pwd": conf.get("test_phone", "pwd")
        }
        response = requests.request(method="post",
                                    url=url,
                                    json=data,
                                    headers=headers)
        res = response.json()
        log.info("--------登录结果:{}--------".format(res))
        member_id = str(jsonpath.jsonpath(res, "$..id")[0])
        token = "Bearer " + jsonpath.jsonpath(res, "$..token")[0]
        # 将提取出的数据保存为EnvData的类属性
        setattr(EnvData, "member_id", member_id)
        setattr(EnvData, "token", token)

    @data(*cases)
    def test_add(self, case):
        # 第一步:准备数据

        # 请求方法
        method = case["method"]
        # 请求地址
        url = os.path.join(conf.get("env", "BASE_URL")) + case["url"]
        # 请求参数
        data = eval(replace_data(case["data"]))
        # 请求头
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = getattr(EnvData, "token")
        # 预期结果
        expected = eval(case["expected"])
        log.info("--------预期结果:{}----------".format(expected))
        # 回写的行
        row = case["case_id"] + 1
        # 数据库前置查询
        if case["check_sql"]:
            start_count = self.db.find_count(replace_data(case["check_sql"]))
        # 第二步:接口调用
        response = requests.request(method=method,
                                    url=url,
                                    json=data,
                                    headers=headers)
        # 实际结果
        res = response.json()
        log.info("--------实际结果:{}----------".format(res))

        # 数据断言和数据库断言
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 数据库后置查询
            if case["check_sql"]:
                end_count = self.db.find_count(replace_data(case["check_sql"]))
                self.assertEqual(1, end_count - start_count)
        except AssertionError as e:
            # 结果回写到excel中
            log.error("用例--{}--执行未通过".format(case["title"]))
            log.debug("预期结果:{}".format(expected))
            log.debug("实际结果:{}".format(res))
            log.exception(e)
            self.excel.write_excel(row, 8, value="未通过")
        else:
            # 结果回写excel中
            log.info("用例--{}--执行通过".format(case["title"]))
            self.excel.write_excel(row, 8, value="通过")