python学习笔记(excel+unittest)

时间:2024-07-23 23:33:20

准备先利用之前整理的python自带的unittest框架

整合excel 实现接口自动化测试功能

先看看excel表格设置:

python学习笔记(excel+unittest)

下来是对excel获取的代码:

 #!/usr/bin/env python
# -*- coding: utf_8 -*- import xlrd
import json class Create_excel:
def open_excel(self,path):
workbook = xlrd.open_workbook(path)
table = workbook.sheets()[0]
return table
#获取sheet def get_nrows(self,table):
nrows = table.nrows
return nrows
#获取行号 def testname(self,table,nrows):
TestName = []
for i in range(1,nrows):
TestName.append(table.cell(i,0).value)
return TestName
#获取用例name def testdata(self,table,nrows):
TestData = []
for i in range(1,nrows):
data = json.loads(table.cell(i,1).value)
TestData.append(data)
return TestData
#获取data接口参数 def testurl(self,table,nrows):
TestUrl = []
for i in range(1,nrows):
TestUrl.append(table.cell(i,2).value)
return TestUrl
#获取接口测试url def testpattern(self,table,nrows):
TestPattern = []
for i in range(1,nrows):
TestPattern.append(table.cell(i,3).value)
return TestPattern
#获取接口期望响应结果 def testreport(self,table,nrows):
TestReport = []
for i in range(1,nrows):
TestReport.append(table.cell(i,4).value)
return TestReport
#获取用例期望的运行结果 if __name__ == "__main__":
Create_excel()

之后是unittest框架

 #!/usr/bin/env python
# -*- coding: utf_8 -*- import requests
import re
import unittest
from myexcel import Create_excel class Testapi():
def testapi(self,url,data):
results = requests.post(url,data)
return results class Testcase(unittest.TestCase):
def setUp(self):
print "接口测试开始" def tearDown(self):
print "接口测试结束" def test_post(self):
global report
api = Testapi()
excel = Create_excel()
testpath = "testcase.xls"
testtable = excel.open_excel(testpath)
testnrows = excel.get_nrows(testtable)
for i in range(0,testnrows-1):
testname = excel.testname(testtable,testnrows)[i]
testdata = excel.testdata(testtable,testnrows)[i]
testurl = excel.testurl(testtable,testnrows)[i]
testpattern = excel.testpattern(testtable,testnrows)[i]
testreport = excel.testreport(testtable,testnrows)[i]
testresults = api.testapi(testurl,testdata)
pattern = re.compile(testpattern)
match = pattern.search(testresults.url)
try:
if testresults.status_code == 200:
if match.group() == testpattern:
report = "pass"
else:
print "测试请求失败"
except AttributeError:
report = "no"
if report == testreport:
print "用例名称:",testname,"测试结果:测试通过"
else:
print "用例名称:",testname,"测试结果:测试失败" if __name__ == "__main__":
unittest.main()

利用循环执行所有用例

python学习笔记(excel+unittest)

现在只要在excel里添加接口测试用例

运行脚本 即可