今天突然想使用做一下接口测试,做了个简单测试
1、准备测试数据
version | cityid | city | ip | callback |
v1 | 101120201 | 青岛 | 27.193.13.255 | |
v1 | 101010100 | 北京 | 27.193.13.255 | |
v1 | 101010300 | 朝阳 | 27.193.13.255 | |
v1 | 101010300 | 顺义 | 27.193.13.255 | |
v1 | 101010400 | 怀柔 | 27.193.13.255 | |
v1 | 101010500 | 通州 | 27.193.13.255 |
2、编写文件读取的工具类:
# coding=utf-8
import xlrd
class FileUtils():
def __init__(self, file_path, sheet_index):
self.data = xlrd.open_workbook(file_path)
self.table = self.data.sheet_by_index(sheet_index)
self.key = self.table.row_values(0)
self.row_num = self.table.nrows
self.clo_num = self.table.ncols
def read_excel(self):
if self.row_num <= 1:
print (u"Excel数据小于等于1行")
else:
list = []
num = 1
for row in range(self.row_num - 1):
dict = {}
values = self.table.row_values(num)
for clo in range(self.clo_num):
dict[self.key[clo]] = values[clo]
list.append(dict)
num += 1
return list
if __name__ == '__main__':
file_path = "E:\\PythonWorkspace\\Portal\\file\\test_data.xlsx"
sheet_index = 0
data = FileUtils(file_path, sheet_index)
list = data.read_excel()
print list
编写测试类:
# coding=utf-8
from interface.FileUtils import FileUtils
import requests
import unittest
import ddt
@ddt.ddt
class Inter(unittest.TestCase):
file_path = "E:\\PythonWorkspace\\Portal\\file\\test_data.xlsx"
sheet_index = 1
data = FileUtils(file_path, sheet_index)
lists = data.read_excel()
def setUp(self):
print (u"程序执行开始")
self.url = "https://www.tianqiapi.com/api/"
@ddt.data(*lists)
def test_inter(self, lists):
print (u"第一%s执行" % lists)
r = requests.get(self.url, lists)
print r.text
def test_4(self):
u"通过post请求获取天气数据"
dicts = {
"version": "v1",
"cityid": "101120201",
"city": u"青岛",
"ip": "27.193.13.255",
"callback": ""
}
url = "https://www.tianqiapi.com/api/"
req = requests.post(url, json=dicts)
print(req.status_code)
print(req.text)
print(req.content)
def tearDown(self):
print u"程序执行完成"
if __name__ == '__main__':
unittest.main()
生成测试报告
# coding:utf-8
import unittest
import os
import HTMLTestRunner
# 用例路径
case_path = os.path.join(os.getcwd(), "")
print case_path
# 报告存放路径
report_path = os.path.join(os.getcwd(), "")
print report_path
# html报告文件
report_abspath = os.path.join(report_path, "result.html")
discover = unittest.defaultTestLoader.discover(case_path,
pattern="case*.py",
top_level_dir=None)
fp = open(report_abspath, "wb")
runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
title=u'自动化测试报告,测试结果如下:',
description=u'用例执行情况:')
# 调用add_case函数返回值
runner.run(discover)
fp.close()