MySQL 数据库断言工具类 笔记

4 阅读1分钟

1,config目录下配置文件………………………………

DB_CONFIG = {
    "host": "xxx",
    "port": 3306,
    "user": "xxx",
    "password": "xxx",
    "database": "xxx"
}

2,db_utils工具类………………………………

import pymysql
from auto_test.config.mysql_setting import DB_CONFIG

class DBUtil:
    # 链接数据库配置
    def __init__(self):
        self.conn = pymysql.connect(
            host=DB_CONFIG["host"],
            port=DB_CONFIG["port"],
            user=DB_CONFIG["user"],
            password=DB_CONFIG["password"],
            database=DB_CONFIG["database"],
            charset="utf8",
            cursorclass=pymysql.cursors.DictCursor  # 返回字典格式
        )
        self.cursor = self.conn.cursor()

    def query(self, sql, args=None):
        """查询单条/多条"""
        self.cursor.execute(sql, args)
        return self.cursor.fetchall()

    def query_one(self, sql, args=None):
        """查询单条"""
        self.cursor.execute(sql, args)
        return self.cursor.fetchone()

    def execute(self, sql, args=None):
        """增删改"""
        rows = self.cursor.execute(sql, args)
        self.conn.commit()
        return rows

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

# 简化调用
db = DBUtil()

3,调用………………………………

def test_order_create():
    # 1. 调用创建订单接口
    order_id = create_order()

    # 2. 数据库查询
    sql = "SELECT * FROM t_order WHERE id = %s"
    order = db.query_one(sql, order_id)

    # 3. 断言数据库数据正确
    assert order is not None
    assert order["status"] == 1
    assert order["money"] == 99

    db.close()