本文共 3180 字,大约阅读时间需要 10 分钟。
随着公司测试方向的转型,由原来的功能测试转变为接口测试,我决定使用Python编写一个接口自动化测试框架。以下是框架的搭建过程和总结。
正常的接口测试流程包括:
为了实现灵活性,我将业务和数据分离,设计了一个模块化的框架。
框架目录结构如下:
common/├── Log.py # 日志处理├── configHttp.py # 接口配置├── ReadConfig.py # 配置文件读取├── ConfigDB.py # 数据库配置├── ConfigEmail.py # 邮件配置└── common.py # 通用方法
result/├── *.log # 测试日志└── test.zip # 测试报告存档
testCase/├── test_case.py # 测试用例└── test_case.txt # 用例列表
testFile/├── SQL.xml # SQL语句存放└── test.xlsx # 测试用例存放
config.ini # 配置文件
caselist.txt # 需要执行的用例列表
配置文件config.ini内容包括:
[DATABASE]host=50.23.190.57username=xxxxxxxpassword=******port=3306database=databasename[HTTP]baseurl=http://xx.xxxx.xxport=8080timeout=1.0[EMAIL]mail_host=smtp.163.commail_user=xxxx@163.commail_pass=*********mail_port=25sender=xxx@163.comreceiver=xxxx@qq.com/xxxx@qq.comsubject=pythoncontent=...on_off=1
ReadConfig.py用于读取配置文件:
import osimport codecsimport configparserclass ReadConfig: def __init__(self): self.cf = configparser.ConfigParser() self.cf.read(os.path.join(os.path.dirname(__file__), "config.ini"))
Log.py实现了日志记录功能,并支持多线程操作:
import loggingfrom datetime import datetimeimport threadingclass Log: def __init__(self): global logPath, resultPath, proDir self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler = logging.FileHandler(os.path.join(self.resultPath, 'output.log')) handler.setFormatter(self.formatter) self.logger.addHandler(handler) configHttp.py实现了HTTP接口的get和post方法:
import requestsfrom ReadConfig import ReadConfigfrom common.Log import Logclass ConfigHttp: def __init__(self): self.log = Log.get_log() self.logger = self.log.get_logger() self.headers = {} self.params = {} self.data = {} self.url = None self.timeout = 0.5 ConfigDB.py实现了数据库连接与操作:
import pymysqlfrom ReadConfig import ReadConfigfrom common.Log import Logclass MyDB: def __init__(self): self.log = Log.get_log() self.logger = self.log.get_logger() self.db = None self.cursor = None
ConfigEmail.py实现了邮件发送功能,支持附件和压缩文件:
import osimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom datetime import datetimeimport threadingimport zipfileimport globclass Email: def __init__(self): self.value = readConfig.get_email("receiver") self.sender = readConfig.get_email("sender") self.subject = readConfig.get_email("subject") + " " + datetime.now().strftime("%Y-%m-%d %H:%M:%S") runAll.py执行测试并生成报告:
import unittestfrom HTMLTestRunner import HTMLTestRunnerimport osclass RunAll(unittest.TestCase): def set_case_list(self): with open(self.caseListFile) as fb: for value in fb.readlines(): data = str(value).strip() if data and not data.startswith("#"): self.caseList.append(data) 通过以上步骤,我们完成了一个完整的接口自动化测试框架。框架支持灵活配置接口参数,自动化处理数据库和邮件发送,并生成HTML格式的测试报告。后续工作中,可以继续扩展支持更多接口类型和测试用例管理功能。
转载地址:http://biafk.baihongyu.com/