Commit ee8b9d4d authored by 蒲肖建's avatar 蒲肖建

极客数学帮APP接口自动化测试项目代码提交

parent a0b6512e
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="Unittests" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.7" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/JksxbAPPInterfaceAutoTest.iml" filepath="$PROJECT_DIR$/.idea/JksxbAPPInterfaceAutoTest.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
# coding:utf-8
from common.operation_log import Log
log = Log(__name__).get_logger()
class ApiDataIndex:
api_id_num = 0
api_name_num = 1
api_method_num = 2
api_uri_num = 3
api_header_num = 4
api_params_num = 5
api_body_num = 6
api_depend_num = 7
api_is_run_num = 8
api_except_num = 9
class ApiData:
def __init__(self, api_data: list):
self.api_id = api_data[get_api_id_num()].strip()
self.api_name = api_data[get_api_name_num()].strip()
self.api_method = api_data[get_api_method_num()].strip()
self.api_uri = api_data[get_api_uri_num()].strip()
self.api_header = api_data[get_api_header_num()].strip()
self.api_params = api_data[get_api_params_num()].strip()
self.api_body = api_data[get_api_body_num()].strip()
self.api_depend = api_data[get_api_depend_num()].strip()
self.api_is_run = api_data[get_api_is_run_num()].strip()
self.api_except = api_data[get_api_expect_num()].strip()
# 获取caseid
def get_api_id_num():
return ApiDataIndex.api_id_num
# 获取uri
def get_api_uri_num():
return ApiDataIndex.api_uri_num
def get_api_is_run_num():
return ApiDataIndex.api_is_run_num
def get_api_method_num():
return ApiDataIndex.api_method_num
def get_api_header_num():
return ApiDataIndex.api_header_num
def get_api_depend_num():
return ApiDataIndex.api_depend_num
def get_api_name_num():
return ApiDataIndex.api_name_num
def get_api_expect_num():
return ApiDataIndex.api_except_num
def get_api_body_num():
return ApiDataIndex.api_body_num
def get_api_params_num():
return ApiDataIndex.api_params_num
# coding=utf-8
import xlrd
from base import api_config
from base import request_data_config
from base.request_api import RequestApi
from common.operation_excel import OperationExcel
from common.operation_log import Log
log = Log(__name__).get_logger()
class GetExcelData:
def __init__(self, api_file_path, request_data_path):
self.api_path = api_file_path
self.request_data_path = request_data_path
log.info("init对象GetExcelData参数,api_file_path: %s, request_data_path: %s" % (api_file_path, request_data_path))
def get_api_datas(self, sheet_name):
wb = xlrd.open_workbook(self.api_path, encoding_override="utf-8")
sheet = wb.sheet_by_name(sheet_name)
row_num = sheet.nrows
api_datas = []
for i in range(1, row_num):
row_values = sheet.row_values(i)
if row_values[0]:
api_data = api_config.ApiData(row_values)
api_datas.append(api_data)
return api_datas
def get_request_datas(self, sheet_name):
wb = xlrd.open_workbook(self.request_data_path, encoding_override="utf-8")
sheet = wb.sheet_by_name(sheet_name)
row_num = sheet.nrows
request_datas = []
for i in range(1, row_num):
row_values = sheet.row_values(i)
if row_values[0]:
request_data = request_data_config.RequestData(row_values)
request_datas.append(request_data)
return request_datas
def get_rquest_data_by_api_id(self, api_id, sheet_name):
log.info("使用api_id获取rquest_data的参数:api_id:%s,sheet_name:%s:" % (api_id, sheet_name))
oe = OperationExcel(self.request_data_path, sheet_name)
request_datas = oe.get_row_datas(api_id, request_data_config.get_api_id_num())
log.info("使用api_id获取rquest_data的request_datas:" + str(request_datas))
return request_datas
def get_rquest_data_by_data_id(self, data_id, sheet_name):
log.info("使用data_id获取rquest_data的参数:data_id:%s,sheet_name:%s:" % (data_id, sheet_name))
oe = OperationExcel(self.request_data_path, sheet_name)
request_datas = oe.get_row_datas(data_id, request_data_config.get_data_id_num())
log.info("使用data_id获取rquest_data的request_datas:" + str(request_datas))
return request_datas
def get_api_data_by_id(self, api_id, sheet_name):
log.info("使用api_id获取api_data的参数:api_id:%s,sheet_name:%s:" % (api_id, sheet_name))
oe = OperationExcel(self.api_path, sheet_name)
# print(api_id, api_config.get_api_id_num())
datas = oe.get_row_datas(api_id, api_config.get_api_id_num())
# print("通过api_id获取的api_data:", datas)
log.info("通过api_id获取的api_data:%s" % str(datas))
api_datas = []
if datas:
for data in datas:
api_id = data[api_config.get_api_id_num()]
if api_id:
api_data = api_config.ApiData(data)
api_datas.append(api_data)
log.info("使用api_id获取rquest_data的request_datas:" + str(api_datas))
return api_datas
def get_request_apis(self, sheet_name: str) -> list:
log.info("使用sheet_name获取request_apis的参数:sheet_name:%s:" % sheet_name)
request_apis = []
api_datas = self.get_api_datas(sheet_name)
for api_data in api_datas:
api_id = api_data.api_id
api_name = api_data.api_name
api_method = api_data.api_method
api_uri = api_data.api_uri
api_header = api_data.api_header
api_params = api_data.api_params
api_body = api_data.api_body
api_depend = api_data.api_depend
api_is_run = api_data.api_is_run
api_except = api_data.api_except
request_datas = self.get_rquest_data_by_api_id(api_id, sheet_name)
if request_datas:
for request_data in request_datas:
# data_id = request_data[request_data_config.get_data_id_num()]
data_name = request_data[request_data_config.get_data_name_num()]
data_params = request_data[request_data_config.get_data_params_num()]
data_body = request_data[request_data_config.get_data_body_num()]
data_except = request_data[request_data_config.get_data_except_num()]
request_api_list = [api_id, data_name, api_method, api_uri, api_header, data_params, data_body,
api_depend, api_is_run, data_except, self.api_path,
self.request_data_path, sheet_name]
log.info("用于创建RequestApi的request_api_list:%s" % str(request_api_list))
request_api = RequestApi(request_api_list)
request_apis.append(request_api)
else:
request_api_list = [api_id, api_name, api_method, api_uri, api_header, api_params, api_body,
api_depend, api_is_run, api_except,
self.api_path, self.request_data_path, sheet_name]
log.info("用于创建RequestApi的request_api_list:%s" % str(request_api_list))
request_api = RequestApi(request_api_list)
request_apis.append(request_api)
return request_apis
def get_request_apis_by_id(self, api_id, sheet_name, request_data_id=None) -> list:
log.info("使用api_id,sheet_name获取request_apis的参数:sheet_name:%s,api_id:%s"
" request_data_id: %s" % (sheet_name, api_id, str(request_data_id)))
request_apis = []
api_datas = self.get_api_data_by_id(api_id, sheet_name)
for api_data in api_datas:
api_id = api_data.api_id
api_name = api_data.api_name
api_method = api_data.api_method
api_uri = api_data.api_uri
api_header = api_data.api_header
api_params = api_data.api_params
api_body = api_data.api_body
api_depend = api_data.api_depend
api_is_run = api_data.api_is_run
api_except = api_data.api_except
if request_data_id:
request_datas = self.get_rquest_data_by_data_id(request_data_id, sheet_name)
else:
request_datas = self.get_rquest_data_by_api_id(api_id, sheet_name)
if request_datas:
for request_data in request_datas:
# data_id = request_data[request_data_config.get_data_id_num()]
data_name = request_data[request_data_config.get_data_name_num()]
data_params = request_data[request_data_config.get_data_params_num()]
data_body = request_data[request_data_config.get_data_body_num()]
data_except = request_data[request_data_config.get_data_except_num()]
request_api_list = [api_id, data_name, api_method, api_uri, api_header, data_params, data_body,
api_depend, api_is_run, data_except, self.api_path,
self.request_data_path, sheet_name]
log.info("用于创建RequestApi的request_api_list:%s" % str(request_api_list))
request_api = RequestApi(request_api_list)
request_apis.append(request_api)
else:
request_api_list = [api_id, api_name, api_method, api_uri, api_header, api_params, api_body,
api_depend, api_is_run, api_except, self.api_path,
self.request_data_path, sheet_name]
log.info("用于创建RequestApi的request_api_list:%s" % str(request_api_list))
request_api = RequestApi(request_api_list)
request_apis.append(request_api)
return request_apis
if __name__ == "__main__":
pass
gep = GetExcelData("../data/api/jky_api.xlsx", "../data/request_data/jky_request_data.xlsx")
print(gep.get_api_data_by_id("jky-2", "login"))
# print(vars(gep.get_api_datas("login")[0]))
# print(gep.get_request_datas("login"))
# request_apis = gep.get_request_apis("login")
# request_apis = gep.get_request_apis_by_api_id("jky-4", "login")
# for request_api in request_apis:
# print(vars(request_api))
# coding:utf-8
from common import operation_conf
from base import get_excel_data
from common.operation_log import Log
log = Log(__name__).get_logger()
class GetRequestApiSuite:
def __init__(self, path_config_path):
self.path_config_path = path_config_path
self.test_sys = []
self.test_modules = []
def get_request_api_suites(self):
request_api_suites = []
request_api_suite_paths = self.get_api_data_path()
for request_api_suite_path in request_api_suite_paths:
api_data_path = request_api_suite_path["api_data_path"]
sheet_names = request_api_suite_path["sheet_name"].split(",")
request_data_path = request_api_suite_path["request_data_path"]
get_data = get_excel_data.GetExcelData(api_data_path, request_data_path )
for sheet_name in sheet_names:
request_apis = get_data.get_request_apis(sheet_name)
if request_apis:
request_api_suite = RequestApiSuite(request_apis, sheet_name, api_data_path, request_data_path)
request_api_suites.append(request_api_suite)
return request_api_suites
def get_api_data_path(self):
request_api_suite_paths = []
suites = operation_conf.get_sections(self.path_config_path)
self.test_sys =suites
for suite in suites:
request_api_suite_path = {}
api_data_path = operation_conf.read_conf(suite, "api_data_path", self.path_config_path)
sheet_name = operation_conf.read_conf(suite, "sheet_name", self.path_config_path).strip()
self.test_modules.append(sheet_name)
request_data_path = operation_conf.read_conf(suite, "request_data_path", self.path_config_path)
if api_data_path and sheet_name and request_data_path:
request_api_suite_path["api_data_path"] = api_data_path
request_api_suite_path["sheet_name"] = sheet_name
request_api_suite_path["request_data_path"] = request_data_path
request_api_suite_paths.append(request_api_suite_path)
else:
print("api_data_path或sheet_name或request_data_path不存在", api_data_path, sheet_name, request_data_path)
return request_api_suite_paths
def get_test_sys_module(self):
test_sys_module = (",".join(self.test_sys), ",".join(self.test_modules))
return test_sys_module
class RequestApiSuite:
def __init__(self, request_apis, sheet_name, api_data_path, request_data_path):
self.request_apis = request_apis
self.sheet_name = sheet_name
self.api_data_path = api_data_path
self.request_data_path = request_data_path
if __name__ == "__main__":
grs = GetRequestApiSuite("../data/config/data_path.conf")
suites = grs.get_request_api_suites()
for grs in suites:
print(vars(grs))
# coding:utf-8
from common.operation_log import Log
log = Log(__name__).get_logger()
class ReportIndex:
request_name_num = 0
run_method_num = 1
uri_num = 2
header_num = 3
params_num = 4
body_num = 5
depend_id_fields_num = 6
except_result_num = 7
run_result_num = 8
real_response_num = 9
class ReportData:
def __init__(self, api_data, run_result, real_response):
self.name = api_data.name
self.request_method = api_data.request_method
self.uri = api_data.uri
self.header = api_data.header
self.params = api_data.params
self.body = api_data.body
self.api_depends = api_data.depend_api
self.except_value = api_data.request_except
self.run_result = run_result
self.real_response = real_response
# 获取uri
def get_uri():
return ReportIndex.uri_num
def get_run_method():
return ReportIndex.run_method_num
def get_header():
return ReportIndex.header_num
def get_api_depends():
return ReportIndex.depend_id_fields_num
def get_request_name():
return ReportIndex.request_name_num
def get_expect():
return ReportIndex.except_result_num
def get_body():
return ReportIndex.body_num
def get_params():
return ReportIndex.params_num
def get_run_result():
return ReportIndex.run_result_num
def get_real_response():
return ReportIndex.real_response_num
# coding:utf-8
from common.operation_log import Log
log = Log(__name__).get_logger()
class RequestApi:
def __init__(self, data: list):
self.id = data[0]
self.name = data[1]
self.request_method = data[2]
self.uri = data[3]
self.header = data[4]
self.params = data[5]
self.body = data[6]
self.depend_api = data[7]
self.is_run = data[8]
self.request_except = data[9]
self.api_path = data[10]
self.data_path = data[11]
self.sheet_name = data[12]
# coding = utf-8
from common.operation_log import Log
log = Log(__name__).get_logger()
class RequestDataIndex:
data_id_num = 0
api_id_num = 1
data_name_num = 2
data_params_num = 3
data_body_num = 4
data_except_num = 5
class RequestData:
def __init__(self, request_data: list):
self.data_id = request_data[get_data_id_num()].strip()
self.api_id = request_data[get_api_id_num()].strip()
self.data_name = request_data[get_data_name_num()]
self.data_params = request_data[get_data_params_num()].strip()
self.data_body = request_data[get_data_body_num()].strip()
self.data_except = request_data[get_data_except_num()].strip()
def get_data_id_num():
return RequestDataIndex.data_id_num
def get_api_id_num():
return RequestDataIndex.api_id_num
def get_data_name_num():
return RequestDataIndex.data_name_num
def get_data_params_num():
return RequestDataIndex.data_params_num
def get_data_body_num():
return RequestDataIndex.data_body_num
def get_data_except_num():
return RequestDataIndex.data_except_num
# coding:utf-8
import string
import time
from common import operation_conf
from common.operation_log import Log
log = Log(__name__).get_logger()
def replace_string(template_str: str, variable_dict: dict):
template = string.Template(template_str)
return template.safe_substitute(**variable_dict)
def get_host(config_path) -> str:
host = operation_conf.read_conf("host", "host", config_path)
if host == "geek.jkwljy.com":
base_url = "https://" + host
else:
base_url = "http://" + host
return base_url
def get_report_path(config_path):
report_path = operation_conf.read_conf("path", "report_path", config_path)
if report_path:
return report_path
else:
return "./"
def get_log_path(config_path):
log_path = operation_conf.read_conf("path", "log_path", config_path)
if log_path:
return log_path
else:
return "./"
def result_calculate(pass_num, fail_num, exception_num):
pass_num = float(pass_num)
fail_num = float(fail_num)
exception_num = float(exception_num)
count_num = pass_num + fail_num + exception_num
# 90%
pass_rate = "%.2f%%" % (pass_num / count_num * 100)
fail_rate = "%.2f%%" % (fail_num / count_num * 100)
rate = (pass_rate, fail_rate)
return rate
def get_time_name() -> list:
names = []
dname = time.strftime("%Y_%m_%d", time.localtime())
names.append(dname)
sname = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
names.append(sname)
return names
def get_time_diff(start, end):
diff = str((end-start).seconds) + "s"
return diff
# coding=utf-8
import psycopg2
from common import operation_conf
from common.operation_log import Log
log = Log(__name__).get_logger()
class OperationDb:
def __init__(self, config_path):
self.database_name = operation_conf.read_conf("postgreSql", "database", config_path)
self.database_user = operation_conf.read_conf("postgreSql", "user", config_path)
self.database_password = operation_conf.read_conf("postgreSql", "password", config_path)
self.database_host = operation_conf.read_conf("postgreSql", "host", config_path)
self.database_port = operation_conf.read_conf("postgreSql", "port", config_path)
def query_sql(self, sql_str):
# 创建连接对象
conn = psycopg2.connect(database=self.database_name, user=self.database_user, password=self.database_password,
host=self.database_host, port=self.database_port)
cur = conn.cursor() # 创建指针对象
try:
cur.execute(sql_str)
results = cur.fetchall()
finally:
conn.commit()
cur.close()
conn.close()
print('查询结束')
return results
if __name__ == "__main__":
sql = """select student_id,student_name from service_profile.student limit 10"""
opd = OperationDb("../data/config/config.conf").query_sql(sql)
print(opd)
import json
import xlwt
def get_datas(file_name):
datas = []
with open(file_name, "r", encoding="utf-8") as fp:
data = json.load(fp)
apis = data["teststeps"]
for api in apis:
data = []
uri = api["name"]
request = api["request"]
method = request["method"]
try:
body = request["json"]
except KeyError as e:
print(e)
body = ""
try:
params = request["params"]
except KeyError as e:
params = ""
print(e)
data.append(method)
data.append(uri)
data.append(params)
data.append(body)
datas.append(data)
return datas
def to_excel(file_name, sheet_name=None):
datas = get_datas("C:/Users/MI2019/Desktop/test.json")
wt = xlwt.Workbook(encoding="utf-8")
if sheet_name is None:
sheet_name = "api"
sheet = wt.add_sheet(sheet_name)
sheet.write(0, 2, "method")
sheet.write(0, 3, "uri")
sheet.col(3).width = 256 * 50
sheet.write(0, 5, "params")
sheet.col(5).width = 256 * 50
sheet.write(0, 6, "body")
sheet.col(6).width = 256 * 100
row_num = 1
for data in datas:
method, uri, params, body = data
sheet.write(row_num, 2, method)
sheet.write(row_num, 3, uri)
sheet.write(row_num, 5, str(params))
sheet.write(row_num, 6, str(body))
row_num += 1
wt.save(file_name)
if __name__ == "__main__":
to_excel("C:/Users/MI2019/Desktop/test.xls")
# coding=utf-8
import configparser
from common.operation_log import Log
log = Log(__name__).get_logger()
def add_option_value(section, option, value, config_path):
config = configparser.ConfigParser()
config.read(config_path, encoding="utf-8")
if not config.has_section(section): # 检查是否存在section
config.add_section(section)
if not config.has_option(section, option): # 检查是否存在该option
config.set(section, option, value)
config.write(open(config_path, "w"))
# 读取配置文件指定值
def read_conf(section, option, config_path):
value = ""
cf = configparser.ConfigParser()
cf.read(config_path, encoding="utf-8")
if cf.has_option(section, option):
value = cf.get(section, option)
else:
print("section或option不存在:", section+" "+option)
return value
# 更新配置文件指定值
def update_conf(section, option, value, config_path):
cf = configparser.ConfigParser()
cf.read(config_path, encoding="utf-8")
if cf.has_option(section, option):
cf.set(section, option, value)
cf.write(open(config_path, "w"))
else:
add_option_value(section, option, value, config_path)
def get_sections(config_path):
cf = configparser.ConfigParser()
cf.read(config_path, encoding="utf-8")
sections = cf.sections()
return sections
def get_section_options(section, config_path):
config = configparser.ConfigParser()
config.read(config_path, encoding="utf-8")
if config.has_section(section):
options = config.options(section)
else:
options = []
return options
def get_get_section_items(section, config_path):
config = configparser.ConfigParser()
config.read(config_path, encoding="utf-8")
if config.has_section(section):
items = config.items(section)
else:
items = []
return items
# coding:utf-8
import xlrd
import xlwt
from xlutils.copy import copy
from base import report_config as rc
import os
from common.operation_log import Log
log = Log(__name__).get_logger()
class OperationExcel:
def __init__(self, file_name, sheet_name):
if file_name:
self.file_name = file_name
self.sheet_name = sheet_name
else:
print("excel的路径和sheetname不能为空", file_name, sheet_name)
# 获取sheets的内容
def get_sheet(self):
data = xlrd.open_workbook(self.file_name, encoding_override="utf-8")
tables = data.sheet_by_name(self.sheet_name)
return tables
# 获取单元格的行数
def get_lines(self):
tables = self.get_sheet()
return tables.nrows
# 获取某一个单元格的内容
def get_cell_value(self, row, col):
return self.get_sheet().cell_value(row, col)
# 根据data,列号,找到找到对应行的内容
def get_row_datas(self, data, col_id):
row_nums = self.get_row_num(data, col_id)
rows_datas = self.get_row_values(row_nums)
return rows_datas
# 根据对应的1个内容找到对应的行号
def get_row_num(self, data, col_id):
nums = []
num = 0
cols_data = self.get_cols_data(col_id)
for col_data in cols_data:
if data == col_data:
nums.append(num)
num = num + 1
return nums
# 根据行号,找到该行的内容
def get_row_values(self, row_nums):
tables = self.get_sheet()
row_datas = []
for num in row_nums:
row_data = tables.row_values(num)
row_datas.append(row_data)
return row_datas
# 获取某一列的内容
def get_cols_data(self, col_id):
if col_id:
cols = self.get_sheet().col_values(col_id)
else:
cols = self.get_sheet().col_values(0)
return cols
# 写入数据
def write_value(self, row, report):
'''
写入excel数据
row,col,value
'''
if not os.path.exists(self.file_name):
self.new_excel()
read_data = xlrd.open_workbook(self.file_name, formatting_info=True, encoding_override="utf-8")
write_data = copy(read_data)
sheet_data = write_data.get_sheet(self.sheet_name)
# alignment = xlwt.Alignment()
# alignment.wrap = 1
font = xlwt.Font()
if report.run_result == "失败":
font.colour_index = 2
else:
font.colour_index = 8
borders = xlwt.Borders()
borders.left = 1
borders.right = 1
borders.top = 1
borders.bottom = 1
style = xlwt.XFStyle()
# style.alignment = alignment
style.borders = borders
style.font = font
sheet_data.write(row, rc.get_request_name(), report.name, style)
sheet_data.write(row, rc.get_uri(), report.uri, style)
sheet_data.write(row, rc.get_run_method(), report.request_method, style)
sheet_data.write(row, rc.get_header(), str(report.header), style)
sheet_data.write(row, rc.get_params(), report.params, style)
sheet_data.write(row, rc.get_body(), report.body, style)
sheet_data.write(row, rc.get_api_depends(), report.api_depends, style)
sheet_data.write(row, rc.get_expect(), report.except_value, style)
sheet_data.write(row, rc.get_run_result(), report.run_result, style)
sheet_data.write(row, rc.get_real_response(), str(report.real_response)[:32766], style)
write_data.save(self.file_name)
def new_excel(self):
wt = xlwt.Workbook(encoding="utf-8")
if self.sheet_name is None:
self.sheet_name = "test_report"
sheet = wt.add_sheet(self.sheet_name)
font = xlwt.Font()
font.height = 20 * 18
font.bold = True
alignment = xlwt.Alignment()
# 0x01(左端对齐)、0x02(水平方向上居中对齐)、0x03(右端对齐)
alignment.horz = 0x02
# 0x00(上端对齐)、 0x01(垂直方向上居中对齐)、0x02(底端对齐)
alignment.vert = 0x01
borders = xlwt.Borders()
borders.left = 1
borders.right = 1
borders.top = 1
borders.bottom = 1
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = 44
style = xlwt.XFStyle()
style.font = font
style.borders = borders
style.pattern = pattern
sheet.write(0, 0, "name", style)
sheet.col(0).width = 256 * 50
sheet.write(0, 1, "method", style)
sheet.write(0, 2, "uri", style)
sheet.col(2).width = 256 * 50
sheet.write(0, 3, "header", style)
sheet.col(3).width = 256 * 50
sheet.write(0, 4, "params", style)
sheet.col(4).width = 256 * 50
sheet.write(0, 5, "body", style)
sheet.col(5).width = 256 * 50
sheet.write(0, 6, "depend_id_fields", style)
sheet.col(6).width = 256 * 50
sheet.write(0, 7, "except_result", style)
sheet.col(7).width = 256 * 50
sheet.write(0, 8, "run_result", style)
sheet.write(0, 9, "real_response", style)
sheet.col(9).width = 256 * 255
wt.save(self.file_name)
if __name__ == '__main__':
pass
# opers = OperationExcel()
# print(opers.get_cell_value(1, 2))
# coding = utf-8
from common import operation_conf
import json
from common.operation_log import Log
log = Log(__name__).get_logger()
class OperationHeader:
def __init__(self, section, config_path):
self.config_path = config_path
self.section = section
def get_headers(self):
headers = {}
items = operation_conf.get_get_section_items(self.section, self.config_path)
if items:
for item in items:
name = item[0]
value = json.loads(item[1])
headers[name] = value
return headers
def set_headers(self, token: str):
headers_keys = operation_conf.get_section_options(self.section, self.config_path)
if headers_keys:
for headers_key in headers_keys:
option_value = operation_conf.read_conf(self.section, headers_key, self.config_path)
option_dict_value = json.loads(option_value)
if "Authorization" in option_dict_value.keys():
token = "Bearer " + token
option_dict_value["Authorization"] = token
operation_conf.update_conf(self.section, headers_key, json.dumps(option_dict_value), self.config_path)
if __name__ == "__main__":
oh = OperationHeader("headers", "../data/config/config.conf")
headers = oh.get_headers()
print(type(headers["header1"]))
print(headers["header2"])
print(headers["header3"])
# oh.set_headers("12345899988455")
# coding:utf-8
import json
import jsonpath
from common.operation_log import Log
log = Log(__name__).get_logger()
class OperetionJson:
# 读取json文件
def read_data(self, file_path):
with open(file_path, "r", encoding="utf-8") as fp:
data = json.load(fp)
log.info()
return data
# 根据关键字获取数据
def get_data(self, id, data):
print(type(data))
return data[id]
# 写json
def write_data(self, file_path, data):
with open(file_path, 'w', encoding="utf-8") as fp:
fp.write(json.dumps(data))
if __name__ == '__main__':
opj = OperetionJson()
json_string = opj.read_data("test_json.json")
print(jsonpath.jsonpath(json_string, "$.data.content[0,1,2].courseIds"))
# coding=utf-8
import logging
import time
import os
class Log(object):
"""封装后的logging"""
def __init__(self, logger=None):
"""
指定保存日志的文件路径,日志级别,以及调用文件
将日志存入到指定的文件中
"""
# 创建一个logger
self.logger = logging.getLogger(logger)
self.logger.setLevel(logging.DEBUG)
# 创建一个handler,用于写入日志文件
self.log_time = time.strftime("%Y_%m_%d")
file_dir = os.getcwd() + '/data/log/'
if not os.path.exists(file_dir):
os.mkdir(file_dir)
self.log_path = file_dir
self.log_name = self.log_path + self.log_time + '_interface_test.log'
# print(self.log_name)
# fh = logging.FileHandler(self.log_name, 'a') # 追加模式 这个是python2的
fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8') # 这个是python3的
fh.setLevel(logging.INFO)
# 再创建一个handler,用于输出到控制台
# ch = logging.StreamHandler()
# ch.setLevel(logging.INFO)
# 定义handler的输出格式
formatter = logging.Formatter(
'[%(asctime)s] %(filename)s->%(funcName)s line:%(lineno)d [%(levelname)s] %(message)s')
fh.setFormatter(formatter)
# ch.setFormatter(formatter)
# 给logger添加handler
self.logger.addHandler(fh)
# self.logger.addHandler(ch)
# 添加下面一句,在记录日志之后移除句柄
# self.logger.removeHandler(ch)
# self.logger.removeHandler(fh)
# 关闭打开的文件
fh.close()
# ch.close()
def get_logger(self):
return self.logger
# coding=utf-8
from dingtalkchatbot import chatbot
from common import operation_conf
from common import common_util
from common.operation_log import Log
log = Log(__name__).get_logger()
class SendDingDindMsg:
def __init__(self, web_hook, msg):
self.web_hook = web_hook
self.msg = msg
def send_dingding_message(self, message_type="text", is_at_all=False, at_mobiles=None):
result = None
ding_robot = chatbot.DingtalkChatbot(self.web_hook)
if message_type == "text":
if isinstance(self.msg, str):
result = ding_robot.send_text(msg=self.msg, is_at_all=is_at_all, at_mobiles=at_mobiles)
elif message_type == "link":
# msg={title="测试标题",text="this is 内容",message_url="http://132.232.15.12/jky/#/personnel/employeeinfo"}
if isinstance(self.msg, dict):
result = ding_robot.send_link(**self.msg)
else:
print("msg数据类型错误")
elif message_type == "markdown":
# msg={title="测试标题",text="this is 内容"}
if isinstance(self.msg, dict):
title = self.msg['title']
text = self.msg['text']
result = ding_robot.send_markdown(title=title, text=text, is_at_all=is_at_all, at_mobiles=at_mobiles)
else:
print("msg数据类型错误")
elif message_type == "send_feed_card":
if isinstance(self.msg, list):
links = []
# title = "测试feedcard",message_url = "http://132.232.15.12/jky/#/personnel/employeeinfo",\
# pic_url="http://pic18.nipic.com/20120103/8993051_170340691334_2.jpg"
for m in self.msg:
if isinstance(m, dict):
link = chatbot.FeedLink(**m)
links.append(link)
else:
print("msg中有类型错误")
if links:
result = ding_robot.send_feed_card(links=links)
else:
print("msg数据类型错误")
elif message_type == "ActionCard":
if isinstance(self.msg, dict):
action_card = chatbot.ActionCard(**self.msg)
result = ding_robot.send_action_card(action_card)
else:
print("msg数据类型错误")
else:
print("msg_type错误")
return result
def get_markdown_template() -> str:
markdown_template = """
接口测试概要(${host})
测试系统:${test_sys}
测试模块;${test_modules}
整体结果: ${result_all}
测试开始时间:${start_time}
测试结束时间:${end_time}
持续时间:${duration}
测试接口总数:${total}
成功:${success_num} || 失败:${fail_num} || 异常:${exception_num}
测试成功率:${success_rate}
测试失败率:${fail_rate}
"""
return markdown_template
def send_result_message(summary: dict, config_path):
result = summary["result"]
result_all = summary["result_all"]
time = summary["time"]
host = operation_conf.read_conf("host", "host", config_path)
messagedata = {
"host": host,
"result_all": result_all,
"total": result["total"],
"success_num": result["success_num"],
"fail_num": result["fail_num"],
"exception_num": result["exception_num"],
"success_rate": result["success_rate"],
"fail_rate": result["fail_rate"],
"start_time": time["start_time"],
"end_time": time["end_time"],
"duration": (str(time["duration"])),
"test_sys": summary["test_sys"],
"test_modules": summary["test_modules"]
}
markdown_template = get_markdown_template()
markdown = common_util.replace_string(markdown_template, messagedata)
web_hook = operation_conf.read_conf("ding_ding_url", "web_hook", config_path)
log.info("发送邮箱的web_hook: %s" % web_hook)
msg = {
"title": "接口测试概况",
"text": markdown
}
log.info("发送邮箱的msg: %s" % str(msg))
sddm = SendDingDindMsg(web_hook, msg)
sddm.send_dingding_message(message_type="markdown")
# coding=utf-8
import smtplib
from common import operation_conf
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from common import common_util
from common.operation_log import Log
log = Log(__name__).get_logger()
class SendEmail:
def __init__(self, config_path):
log.info("init对象send_email的参数config_path:%s" % config_path)
self.__get_email_conf(config_path)
self.smt_obj = smtplib.SMTP_SSL(self.host, self.port)
def __get_email_conf(self, config_path):
self.host = operation_conf.read_conf("email", "host", config_path)
self.port = operation_conf.read_conf("email", "port", config_path)
self.from_adress = operation_conf.read_conf("email", "from_adress", config_path)
self.password = operation_conf.read_conf("email", "password", config_path)
self.to_adresses = operation_conf.read_conf("email", "to_adresses", config_path).split(",")
log.info("获取的email配置:host:%s,port:%s,from_adress:%s" % (self.host, self.port, str(self.from_adress)))
log.info("获取的email配置:password:%s,to_adresses:%s" % (self.password, str(self.to_adresses)))
def send_email(self, subject, text, html_msg=None, attachments=None):
log.info("发送邮件时传入的参数suject: %s,text:%s, attachments:%s" % (subject, text, str(attachments)))
message = MIMEMultipart()
# 发件人邮箱账号
message['From'] = self.from_adress
# 收件人邮箱账号
message['To'] = ";".join(self.to_adresses)
message['Subject'] = subject
message.attach(MIMEText(text, 'plain', 'utf-8'))
if html_msg:
message.attach(MIMEText(html_msg, 'html', 'utf-8'))
# 构造附件1,传送当前目录下的 test.txt 文件
if isinstance(attachments, list) and attachments:
for attachment in attachments:
att = MIMEText(open(attachment, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att["Content-Disposition"] = 'attachment; filename="%s"' % attachment
message.attach(att)
try:
self.smt_obj.login(self.from_adress, self.password)
self.smt_obj.sendmail(self.from_adress, self.to_adresses, message.as_string())
log.info("邮件发送成功")
self.smt_obj.quit()
except smtplib.SMTPException as e:
log.info("Error: 邮件发送失败%s" % e)
self.smt_obj.quit()
def send_test_result_email(report_path, config_path):
log.info("发送测试结果邮件参数:report_path:%s, config_path:%s" % (report_path, config_path))
subject = common_util.get_time_name()[1] + "接口测试报告"
attachments = []
attachments.append(report_path)
send_email = SendEmail(config_path)
send_email.send_email(subject, "详情请下载查看附件", attachments=attachments)
if __name__ == "__main__":
send_email = SendEmail("../data/config/config.conf")
send_email.send_email("测试邮件", "测试内容")
# coding:utf-8
import json
import operator
import jsonpath
from common.operation_log import Log
log = Log(__name__).get_logger()
def is_contain(str_one, str_two):
"""
判断一个字符串是否再另外一个字符串中
str_one:查找的字符串
str_two:被查找的字符串
"""
if isinstance(str_one, str):
str_one = str(str_one)
return operator.le(str_one, str_two)
def is_equal_dict(dict_one, dict_two):
"""判断两个字典是否相等"""
if isinstance(dict_one, str):
dict_one = json.loads(dict_one)
if isinstance(dict_two, str):
dict_two = json.loads(dict_two)
return operator.eq(dict_one, dict_two)
def res_verify(except_datas, res):
log.info("校验期望结果的参数:except_datas:%s, res:%s" % (except_datas, res))
flag = False
if except_datas:
except_datas = except_datas.split()
for except_data in except_datas:
if except_data:
try:
except_list = except_data.split(":")
# print(except_list)
if len(except_list) == 2:
real_path, except_value = except_list
real_value = jsonpath.jsonpath(res, real_path)
if real_value:
print("期望值:%s,实际值:%s" % (except_value, str(real_value[0])))
log.info("期望值:%s,实际值:%s" % (except_value, str(real_value[0])))
flag = operator.eq(str(real_value[0]), except_value)
else:
flag = False
elif len(except_list) == 3:
real_path, except_value, assert_method = except_list
real_value = jsonpath.jsonpath(res, real_path)
# print(type(real_value))
# print(real_value)
if real_value:
# print("期望值:%s,实际值:%s" % (except_value, str(real_value)))
log.info("期望值:%s,实际值:%s" % (except_value, str(real_value)))
if assert_method.strip() == "contain":
# print(real_value)
flag = True if except_value in str(real_value) else False
elif assert_method.strip() == "not_contain":
flag = False if except_value in str(real_value) else True
else:
flag = operator.eq(str(real_value[0]), except_value)
else:
flag = False
else:
print("期望值得格式有误,请检查")
flag = False
except ValueError:
flag = False
print("期望值得格式有误,请检查", ValueError)
if not flag:
break
else:
print("未填写期望值")
flag = True
return flag
[host]
host = 132.232.15.12
[ding_ding_url]
web_hook = https://oapi.dingtalk.com/robot/send?access_token=94b76afb5b538437e9986e95bd9e4c882cfcf3c75e8c1b3a6f209cac403b8e00
[universal_password]
is_init = Y
universal_password = A0S78dcd4866-f5c
[login_conf]
uri = /service-user/app/auth
body = {"account":"15360956010","password":"123456","type":"customer"}
params =
[path]
report_path = data/report/jky_report.xls
[email]
host = smtp.exmail.qq.com
port = 465
from_adress = puxiaojian@jiuaoedu.com
password = Xj15208176554
to_adresses = puxiaojian6554@dingtalk.com
[postgreSql]
database = edu-admin
user = dev
password = mko0PL<.;?
host = 192.168.32.41
port = 5432"
[headers]
header1 = {"Content-Type": "application/json;charset=UTF-8","Accept": "application/json, text/plain, */*"}
header2 = {"Content-Type": "application/json;charset=UTF-8", "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIyMjg1ODciLCJ0ZXJtaW5hbCI6ImFwcCIsInV1aWQiOiI2YmZhMmFkZDExMmY0ZmNjYmQyZjA2MDE2MzhhMzJlOCIsInRpbWVzdGFtcCI6MTU4MzgyNzk3NjE5MX0.SjLr-owF_ceCUQJYOdWNPtINgB8j8C5tvnSbzAjFYi8"}
header3 = {"Accept": "application/json, text/plain, */*"}
header4 = {"Content-Type": "application/x-www-form-urlencoded","Accept": "application/json, text/plain, */*"}
[geekApp]
api_data_path = data/api/jky_api.xlsx
#sheet_name = login,teach_manage,apply,financial_manage,system_setting,statistics_report
sheet_name = login
request_data_path = data/request_data/jky_request_data.xlsx
This source diff could not be displayed because it is too large. You can view the blob instead.
No preview for this file type
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment