HttpRunner+Mysql查询实现接口测试

一、框架版本
httprunner 2.X

二、实现场景
实现充值接口测试

三、接口文档
在这里插入图片描述

四、代码
在这里插入图片描述

设计思路:
接口调用前,先查下数据库余额(假设是1000),然后将想要充值的金额(定义好是600),两者求和,1000+600=1600.。
调用接口,看返回值,取出金额字段的值,进行断言,如果是1600,那么断言成功,测试通过。

1、测试用例recharge_amountchange.yml:

config:
    name: "充值接口测试"

teststeps:
-
    # 第一步,登录
    name: "登录"
    #需要引用api文件夹中的接口(接口代码不方便公开)
    api: api/login.yml
    variables:
    
    extract:
        - token: content.data.token_info.token
    validate:
        - eq: [content.code, 0]
        - eq: ["content.msg", "OK"]
-
    # 第二步, 充值
    name: "充值"
     #需要引用api文件夹中的接口(接口代码不方便公开)
    api: api/recharge.yml
    variables:
        #充值金额
        amount: 600
        #用户id
        inver_user_id: ${ENV(inver_user_id)}
         #充值前余额,需要引用debugtalk里面的方法
        before_amount: ${before_recharge_amount($inver_user_id)}
        #充值后余额,需要引用debugtalk里面的方法
        new_amount: ${new_recharge_amount($amount,$before_amount)}

    validate:

        - {"check":"content.code","comparator":"eq","expect":0}
        - {"check":"content.msg","comparator":"contains","expect":"OK"}
        #接口返回值与预期值对比(new_amount)
        - {"check":"content.data.leave_amount","comparator":"eq","expect":$new_amount}

2、将自定义的方法写入debugtalk.py(框架自带的文件,可写入自己需要的方法)

import handle_mysql
#查询充值前余额
def before_recharge_amount(inver_user_id):
    sql1="SELECT leave_amount FROM member WHERE id ="
    sql2=str(inver_user_id)
    sql3=';'
    #拼接sql语句
    check_sql =sql1+sql2+sql3
    #创建实例
    sql_class=handle_mysql.HandleMysql()
    #调用实例类中的方法
    mysql_data = sql_class.get_one_value(sql=check_sql)
    sql_class.close()
    return float(mysql_data['leave_amount']) 
#计算充值后的余额
def new_recharge_amount(amount,before_amount):
    return  float(amount)+float(before_amount)

3、连接mysql方法handle_mysql工具类

class HandleMysql:
    """
    执行sql语句
    """
    def __init__(self):
        self.conn = pymysql.connect(host="XXXXXXX",
                                    user="XXXXXXX",
                                    password="XXXXXXX",
                                    db="XXXXXXX",
                                    port=3306,
                                    charset='utf8',  # 这里只能写为utf8
                                    cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()

    def get_one_value(self, sql, args=None):
        self.cursor.execute(sql, args=args)
        self.conn.commit()
        return self.cursor.fetchone()

    def get_values(self, sql, args=None):
        self.cursor.execute(sql, args=args)
        self.conn.commit()
        return self.cursor.fetchall()

    def close(self):
        self.cursor.close()
        self.conn.close()

猜你喜欢

转载自blog.csdn.net/weixin_38917342/article/details/107549118