Pytest-数据库连接操作(执行用例前或者执行用例之后的前置或者后置工作)

2021/5/19 2:25:30

本文主要是介绍Pytest-数据库连接操作(执行用例前或者执行用例之后的前置或者后置工作),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

pytest操作数据所需模块PyMysql

安装推荐:pip install PyMsyql==0.9.3

先写个方法获取到项目的根目录

# coding=utf-8
import os

def root_path():
    cur_path = os.path.dirname(os.path.realpath(__file__))
    root_path = os.path.dirname(cur_path)

    return root_path

if __name__ == '__main__':
    print(root_path())

再写个方法读取yaml文件中的数据库配置信息

# coding=utf-8
from config.root_path import root_path
import yaml
import os

def rade_date_list(yaml_path):
    f = open(yaml_path, "r", encoding="utf-8")
    read_f = f.read()

    login_data_list = yaml.safe_load(read_f)

    return login_data_list

if __name__ == '__main__':

    yaml_path = os.path.join(root_path(), "data", "mysql.yml")
    print(rade_date_list(yaml_path))

封装一个查询数据和执行数据操作的方法

# coding=utf-8
import pymysql
import os
from common.rade_yml import rade_date_list
from config.root_path import root_path

class DbMysql(object):

    def __init__(self,dbinfo):
        self.db = pymysql.connect(
            cursorclass=pymysql.cursors.DictCursor,
            **dbinfo
        )
        self.cursor = self.db.cursor()

    def select(self,sql):
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        return result

    def execute(self,sql):
        self.cursor.execute(sql)
        self.db.commit()

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

if __name__ == '__main__':
    mysql_info = rade_date_list(os.path.join(root_path(), "data", "mysql.yml"))
    db = DbMysql(mysql_info)
    sql = 'select * from auth_user au where username = "test001"'
    result = db.select(sql)
    print(result)
    db.close()

最后接口用例进行调用

# coding=utf-8
from api.ke_register import user_register
from common.common_mysql import DbMysql
from common.rade_yml import rade_date_list
from config.root_path import root_path
import os
import pytest

db_cnf = rade_date_list(os.path.join(root_path(),"data","mysql.yml"))

@pytest.fixture(scope="function")
def delete_register():
    '''前置操作,删除注册的数据'''
    db = DbMysql(db_cnf)
    sql = 'DELETE FROM auth_user where username ="test001"'
    db.execute(sql)
    db.close()

def test_user_register(delete_register):
    '''输入待注册账号以及密码,完成注册'''
    print("输入账号密码,完成注册!")
    res = user_register()
    print(res.text)
    assert res.json()["code"] == 0

 



这篇关于Pytest-数据库连接操作(执行用例前或者执行用例之后的前置或者后置工作)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程