前言
自己通过摸索,和借鉴、综合大神些的意见,捣鼓了一套接口自动化的脚本。比较简略,还有一些有局限的地方,欢迎大家斧正留言~~~
工具
requests -- Python的requests库
xlrd -- 操作Excel
moco(moco-runner-0.10.0-standalone.jar) -- moco-server模拟接口
logging -- 日志
下图是我的目录结构:
common:存放一些通用/公用的文件
function:存放的接口的业务文件
工作流程
接口的测试用例在Excel文件中进行维护,使用第三方库 xlrd 对 Excel 操作,遍历读取测试用例。接下来封装requests库,符合自己的接口业务测试流程,使用封装好的类完成接口请求,创建run_api.py文件,运行测试用例。
一、配置文件config
我本次使用的Python文件来作为配置文件,因为个人觉得这种方式读取配置项的时候:简单、易懂、直观,在使用的时候,直接导入配置文件即可使用。
config.py:
# -*- coding:utf-8 -*-
""" 接口相关配置 """
host = 'http://127.0.0.1:5025'
"""Excel"""
# FILE_PATH = "F:\PyCharmProject\LYKION\new\API_Case.xlsx" # 因为文件夹的名字中有'n',而在Python中'n'表示空格,所以要在前面加'\'进行转义
FILE_PATH = "F:\PyCharmProject\LYKION\self_learn\API_Case.xlsx"
"""Excel中单元格列的配置"""
CASE_URL = 3
CASE_METHOD = 4
CASE_HEADER = 5
CASE_DATA = 7
"""其他(测试类会用到)"""
url = 'http://127.0.0.1:5025/do/extra'
method = 'post'
data = {
'OrderCode': '1002',
'ShipperCode': 'SF',
'LogisticCode': '118652124588863'
}
headers = {
'Content-Type': 'application/json'
}
data_type = 'Json'
is_header = 'yes'
二、logging封装
个人觉得用 print 打印,不好看(哈哈^_^),就用logging自己封装了一个,log输出格式自己定义,在控制台打印的 log 开起来就舒服多了,本文的 log 格式比较简单
# -*- coding:utf-8 -*-
import logging
class logger:
def __init__(self):
self.logger = logging.getLogger()
self.logger.setLevel(logging.INFO)
# 设置log输出格式
self.formatter = logging.Formatter('[%(asctime)s] -- %(levelname)s: %(message)s', '%Y-%m-%d %H:%M:%S')
self.consle = logging.StreamHandler() # StreamHandler将log输出到控制台
self.consle.setFormatter(self.formatter)
self.consle.setLevel(logging.INFO)
self.logger.addHandler(self.consle)
def info(self, msg):
self.logger.info(msg)
self.logger.removeHandler(self.consle)
def debug(self, msg):
self.logger.debug(msg)
self.logger.removeHandler(self.consle)
def error(self, msg):
self.logger.error(msg)
self.logger.removeHandler(self.consle)
def critical(self, msg):
self.logger.critical(msg)
self.logger.removeHandler(self.consle)
def warning(self, msg):
self.logger.warning(msg)
self.logger.removeHandler(self.consle)
if __name__ == '__main__':
logger().info('dfd14575')
三、封装Excel
Excel的格式都是自定义的,其格式都是按照各自的接口需求来定。
我自己写的格式不复杂,很简单。