-数据插入(容易实现的测试场景下所需外部数据)
-准备sql (接口需要重复使用,参数一定得是变量)
-平滑升级验证脚本加入自动化
-调用mysql
-excel遍历测试用例
-requests实现接口调用
-根据接口返回的code值和Excel对比
-报告反馈
-暴露服务
写一个简单登录的接口自动化测试
代码实现如下:
#!/usr/bin/python
#-*- coding: UTF-8 -*-
# 基础包:excel的封装
import xlrd
workbook = None
def openExcel(path):
"""打开excel"""
global workbook
if (workbook == None):
workbook = xlrd.open_workbook(path, on_demand=True)
def getSheet(sheetName):
"""获取行号"""
global workbook
return workbook.sheet_by_name(sheetName)
def getRows(sheet):
"""获取行号"""
return sheet.nrows
def getContent(sheet, row, col):
"""获取表格中内容"""
return sheet.cell(row, col).value
def release(path):
"""释放excel减少内存"""
global workbook
workbook.release_resources()
del workbook
代码封装后当成模块引用,这还是最开始呢。
准备工作:
需要一个日志的捕获,包括框架和源码抛出的expection。
代码如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 基础包:日志服务
import logging
import time
def getLogger():
global tezLogPath
try:
tezLogPath
except NameError:
tezLogPath = "/data/log/apiTest/"
FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
# file = tezLogPath + time.strftime("%Y-%m-%d", time.localtime()) + ".log"
# logging.basicConfig(filename=file, level=logging.INFO, format=FORMAT)
# 开发阶段为了方便调试,可不输出到文件
logging.basicConfig(level=logging.INFO, format=FORMAT)
return logging
准备工作:
需要的请求类型和执行测试的方法。
代码如下:
#!/usr/bin/python#
#-*- coding: UTF-8 -*-
# 基础包:接口测试的封装
import requests
import tezLog as log
logging = log.getLogger()
def apiTest(method, url, data ,headers):
"""
定义一个请求接口的方法和需要的参数
:Args:
method - 企业名称 str
url - 用户昵称 str
data - 参数 str
headers - 请求头信息 dict
"""
try:
if method == "post":
results = requests.post(url, data, headers=headers)
if method == "get":
results = requests.get(url, data, headers=headers)
if method == "put":
results = requests.put(url, data, headers=headers)
if method == "delete":
results = requests.delete(url, headers=headers)
if method == "patch":
results == requests.patch(url, data, headers=headers)
if method == "options":
results == requests.options(url, headers=headers)
response = results.json()
code = response.get("code")
return code
except Exception, e:
logging.error("service is error", e)
def runTest(sheet):
"""
定义一个执行和断言的方法
:Args:
sheet - 服务名称 str(excel页脚名称识别的)
"""
rows = excel.getRows(sheet)
fail = 0
for i in range(2, rows):
#这里为什么从第二行开始跑,因为会先执行SQL如之前Excel展示的空白位置
testData = excel.getContent(sheet, i, gl.CASE_DATA)
testUrl = excel.getContent(sheet, i, gl.CASE_URL)
testMethod = excel.getContent(sheet, i, gl.CASE_METHOD)
testHeaders = eval(excel.getContent(sheet, i, gl.CASE_HEADERS))
testCode = excel.getContent(sheet, i, gl.CASE_CODE)
actualCode = request.apiTest(testMethod, testUrl, testData, testHeaders)
expectCode = str(int(testCode))
failResults = ' url: ' + testUrl + ' params: ' + testData + ' actualCode: ' + actualCode + ' expectCode: ' + expectCode
if actualCode == expectCode:
logging.info("pass")
elif actualCode != expectCode:
logging.info("fail %s", failResults)
fail += 1
if fail > 0 :
return False
return True
准备工作:
所有的参数和常量我们会整理到这个文件中,因为设计业务和服务密码、数据库密码这里展示一部分。
代码如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 脚本功能:全部变量
import time
import uuid
CASE_NUMBER = 0 # 用例编号
CASE_NAME = 1 # 用例名称
CASE_DATA = 2 # 用例参数
CASE_URL = 3 # 用例接口地址
CASE_METHOD = 4 # 用例请求类型
CASE_CODE = 5 # 用例code
CASE_HEADERS = 6 # 用例headers
SQL_ROW = 0 # 预执行SQL的行号
SQL_COL = 1 # 预执行SQL的列号
代码如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 验证包:接口测试脚本
import sys
import core.tezLog as log
import function.common as common
logging = log.getLogger()
"""1.外部输入参数"""
path = sys.path[0] # 当前路径
module = sys.argv[1] # 服务模块名
url = sys.argv[2] # 服务地址
host = sys.argv[3] # 数据库地址
user = sys.argv[4] # 数据库用户名
password = sys.argv[5] # 数据库密码
db = sys.argv[6] # 数据库名称
"""2.根据module获取Sheet"""
logging.info("-------------- Execute TestCases ---------------")
sheet = common.getExcelSheet(path + "/" + common.filename, module)
"""3.数据准备"""
logging.info("-------------- Prepare data through MysqlDB --------------")
sql = common.getPrepareSql(sheet)
common.prepareData(host=host, user=user, password=password, db=db, sql=sql)
"""4.执行测试用例"""
res = common.runTest(sheet, url)
logging.info("-------------- Get the result ------------ %s", res)
#这里的res是我们平滑升级的时候需要返回结果为TRUE才会继续下面走。