对python自动生成接口测试的示例讲解


Posted in Python onNovember 30, 2018

在python中Template可以将字符串的格式固定下来,重复利用。 同一套测试框架为了可以复用,所以我们可以将用例部分做参数化,然后运用到各个项目中。

代码如下:

coding=utf-8
'''
作者:大石
功能:自动生成pyunit框架下的接口测试用例
环境:python2.7.6
用法:将用户给的参数处理成对应格式,然后调用模块类生成函数,并将参数传入即可
'''
 
from string import Template
#动态生成单个测试用例函数字符串
def singleMethodCreate(MethodList,interfaceNamePara):
  code=Template('''\n  def test_${testcase}(self):
    u"""${testcaseName}"""
    headers = $headers
    data = $data
    re = requests.$method(url='$url',headers=headers,data=data)
    status_code = re.status_code
    s = str(status_code)
    json = re.text
    logging.info('-'*5+'返回状态码是'+s+'-'*5)
    logging.info('-'*5+'返回结果集是'+json+'-'*5)
    assert status_code == 200
    assert json['status'] == 'ok'
''')
 
  string = code.substitute(testcase=MethodList["testcase"],testcaseName=MethodList["TestcaseName"],
               method=MethodList['method'],url=MethodList['url'],headers=MethodList['headers'],data=MethodList['data'],
               )
  return string
 
#拼接单个的测试用例函数字符串为完整字符串并传回主函数
#MethodParaList获取测试用例部分list
def methodCreate(MethodParaList,interfaceNamePara):
  string = ""
  for MethodPara in MethodParaList:
    string2=singleMethodCreate(MethodPara,interfaceNamePara)
    string=string+string2
  return string
 
#构造单个测试集
def singleTestsuitCreate(MethodList,parameters):
  code = Template('''suite.addTest(${className}("test_${testcase}"))''')
  string = code.substitute(testcase = MethodList["testcase"],className = parameters[0])
  return string
 
#添加测试集
def addtestsuit(MethodParaList,interfaceNamePara):
  string = ""
  for MethodPara in MethodParaList:
    string2 = singleTestsuitCreate(MethodPara,interfaceNamePara)
    string=string+string2
  return string
 
#生成测试用例类函数字符串
def modelClassCreate(parameters):
  modelCode = methodCreate(parameters[2],parameters[1])
  adtestsuit = addtestsuit(parameters[2],parameters)
  code = Template('''#coding: utf-8
"""
作者:大石
功能:待执行的接口测试用例
环境:python2.7.6
用法:通过框架自动触发调用
"""
import unittest,requests,datetime,sys,logging,BSTestRunner,time,os
from Log import Log
class ${className}(unittest.TestCase):
  u"""待测试接口:${interfaceName}"""
  def setUp(self):
    logging.info('-'*5+"begin test"+"-"*5)
  def tearDown(self):
    logging.info('-'*5+"end test"+'-'*5)
  ${model}
if __name__ == "__main__":
  #解决UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 97: ordinal not in range(128)
  reload(sys)
  sys.setdefaultencoding('utf8')
  #构造测试集
  suite = unittest.TestSuite()
  ${testsuite}
  #定义date为日期,time为时间
  date=time.strftime("%Y%m%d")
  time1=time.strftime("%H%M%S")
  now=time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
  #创建路径
  path='F:/test/study/yaml/test_log/'+now+"/"
  #解决多次执行时报路径已存在的错误
  try:
    os.makedirs(path)
  except:
    if path!= None:
      logging.error(u'当前路径已经存在')
  filename=path+'Report.html'
  fp=file(filename,'wb')
  #日志记录
  Log.log()
  #执行测试
  runner =BSTestRunner.BSTestRunner(stream=fp,title=u'下单平台接口测试用例',description=u'接口用例列表:')
  runner.run(suite)
  fp.close()
''')
  fileStr = code.substitute(className=parameters[0],interfaceName=parameters[1],testsuite=adtestsuit,model=modelCode)
  f=open(parameters[0]+".py",'w')
  f.write(fileStr)
  f.close()

然后测试用例部分如下:

parameters=["Testcase_Orders",
        "/login",
        [
          {"TestcaseName":"测试登录","method":"post","url":"http://www.senbaba.cn/login","headers":{'content-type': 'application/json',
          'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
          'Accept':'application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, */*',
          'Accept-Language':'zh-CN'},"data":{"uname":"187071484771","pwd":"123456"},
            "testcase":"login"},
 
          {"TestcaseName":"测试登录","method":"post","url":"http://www.senbaba.cn/login1","headers":{'content-type': 'application/json',
          'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
          'Accept':'application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, */*',
          'Accept-Language':'zh-CN'},"data":{"uname":"187071484771","pwd":"123457"},
            "testcase":"login_failed"}
        ]
      ]

自动生成的测试用例如下:

#coding: utf-8
"""
作者:大石
功能:待执行的接口测试用例
环境:python2.7.6
用法:通过框架自动触发调用
"""
import unittest,requests,datetime,sys,logging,BSTestRunner,time,os
from Log import Log
class Testcase_Orders(unittest.TestCase):
  u"""待测试接口:/login"""
  def setUp(self):
    logging.info('-'*5+"begin test"+"-"*5)
 
  def tearDown(self):
    logging.info('-'*5+"end test"+'-'*5)
 
  
  def test_login(self):
    u"""测试登录"""
    headers = {'Accept-Language': 'zh-CN', 'content-type': 'application/json', 'Accept': 'application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, */*', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'}
    data = {'uname': '187071484771', 'pwd': '123456'}
    re = requests.post(url='http://www.senbaba.cn/login',headers=headers,data=data)
    status_code = re.status_code
    s = str(status_code)
    json = re.text
    logging.info('-'*5+'返回状态码是'+s+'-'*5)
    logging.info('-'*5+'返回结果集是'+json+'-'*5)
    assert status_code == 200
    assert json['status'] == 'ok'
 
  def test_login_failed(self):
    u"""测试登录"""
    headers = {'Accept-Language': 'zh-CN', 'content-type': 'application/json', 'Accept': 'application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, */*', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'}
    data = {'uname': '187071484771', 'pwd': '123457'}
    re = requests.post(url='http://www.senbaba.cn/login1',headers=headers,data=data)
    status_code = re.status_code
    s = str(status_code)
    json = re.text
    logging.info('-'*5+'返回状态码是'+s+'-'*5)
    logging.info('-'*5+'返回结果集是'+json+'-'*5)
    assert status_code == 200
    assert json['status'] == 'ok'
 
 
if __name__ == "__main__":
  #解决UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 97: ordinal not in range(128)
  reload(sys)
  sys.setdefaultencoding('utf8')
  #构造测试集
  suite = unittest.TestSuite()
  
  suite.addTest(Testcase_Orders("test_login"))
 
  suite.addTest(Testcase_Orders("test_login_failed"))
 
  #定义date为日期,time为时间
  date=time.strftime("%Y%m%d")
  time1=time.strftime("%H%M%S")
  now=time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
  #创建路径
  path='F:/test/study/yaml/test_log/'+now+"/"
  #解决多次执行时报路径已存在的错误
  try:
    os.makedirs(path)
  except:
    if path!= None:
      logging.error(u'当前路径已经存在')
  filename=path+'Report.html'
  fp=file(filename,'wb')
  #日志记录
  Log.log()
  #执行测试
  runner =BSTestRunner.BSTestRunner(stream=fp,title=u'下单平台接口测试用例',description=u'接口用例列表:')
  runner.run(suite)
  fp.close()

20171019添加测试集的一个简单方法:

#添加测试集
def addtestsuit(parameters):
  string = ""
  temp = Template('''\n  suite.addTest(${className}("test_${testcase}"))
''')
  l = len(parameters[2])
  for i in range(0,l):
    testcase1 = parameters[2][i]['testcase']
    string2 = temp.substitute(className = parameters[0],testcase = testcase1)
    string=string+string2
    print string
  return string

以上这篇对python自动生成接口测试的示例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
py中的目录与文件判别代码
Jul 16 Python
浅析python中SQLAlchemy排序的一个坑
Feb 24 Python
Python处理XML格式数据的方法详解
Mar 21 Python
浅谈numpy数组中冒号和负号的含义
Apr 18 Python
对python中for、if、while的区别与比较方法
Jun 25 Python
python+numpy+matplotalib实现梯度下降法
Aug 31 Python
python实现AES加密与解密
Mar 28 Python
python实现祝福弹窗效果
Apr 07 Python
在Python中合并字典模块ChainMap的隐藏坑【推荐】
Jun 27 Python
使用Python实现跳一跳自动跳跃功能
Jul 10 Python
Python如何实现小程序 无限求和平均
Feb 18 Python
python中使用input()函数获取用户输入值方式
May 03 Python
在unittest中使用 logging 模块记录测试数据的方法
Nov 30 #Python
浅谈python在提示符下使用open打开文件失败的原因及解决方法
Nov 30 #Python
python2与python3的print及字符串格式化小结
Nov 30 #Python
Python 中 function(#) (X)格式 和 (#)在Python3.*中的注意事项
Nov 30 #Python
Python3 jupyter notebook 服务器搭建过程
Nov 30 #Python
解决Python2.7中IDLE启动没有反应的问题
Nov 30 #Python
python实现停车管理系统
Nov 30 #Python
You might like
上海地方志办公室-上海电子仪表工业志
2021/03/04 无线电
php empty,isset,is_null判断比较(差异与异同)
2010/10/19 PHP
PHP中JSON的应用技巧
2015/10/10 PHP
PHP使用递归算法无限遍历数组示例
2017/01/13 PHP
php字符集转换
2017/01/23 PHP
PHP两种实现无级递归分类的方法
2017/03/02 PHP
PHP实现简单用户登录界面
2019/10/23 PHP
js操作CheckBoxList实现全选/反选(在客服端完成)
2013/02/02 Javascript
简单的代码实现jquery定时器
2014/01/03 Javascript
jQuery实现流动虚线框的方法
2015/01/29 Javascript
jQuery中$.extend()用法实例
2015/06/24 Javascript
jquery实现ajax加载超时提示的方法
2016/07/23 Javascript
JS正则替换去空格的方法
2017/03/24 Javascript
使用Browserify来实现CommonJS的浏览器加载方法
2017/05/14 Javascript
关于Js中new操作符的作用详解
2021/02/21 Javascript
Python类的基础入门知识
2008/11/24 Python
深入理解python try异常处理机制
2016/06/01 Python
Python 3.x 判断 dict 是否包含某键值的实例讲解
2018/07/06 Python
对pandas的层次索引与取值的新方法详解
2018/11/06 Python
Python 最强编辑器详细使用指南(PyCharm )
2019/09/16 Python
提升python处理速度原理及方法实例
2019/12/25 Python
python单例设计模式实现解析
2020/01/07 Python
pytorch查看通道数 维数 尺寸大小方式
2020/05/26 Python
使用Python pip怎么升级pip
2020/08/11 Python
Python3利用scapy局域网实现自动多线程arp扫描功能
2021/01/21 Python
吉力贝官方网站:Jelly Belly
2019/03/11 全球购物
G-Form护具官方网站:美国运动保护装备
2019/09/04 全球购物
罗马尼亚在线杂货店:Pilulka.ro
2019/09/28 全球购物
会计应聘求职信范文
2013/12/17 职场文书
男女朋友协议书
2014/04/23 职场文书
学习三严三实对照检查材料思想汇报
2014/09/22 职场文书
2014年酒店工作总结范文
2014/11/17 职场文书
初中班主任工作总结2015
2015/05/13 职场文书
女方家长婚礼答谢词
2015/09/29 职场文书
2016母亲节感恩话语
2015/12/09 职场文书
小学音乐课歌曲《堆雪人》教学反思
2016/02/18 职场文书