如何实现接口测试case中的数据初始化

python

(zell.羽) #1

我们使用接口测试框架中需要实现case的数据初始化这里把代码说一下:
#-- coding: utf-8 --
import ConfigParser
import pymysql
import sys
sys.path.append(’…/db_fixture’)
class getDBConfig():
configpath = unicode(“E:/docs/系统测试/测试用例/zuihuibao_interface/db_config.ini”,“utf-8”)
#返回配置
def get_DBConfig(self,section, key):
config = ConfigParser.ConfigParser()
config.read(self.configpath)
return config.get(section, key)
#链接数据库
def connectDB(self):
dbhost = self.get_DBConfig(“testmysqlconf”, “host”)
dbport = int(self.get_DBConfig(“testmysqlconf”, “port”))
dbuser = self.get_DBConfig(“testmysqlconf”, “user”)
dbpassword = self.get_DBConfig(“testmysqlconf”, “password”)
dbname = self.get_DBConfig(“testmysqlconf”, “name”)
dbcharset = self.get_DBConfig(“testmysqlconf”, “charset”)
self.connection = pymysql.connect(host = dbhost,port = dbport,user = dbuser,password = dbpassword,db = dbname,charset= dbcharset, cursorclass=pymysql.cursors.DictCursor)
cur = self.connection.cursor()
return cur

#创建表
def createDB(self,sqlstr=None):
    cur = self.connectDB()
    if sqlstr!=None:
        try:
            cur.execute("%s"%(sqlstr))
            self.connection.commit()
        except:
            self.connection.rollback()
        else:
            self.connection.close()
        self.connection.close()

#插入数据
def insertDB(self,sqlstr=None):
    cur = self.connectDB()
    if sqlstr!=None:
        try:
            cur.execute("%s"%(sqlstr))
            self.connection.commit()
        except:
            self.connection.rollback()
    else:
        self.connection.close()
    self.connection.close()
#查询插入数据
def searchDB(self,sqlstr=None):
    cur = self.connectDB()
    if sqlstr!=None:
        try:
            cur.execute("%s"%(sqlstr))
            rows = cur.fetchall()
            for row in rows:
                return row
                #print "%s"%(row["id"])
        except:
            self.connection.rollback()
        self.connection.close()

#删除数据
def removeDB(self,sqlstr=None):
    cur = self.connectDB()
    if sqlstr!=None:
        try:
            cur.execute("%s"%(sqlstr))
            self.connection.commit()
        except:
            self.connection.rollback()
        self.connection.close()

if name == “main”:
getDBConfig()

备注:db_config.ini 的文件配置就是链接数据库的ip,port等等

实现测试cese时直接在def setUp(self): 里面实现调用方法就行了,方便吧


(冰河) #2

这个确实方便,自动化的初衷就是把重复的操作抽象到函数或类里面,供其他人调用,干得好😊


(骑车去看海) #3

傻傻的没看懂


(zell.羽) #4

返回配置那里写的是读取配置文件是以字典返回结果,相当于请求一个结果返回的reponse形式,我写在那里是为了让人看得懂它的原理,而不是直接写config.get()这个方法获取配置的值。下面的内容就是链接数据库,对数据库的各种操作


(骑车去看海) #5

谢谢你,你说的很清楚,我太菜了,我好好理解


(1024) #6

函数封装脑壳疼