Example #1
0
    def test_register(self, case):
        # 第一步:准备用例数据
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        # 生成一个手机号码
        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 = self.request.send(url=url, method=method, json=data, headers=headers)
        res = response.json()

        # 第三步:断言(比对预期结果和实际结果)
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            if case["check_sql"]:
                sql = "SELECT * FROM futureloan.member WHERE mobile_phone={}".format(data["mobile_phone"])
                count = self.db.find_count(sql)
                self.assertEqual(1, 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"]))
Example #2
0
 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(CaseDate, "token_value")
     # 在请求头中加入setupclass中提取出来的token
     expected = eval(case["expected"])
     row = case["case_id"] + 1
     # 第二步:发送请求,获取结果
     print("请求参数为:",data,type(data))
     response = self.request.send(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"]))
Example #3
0
    def test_withdraw(self, case):
        # 准备用例数据
        url = conf.get("env", "url") + case["url"]
        case["data"] = case["data"].replace("#member_id#", str(self.member_id))
        data = eval(case["data"])
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = self.token_value
        method = case["method"]
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        # 发送请求前的金额
        sql = "select leave_amount from futureloan.member where mobile_phone = {}".format(
            conf.get("test_case", "mobile_phone"))
        pre_money = self.basedata.find_one(sql=sql)["leave_amount"]
        # 发送请求
        response = self.request.send_requests(method=method, url=url, json=data, headers=headers)
        res = response.json()
        # 断言
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            if expected["code"] == 0:
                end_money = self.basedata.find_one(sql=sql)["leave_amount"]
                self.assertEqual(pre_money-end_money,Decimal(str(data["amount"])))

        except AssertionError as e:
            print("预期结果:",expected)
            print("实际结果:",res)
            self.execl.write_data(row=row, column=8, value="未通过")
            log.error("用例:{} ,执行".format(case["title"]) + color.white_red("未通过"))
            log.exception(e)
            raise e
        else:
            self.execl.write_data(row=row, column=8, value="通过")
            log.info("用例:{},执行".format(case["title"]) + color.white_green("通过"))
 def test_login(self, case):
     # 准备用例数据
     url = conf.get("env", "url") + case["url"]
     headers = eval(conf.get("env", "headers"))
     case["data"] = CaseData.replace_data(case["data"])
     data = eval(case["data"])
     method = case["method"]
     if case["title"] != "登录成功":
         expected = eval(case["expected"])
     row = case["case_id"] + 1
     # 发送请求并获取响应结果
     response = self.request.send(url=url, method=method, headers=headers, json=data)
     res = response.json()
     if case["title"] == "登录成功":
         CaseData.pass_username = jsonpath.jsonpath(res, "$.username")[0]
         expected = eval(CaseData.replace_data(case["expected"]))
     print("预期结果:", expected)
     print("实际结果:", res)
     # 断言
     try:
         if case["assert"] == "u":
             self.assertEqual(expected["username"], res["username"])
         elif case["assert"] == "p":
             self.assertEqual(expected["password"], res["password"])
         elif case["assert"] == "n":
             self.assertEqual(expected["non_field_errors"], res["non_field_errors"])
     except AssertionError as e:
         self.excel.write_data(row=row, column=9, value="不通过")
         raise e
     else:
         self.excel.write_data(row=row, column=9, value="通过")
Example #5
0
 def test_loans(self, case):
     # 第一步:准备用例数据
     url = conf.get("env", "url") + case["url"]
     method = case["method"]
     data = replace_data(case["data"])
     # 替换参数中的用户id
     headers = eval(conf.get("env", "headers"))
     expected = eval(case["expected"])
     row = case["case_id"] + 1
     # 第二步:发送请求,获取结果
     response = self.request.send(url=url,
                                  method=method,
                                  params=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"]))
Example #6
0
    def create_logger():
        # 创建日志收集器,设置日志等级
        mylog = logging.getLogger(conf.get("log","name"))
        mylog.setLevel(conf.get("log","level"))
        #创建输出到控制台的日志等级
        sh = logging.StreamHandler()
        sh.setLevel(conf.get("log","sh_level"))
        #error级别
        mylog.addHandler(sh)
        # 丢到日志收集器中去

        #创建输出到文件的日志等级
        fh = logging.FileHandler(os.path.join(LOGDIR,"log.log"),encoding="UTF-8")
        # 输出到的文件及其目录
        fh.setLevel(conf.get("log","fh_level"))
        #设置级别(info)
        mylog.addHandler(fh)
        # 丢到日志收集器中去

        #定义输出日志的格式
        formater = '%(asctime)s - [%(filename)s-->line:%(lineno)d] - %(levelname)s:%(message)s'
        fm = logging.Formatter(formater)
        # 格式化输出
        sh.setFormatter(fm)
        fh.setFormatter(fm)

        return mylog
Example #7
0
    def test_list(self, case):
        # 第一步,准备用例数据
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = getattr(CaseData, "admin_token_value")
        expected = eval(case["expected"])
        row = case["case_id"] + 1

        # 第二步,发送请求,获取结果
        response = self.request.send(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:
            self.excel.write_data(row=row, column=8, value="未通过")
            print("预期结果", expected)
            print("实际结果", res)
            log.error("用例{}执行未通过".format(case["title"]))
            log.exception(e)
            raise e
        else:
            self.excel.write_data(row=row, column=8, value="通过")
            print("预期结果", expected)
            print("实际结果", res)
            log.error("用例{}执行通过".format(case["title"]))
Example #8
0
    def test_login(self, case):
        # 准备用例数据
        url = conf.get("env", "url") + case["url"]
        data = eval(case["data"])
        headers = eval(conf.get("env", "headers"))
        method = case["method"]
        expected = eval(case["expected"])
        row = case["case_id"] + 1

        # 发送请求
        reponse = self.send.send_requests(url=url, method=method, headers=headers, json=data)
        res = reponse.json()

        # 断言
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
        except AssertionError as e:
            self.excel.write_data(row=row, column=8, value="不通过")
            log.error("用例:{} ,执行".format(case["title"]) + color.white_red("不通过"))
            log.exception(e)
            raise e
        else:
            self.excel.write_data(row=row, column=8, value="通过")
            log.info("用例:{} ,执行".format(case["title"]) + color.white_green("通过"))
Example #9
0
 def __init__(self):
     self.conn = pymysql.connect(host=conf.get("db", "host"),
                                 port=conf.getint("db", "port"),
                                 user=conf.get("db", "user"),
                                 password=conf.get("db", "pwd"),
                                 charset=conf.get("db", "charset"),
                                 cursorclass=pymysql.cursors.DictCursor)
     self.cur = self.conn.cursor()
Example #10
0
 def __init__(self):
     self.conn = pymysql.connect(host=conf.get('mysql', 'host'),
                                 port=conf.getint('mysql', 'port'),
                                 user=conf.get('mysql', 'name'),
                                 password=conf.get('mysql', 'password'),
                                 charset=conf.get('mysql', 'charset'),
                                 cursorclass=pymysql.cursors.DictCursor)
     self.cur = self.conn.cursor()
Example #11
0
    def testadd(self, case):
        #准备测试数据,对登录接口用例替换相应的手机号、密码
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        headers = eval(conf.get("env", "headers"))
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        title = case["title"]
        case["data"] = ReplaceData.replace_data(case["data"])
        data = eval(case["data"])
        # 判断是否是添加项目接口,添加项目接口则加上请求头,替换相应的用户id
        if case["interface"] == "add":
            headers["Authorization"] = ReplaceData.Authorization
            #添加时间戳和签名到json请求体
            sign = HandleSign.generate_sign(ReplaceData.token)
            data.update(sign)
            #判断是否需要sql校验
            if case["sql_check"]:
                # 查询执行用例前当前用户添加的项目总数
                start_loan = self.db.find_count(case["sql_check"].format(
                    ReplaceData.member_id))

        #发送请求,获取实际结果
        respons = self.request.send(url=url,
                                    method=method,
                                    headers=headers,
                                    json=data)
        res = respons.json()

        # 判断是否是登录接口
        if case["interface"] == "login":
            # 提取token,保存为类属性
            ReplaceData.token = jsonpath.jsonpath(res, "$..token")[0]
            token_type = jsonpath.jsonpath(res, "$..token_type")[0]
            ReplaceData.Authorization = token_type + " " + ReplaceData.token
            # 提取用户id保存为类属性
            ReplaceData.member_id = str(jsonpath.jsonpath(res, "$..id")[0])

        #断言:比对预期结果和实际结果
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            if case["sql_check"]:
                # 查询用例执行后当前用户添加的项目总数
                end_loan = self.db.find_count(case["sql_check"].format(
                    ReplaceData.member_id))
                self.assertEqual(1, end_loan - start_loan)
        except AssertionError as e:
            print("预期结果:{}".format(expected))
            print("实际结果:{}".format(res))
            self.excel.write_data(row=row, column=8, value="未通过")
            log.error("用例未通过:{},错误原因:{}".format(title, e))
            raise e
        else:
            self.excel.write_data(row=row, column=8, value="通过")
            log.debug("用例通过:{}".format(title))
Example #12
0
    def send_email(file_path,text_msg=None,subject="Python代码邮件"):
        """
        发送附件文件的邮件的方法
        :param file_path: 附件路径,必填项
        :param text_msg: 邮件内文本内容,不填则默认为附件内文本;
        :param subject: 邮件的主题名称。
        :return:
        """

        #第一步:根据smtp服务器地址,准备测试账号及授权码
        #smtp服务器地址
        host = conf.get("email","host")
        #端口
        port = conf.getint("email","port")
        #发件人邮箱
        user = conf.get("email","user")
        #发件人邮箱授权码
        password = conf.get("email","password")
        #收件人邮箱
        to_user = eval(conf.get("email","to_user"))
        #附件的文件名
        filename = conf.get("email","filename")

        # 1、连接smtp服务器
        smtp = smtplib.SMTP_SSL(host=host,port=port)
        #2、登录账户
        smtp.login(user=user,password=password)

        # 创建一封多组件的邮件
        email = MIMEMultipart()
        with open(file_path,"rb") as f :
            content = f.read()

        #邮件内的文本信息
        if text_msg == None:
            text_msg = content
        text_email = MIMEText(text_msg, _subtype='html', _charset="utf8")
        # 添加到多组件的邮件中
        email.attach(text_email)

        #邮件的附件信息
        file_email = MIMEApplication(content)
        file_email.add_header("content-disposition", "attachment", filename=filename)
        # 添加到多组件的邮件中
        email.attach(file_email)

        #1、设置邮件主题名
        email["Subject"] = subject
        #2、设置邮件发送人
        email["From"] = user
        #3、设置邮件接收人
        for i in to_user:
            email["To"] = i

        #发送邮件
        smtp.send_message(email,from_addr=user,to_addrs=to_user)
 def __init__(self):
     # 连接数据库
     self.connect = pymysql.connect(host=conf.get("bd", "host"),
                                    port=conf.getint("bd", "port"),
                                    user=conf.get("bd", "user"),
                                    password=conf.get("bd", "password"),
                                    charset="utf8",
                                    cursorclass=pymysql.cursors.DictCursor)
     # 创建一个游标对象
     self.cur = self.connect.cursor()
Example #14
0
    def test_loan(self, case):
        # 准备用例数据
        url = conf.get("env", "url") + case["url"]
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = getattr(CaseData, "token_value")
        case["data"] = CaseData.replace_data(case["data"])
        data = eval(case["data"])
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        method = case["method"]
        # 发送请求
        # 第一种:通过新增项目数量进行断言
        # if case["check_sql"] ==1:
        #     sql = "select * from futureloan.loan"
        #     start_count = self.basedata.find_count(sql)

        # 第二种:通过新增项目id进行断言
        if case["check_sql"] == 1:
            sql = "select MAX(id) as id from futureloan.loan"
            start_id = self.basedata.find_one(sql)["id"]

        response = self.request.send_requests(method=method,
                                              url=url,
                                              headers=headers,
                                              json=data)
        res = response.json()
        # 断言
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 通过新增项目数量断言
            # if case["check_sql"] ==1:
            #     sql = "select * from futureloan.loan"
            #     end_count = self.basedata.find_count(sql)
            #     self.assertEqual(end_count-start_count,1)

            # 通过新增项目id进行断言
            if case["check_sql"] == 1:
                sql = "select MAX(id) as id from futureloan.loan where member_id = {}".format(
                    getattr(CaseData, "member_id"))
                end_id = self.basedata.find_one(sql)["id"]
                self.assertEqual(end_id, start_id + 1)

        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:
            print("预期结果:", expected)
            print("实际结果:", res)
            self.excel.write_data(row=row, column=8, value="通过")
            log.error("用例:{}执行通过".format(case["title"]))
Example #15
0
    def test_recharge(self, case):
        # 第一步,准备用例数据
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        # 替换参数中的用户ID
        # case["data"] = case["data"].replace("#member_id#", str(self.member_id))
        case["data"] = replace_data(case["data"])
        data = eval(case["data"])
        # 在请求体中加入时间戳和签名
        sign_info = HandleSign.generate_sign(getattr(CaseData, "token"))
        data.update(sign_info)

        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = getattr(CaseData, "token_value")

        expected = eval(case["expected"])
        row = case["case_id"] + 1
        if case["check_sql"]:
            # 查询当前用户的余额
            sql = "SELECT leave_amount FROM futureloan.member WHERE mobile_phone={}".format(
                conf.get("test_data", "phone"))
            start_money = self.db.find_one(sql)["leave_amount"]

        # 第二步,发送请求,获取结果
        response = self.request.send(url=url,
                                     method=method,
                                     json=data,
                                     headers=headers)
        res = response.json()
        if case["check_sql"]:
            # 查询当前用户的余额
            sql = "SELECT leave_amount FROM futureloan.member WHERE mobile_phone={}".format(
                conf.get("test_data", "phone"))
            end_money = self.db.find_one(sql)["leave_amount"]

        # 第三步,断言比对预期结果和实际结果
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 判断是否需要sql校验
            if case["check_sql"]:
                self.assertEqual(end_money - start_money,
                                 Decimal(str(data["amount"])))

        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.error("用例{}执行通过".format(case["title"]))
Example #16
0
    def testinfo(self, case):
        #准备测试数据,替换用例中相应的手机号、密码、用户id、项目id
        method = case["method"]
        headers = eval(conf.get("env", "headers"))
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        title = case["title"]
        case["data"] = ReplaceData.replace_data(case["data"])
        data = eval(case["data"])
        # 判断是否是用户信息接口,用户信息接口则加上请求头
        if case["interface"] == "info":
            headers["Authorization"] = ReplaceData.Authorization
            # 添加时间戳和签名到json请求体
            sign = HandleSign.generate_sign(ReplaceData.token)
            data.update(sign)
            case["url"] = ReplaceData.replace_data(case["url"])

        url = conf.get("env", "url") + case["url"]

        #发送请求,获取实际结果
        respons = self.request.send(url=url,
                                    method=method,
                                    headers=headers,
                                    json=data)
        res = respons.json()

        #获取用户id和token值,并保存为类属性
        if case["interface"] == "login":
            ReplaceData.token = jsonpath.jsonpath(res, "$..token")[0]
            ReplaceData.member_id = str(jsonpath.jsonpath(res, "$..id")[0])
            ReplaceData.Authorization = jsonpath.jsonpath(
                res, "$..token_type")[0] + " " + jsonpath.jsonpath(
                    res, "$..token")[0]

        #断言:比对预期结果和实际结果
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertIn(expected["msg"], res["msg"])
            #判断是否需要SQL校验
            if case["sql_check"]:
                #获取执行结果的用户可用余额
                info = jsonpath.jsonpath(res, "$..leave_amount")[0]
                # 获取预期结果的用户可用余额
                user_info = self.db.find_one(case["sql_check"].format(
                    ReplaceData.member_id))["leave_amount"]
                self.assertEqual(user_info, Decimal(str(info)))
        except AssertionError as e:
            print("预期结果:{}".format(expected))
            print("实际结果:{}".format(res))
            self.excel.write_data(row=row, column=8, value="未通过")
            log.error("用例未通过:{},错误原因:{}".format(title, e))
            raise e
        else:
            self.excel.write_data(row=row, column=8, value="通过")
            log.debug("用例通过:{}".format(title))
    def setUpClass(cls):
        """所有用例执行之前的环境准备:登录  添加项目   添加接口"""
        # 1、准备登录所需数据进行登录
        url = conf.get("env", "url") + "/user/login/"
        login_data = {
            "username": conf.get("test_data", "username"),
            "password": conf.get("test_data", "password")
        }
        response = cls.request.send(url=url, method="post", json=login_data)
        res = response.json()
        # 提取登录之后的token
        token = jsonpath.jsonpath(res, "$..token")[0]
        # 保存token
        CaseDate.token = "JWT" + " " + token

        # 2、准备添加项目的数据,添加一个项目
        pro_url = conf.get("env", "url") + "/projects/"
        pro_data = {
            "name": cls.random_project_name(),
            "leader": "lemonban",
            "tester": "木木木",
            "programmer": "zhang",
            "publish_app": "123",
            "desc": "jian"
        }
        headers = {"Authorization": getattr(CaseDate, "token")}
        # 发送请求添加项目
        response2 = cls.request.send(url=pro_url,
                                     method="post",
                                     json=pro_data,
                                     headers=headers)
        res2 = response2.json()
        # 保存添加的项目id
        CaseDate.project_id = str(jsonpath.jsonpath(res2, "$..id")[0])
        # 保存添加的项目名
        CaseDate.pro_name = pro_data["name"]

        # 3、准备添加接口的参数,添加一个接口
        inter_url = conf.get("env", "url") + "/interfaces/"
        inter_data = {
            "name": "{}_测试接口".format(pro_data["name"]),
            "project_id": CaseDate.project_id,
            "tester": "木木木",
            "desc": "注册接口"
        }
        response3 = cls.request.send(url=inter_url,
                                     method="post",
                                     json=inter_data,
                                     headers=headers)
        res3 = response3.json()
        # 保存接口id
        CaseDate.interface_id = str(jsonpath.jsonpath(res3, "$..id")[0])
        # 保存添加的接口名
        CaseDate.inter_name = inter_data["name"]
Example #18
0
 def __init__(self):
     '''拿到了数据库的连接对象'''
     self.conn = pymysql.connect(host=conf.get("db", "host"),
                                 user=conf.get("db", "user"),
                                 password=conf.get("db", "password"),
                                 database=conf.get("db", "database"),
                                 port=int(conf.get("db", "port")))
     #获取mysql数据库的游标对象
     #1.执行SQL语句
     #2.并返回结果
     self.cur = self.conn.cursor()
Example #19
0
 def __init__(self):
     #拿到数据库的连接对象
     self.conn = pymysql.connect(host=conf.get("db", "host"),
                                 user=conf.get("db", "user"),
                                 password=conf.get("db", "password"),
                                 database=conf.get("db", "database"),
                                 port=conf.get("db", "port"))
     #获取mysql数据库的游标对象
     # 1.执行sql语句
     # 2.返回结果
     self.cur = self.conn.cursor()
 def setUpClass(cls):
     # 执行用例前先登录系统
     url = conf.get("env", "url") + "/user/login/"
     headers = eval(conf.get("env", "headers"))
     data = {
         "username": conf.get("testcase", "username"),
         "password": "******"
     }
     reponse = cls.request.send(url=url, headers=headers, method="post", json=data)
     res = reponse.json()
     token = jsonpath.jsonpath(res, "$.token")[0]
     CaseData.token_value = "JWT" + " " + token
Example #21
0
    def testwithdraw(self, case):
        #准备测试数据,对登录接口用例替换相应的测试手机号、密码
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        headers = eval(conf.get("env", "headers"))
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        title = case["title"]
        case["data"] = ReplaceData.replace_data(case["data"])
        data = eval(case["data"])
        # 判断是否是取现接口,取现接口则加上请求头,替换相应的用户id,添加时间戳和签名到json请求体
        if case["interface"] == "withdraw":
            headers["Authorization"] = ReplaceData.Authorization
            sign = HandleSign.generate_sign(ReplaceData.token)
            data.update(sign)

        # 判断是否需要进行sql校验
        if case["sql_check"]:
            #查询充值前用户的可用余额
            start_leave_amount = self.db.find_one(case["sql_check"].format(
                conf.get("test_data", "phone")))["leave_amount"]
        #发送请求,获取实际结果
        respons = self.request.send(url=url,
                                    method=method,
                                    headers=headers,
                                    json=data)
        res = respons.json()
        # 判断是否是登录接口
        if case["interface"] == "login":
            # 提取token,保存为类属性
            ReplaceData.token = jsonpath.jsonpath(res, "$..token")[0]
            token_type = jsonpath.jsonpath(res, "$..token_type")[0]
            ReplaceData.Authorization = token_type + " " + ReplaceData.token
            # 提取用户id保存为类属性
            ReplaceData.member_id = str(jsonpath.jsonpath(res, "$..id")[0])
        #断言,比对结果
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            if case["sql_check"]:
                end_leave_amount = self.db.find_one(case["sql_check"].format(
                    conf.get("test_data", "phone")))["leave_amount"]
                self.assertEqual(Decimal(str(data["amount"])),
                                 start_leave_amount - end_leave_amount)
        except AssertionError as e:
            print("预期结果:{}".format(expected))
            print("实际结果:{}".format(res))
            self.excel.write_data(row=row, column=8, value="未通过")
            log.error("用例未通过:{},错误原因:{}".format(title, e))
            raise e
        else:
            self.excel.write_data(row=row, column=8, value="通过")
            log.debug("用例通过:{}".format(title))
Example #22
0
 def test_interfaces(self, case):
     # 准备用例数据
     url = conf.get("env", "url") + case["url"]
     headers = eval(conf.get("env", "headers"))
     headers["Authorization"] = getattr(CaseData, "token_value")
     if case["title"] == "新增项目成功":
         case["data"] = case["data"].replace("@project@",
                                             RandomData.random_project())
     if case["title"] != "新增项目成功":
         case["data"] = case["data"].replace("@interface@",
                                             RandomData.random_interface())
         case["data"] = CaseData.replace_data(case["data"])
     case["data"] = CaseData.replace_data(case["data"])
     data = eval(case["data"])
     if case["title"] != "创建失败-接口名称字段为空":
         CaseData.pass_project = data["name"]
         CaseData.pass_interface = data["name"]
     case["expected"] = CaseData.replace_data(case["expected"])
     expected = eval(case["expected"])
     method = case["method"]
     row = case["case_id"] + 1
     # 发送请求并获取响应结果
     response = self.request.send(url=url,
                                  headers=headers,
                                  method=method,
                                  json=data)
     res = response.json()
     if case["title"] == "新增项目成功":
         CaseData.project_id = str(jsonpath.jsonpath(res, "$.id")[0])
     if case["title"] == "创建成功-创建接口成功":
         CaseData.repeat_interface = jsonpath.jsonpath(res, "$.name")[0]
     print("预期结果", expected)
     print("实际结果", res)
     # 断言
     try:
         if case["assert"] == "n":
             self.assertEqual(expected["name"], res["name"])
         elif case["assert"] == "t":
             self.assertEqual(expected["tester"], res["tester"])
         elif case["assert"] == "p":
             self.assertEqual(expected["project_id"], res["project_id"])
         elif case["assert"] == "d":
             self.assertEqual(expected["desc"], res["desc"])
         elif case["assert"] == "j":
             self.assertLessEqual(expected["project_id"], res["project_id"])
         else:
             self.assertEqual(expected["name"], res["name"])
     except AssertionError as e:
         self.excel.write_data(row=row, column=9, value="不通过")
         raise e
     else:
         self.excel.write_data(row=row, column=9, value="通过")
Example #23
0
    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 = cls.request.send(url=url, method="post", json=data, headers=headers)
        res = response.json()
        token = jsonpath.jsonpath(res, "$..token")[0]
        token_type = jsonpath.jsonpath(res, "$..token_type")[0]
        cls.token_value = token_type + " " + token
        cls.member_id = jsonpath.jsonpath(res, "$..id")[0]
Example #24
0
 def setUpClass(cls):
     url = conf.get("env", "url") + "/member/login"
     data = {
         "mobile_phone": conf.get("test_case", "mobile_phone"),
         "pwd": conf.get("test_case", "pwd")
     }
     headers = eval(conf.get("env", "headers"))
     method = "post"
     login_response = cls.send.send_requests(url=url, method=method, headers=headers, json=data)
     data = login_response.json()
     token_type = jsonpath.jsonpath(data, "$..token_type")[0]
     token = jsonpath.jsonpath(data, "$..token")[0]
     cls.token_value = token_type + " " + token
     cls.member_id = jsonpath.jsonpath(data, "$..id")[0]
Example #25
0
    def test_recharge(self, case):
        # 第一步:准备用例数据
        url = conf.get("env", "url") + case["url"]
        method = case["method"]
        # 替换参数中的用户id
        case["data"] = replace_data(case["data"])
        data = eval(case["data"])
        headers = eval(conf.get("env", "headers"))
        headers["Authorization"] = getattr(CaseDate, "token_value")
        # 在请求头中加入setupclass中提取出来的token
        expected = eval(case["expected"])
        row = case["case_id"] + 1
        # 第二步:发送请求,获取结果
        # 发送请求之前,获取用余额
        if case["check_sql"]:
            sql = "SELECT leave_amount FROM futureloan.member WHERE mobile_phone={}".format(
                conf.get("test_data", "phone"))
            # 查询当前用户的余额
            start_money = self.db.find_one(sql)["leave_amount"]

        response = self.request.send(url=url,
                                     method=method,
                                     json=data,
                                     headers=headers)
        res = response.json()
        # 发送请求之后,获取用余额
        if case["check_sql"]:
            sql = "SELECT leave_amount FROM futureloan.member WHERE mobile_phone={}".format(
                conf.get("test_data", "phone"))
            # 查询当前用户的余额
            end_money = self.db.find_one(sql)["leave_amount"]
        # 第三步:断言(比对预期结果和实际结果)
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            # 判断示范需要进行sql校验
            if case["check_sql"]:
                self.assertEqual(end_money - start_money,
                                 Decimal(str(data["amount"])))
        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"]))
Example #26
0
    def test_withdraw(self, case):
        # 准备用例数据
        url = conf.get("env", "url") + case["url"]
        headers = eval(conf.get("env", "headers"))
        case["data"] = CaseData.replace_data(case["data"])
        if case["interface"] == "withdraw":
            headers["Authorization"] = getattr(CaseData, "token_value")
        data = eval(case["data"])
        expected = eval(case["expected"])
        method = case["method"]
        row = case["case_id"] + 1
        # 发送请求
        # 发送请求前查询数据库leave_amount金额
        if expected["code"] == 0:
            sql = "select leave_amount from futureloan.member where mobile_phone = {}".format(
                conf.get("test_case", "mobile_phone"))
            start_money = self.basedata.find_one(sql)["leave_amount"]
        reponse = self.request.send_requests(method=method,
                                             url=url,
                                             json=data,
                                             headers=headers)
        res = reponse.json()
        # 执行登录用例后,提取返回的token和member_id
        if case["interface"] == "login":
            token_type = jsonpath.jsonpath(res, "$..token_type")[0]
            token = jsonpath.jsonpath(res, "$..token")[0]
            CaseData.token_value = token_type + " " + token
            CaseData.member_id = str(jsonpath.jsonpath(res, "$..id")[0])
        # 断言
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertEqual(expected["msg"], res["msg"])
            if expected["code"] == 0 and case["interface"] != "login":
                sql = "select leave_amount from futureloan.member where mobile_phone = {}".format(
                    conf.get("test_case", "mobile_phone"))
                end_money = self.basedata.find_one(sql)["leave_amount"]
                self.assertEqual(start_money - end_money,
                                 Decimal(str(data["amount"])))

        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"]))
Example #27
0
 def test_recharge(self, case):
     # 准备用例数据
     url = conf.get("env", "url") + case["url"]
     headers = eval(conf.get("env", "headers"))
     headers["Authorization"] = getattr(CaseData, "token_value")
     case["data"] = CaseData.replace_data(case["data"])
     data = eval(case["data"])
     method = case["method"]
     expected = eval(case["expected"])
     row = case["case_id"] + 1
     # 发送请求
     if eval(case["expected"])["code"] == 0:
         sql = "select leave_amount from futureloan.member where mobile_phone={}".format(
             conf.get("test_case", "mobile_phone"))
         pre_data = self.basedata.find_one(sql)["leave_amount"]
Example #28
0
    def test_main_stream(self, case):
        # 第一步:准备用例数据
        url = conf.get("env", "url") + replace_data(case["url"])
        method = case["method"]
        if case["interface"] == "register":
            # 注册接口,则随机生成一个手机号码
            CaseDate.mobilephone = self.random_phone()
        data = eval(replace_data(case["data"]))
        headers = eval(conf.get("env", "headers"))

        # 判断是否是登录接口,不是登录接口则需要添加token
        if case["interface"] != "login" and case["interface"] != "register":
            headers["Authorization"] = getattr(CaseDate, "token_value")

        expected = eval(case["expected"])
        row = case["case_id"] + 1
        # 第二步:发送请求,获取结果
        print("请求参数:", data)
        response = self.request.send(url=url,
                                     method=method,
                                     json=data,
                                     headers=headers)
        res = response.json()
        print("预期结果", expected)
        print("实际结果", res)
        # 发送请求后,判断是否是登陆接口
        if case["interface"].lower() == "login":
            # 提取用户id保存为类属性
            CaseDate.member_id = str(jsonpath.jsonpath(res, "$..id")[0])
            token = jsonpath.jsonpath(res, "$..token")[0]
            token_type = jsonpath.jsonpath(res, "$..token_type")[0]
            # 提取token,保存为类属性
            CaseDate.token_value = token_type + " " + token
        # 判断是否是加标的用例,如果是的则请求标id
        if case["interface"] == "add":
            CaseDate.loan_id = str(jsonpath.jsonpath(res, "$..id")[0])
        # 第三步:断言(比对预期结果和实际结果)
        try:
            self.assertEqual(expected["code"], res["code"])
            self.assertIn(expected["msg"], res["msg"])
        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"]))
Example #29
0
    def logfile():
        # 创建一个日志收集器对象
        mylog = logging.getLogger(conf.get("log", "name"))
        # 设置日志收集器的收集等级
        mylog.setLevel("DEBUG")
        # 设置日志输出渠道
        # 控制台输出
        # 创建一个日志输出渠道对象
        sh = logging.StreamHandler()
        # 设置输出渠道的输出等级
        sh.setLevel("INFO")
        # 将日志输出渠道添加到日志收集器中
        mylog.addHandler(sh)

        # 日志文件输出
        # 创建一个日志文件输出渠道
        fh = logging.FileHandler(os.path.join(logs_dir, "Sunny.log"),
                                 encoding="utf8")
        # 设置日志输出渠道的输出等级
        fh.setLevel("INFO")
        # 将日志输出渠道添加到日志收集器中
        mylog.addHandler(fh)
        # 设置日志输出格式
        form = "%(asctime)s - [%(filename)s-->line:%(lineno)d] - %(levelname)s: %(message)s"
        # 创建一个日志输出格式对象
        fm = logging.Formatter(form)
        # 将日志输出渠道和日志格式绑定
        sh.setFormatter(fm)
        fh.setFormatter(fm)

        return mylog
 def test_projects(self, case):
     # 第一步:准备用例数据
     url = conf.get("env", "url") + case["url"]
     method = case["method"]
     # 准备请求头
     headers = {"Authorization": getattr(CaseDate, "token")}
     # 替换用例数据中的参数化
     data = eval(replace_data(case["data"]))
     # 替换预期结果中的数据
     expected = eval(replace_data(case["expected"]))
     row = case["case_id"] + 1
     # 第二步:发送请求,获取结果
     response = self.request.send(url=url,
                                  method=method,
                                  json=data,
                                  headers=headers)
     res = response.json()
     try:
         self.assert_dict_item(expected, res)
     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"]))