使用XML文件管理测试数据 使用Excel文件保存测试用例和测试结果: Python脚本遍历全部测试用例: # -*- coding=utf-8 -*-
import os
import sys
import requests
from xml.dom.minidom import parse
from openpyxl.reader.excel import load_workbook
# import xml.dom.minidom
# Window下必须加载Commons库的目录 否则在Dos窗口中执行时会找不到库文件
parent_dir = os.path.split(os.getcwd())[0]
comm_dir = parent_dir+str("\BaseFunction")
sys.path.append(comm_dir)
AUTO_RESULT = u"E:\PyScripts\MdServices\TestCases\WebServiceCases.xlsx"
# 自动化测试用例Excel文件
case_file = open(u'E:\PyScripts\MdServices\TestCases\casedata.xml', 'rb')
# 加载XML文件
tree = parse(file=case_file)
collection = tree.documentElement
# 读取所有接口方法信息
operation_list = collection.getElementsByTagName('Operation')
# 读取保存测试结果的文件
book = load_workbook(AUTO_RESULT)
# 获取Excel文件中的表单sheet
sheet_names = book.get_sheet_names()
# 指定工作表单--根据sheet名查找
working_sheet = book.get_sheet_by_name(sheet_names[0])
# Excel中测试用例开始的索引
start_index = 2
# 循环每个webservice方法
for operation in operation_list:
# 定义operation的UR地址
uri = operation.getAttribute('url')
# 读取接口中方法的调用方式get post head等等
action_type = operation.getAttribute('action')
# 接口方法名
function_name = operation.getAttribute('name')
# 读取所有测试用例
case_list = operation.getElementsByTagName("case")
# 循环执行所有测试用例
for case in case_list:
# 得到测试用例中所有参数的名称和值
parameter_list = case.getElementsByTagName("Parameter")
length = len(parameter_list)-1
json_data = {}
for index in (0, length):
# 得到参数名称
name = parameter_list[index].getAttribute('name')
# 得到参数值
value = parameter_list[index].getAttribute('value')
# 将每个参数和值存为字典形式 即JSON格式
json_data[name] = value
# 接口调用方式为post
if action_type == 'post':
# 接口中方法的调用方式为post
response = requests.post(uri, data=json_data)
# 测试用例编号
case_id_locator = 'A'+str(start_index)
# 保存case id
working_sheet.cell(case_id_locator).value = start_index
# 保存Excel文件的更改信息
book.save(AUTO_RESULT)
# service接口 url地址
service_url_locator = 'B'+str(start_index)
# 保存case id
working_sheet.cell(service_url_locator).value = uri
# 保存Excel文件的更改信息
book.save(AUTO_RESULT)
# 接口方法名称
function_name_locator = 'C'+str(start_index)
# 保存case id
working_sheet.cell(function_name_locator).value = function_name
# 保存Excel文件的更改信息
book.save(AUTO_RESULT)
# 实际返回结果
actual_result_locator = 'G'+str(start_index)
# 保存case id
working_sheet.cell(actual_result_locator).value = response.content
# 保存Excel文件的更改信息
book.save(AUTO_RESULT)
# 预期返回结果
expect_result_locator = 'F'+str(start_index)
expected_content = working_sheet.cell(expect_result_locator).value
# run result测试结果
run_result_locator = 'H'+str(start_index)
# 对比预期结果和实际结果
if expected_content == actual_result_locator:
working_sheet.cell(run_result_locator).value = 'Pass'
else:
working_sheet.cell(run_result_locator).value = 'Fail'
# 保存Excel文件的更改信息
book.save(AUTO_RESULT)
# 接口调用方式为get
elif action_type == 'get':
response = requests.get(uri, data=json_data)
print 'hello get webservice'
# Excel中循环
start_index += 1
# print 'start index', start_index
|