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

家长APP切换新框架

parent ab617218
# 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
# coding: utf-8
run_setting = {
"host": "geek.jkwljy.com",
# [ding_ding_url]
"web_hook": "https://oapi.dingtalk.com/robot/send?access_token=94b76afb5b538437e9986e95bd9e4c882cfcf3c75e8c1b3a6f209cac403b8e00BBBBB",
"report_path": "data/report/jky_report.xls",
"email": {
"host": "smtp.exmail.qq.com",
"port": 465,
"from_adress": "puxiaojian@jiuaoedu.com",
"password": "Xj15208176554",
"to_adresses": ["mzx6010@dingtalk.com","puxiaojian6554@dingtalk.com"]
},
"postgreSql": {
"database": "edu-admin",
"user": "dev",
"password": "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 ${app_token}"}""",
"header3": """{"Accept": "application/json, text/plain, */*"}""",
"header4": """{"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json, text/plain, */*"}"""
},
"excel_setting": {
"sys_name": "JKSXBAPP",
"module_name": "登录、选课报名、我的、消息、购课单",
"api_data_path": "data/api/jky_api.xlsx",
"request_data_path": "data/request_data/jky_request_data.xlsx",
"sheet_name": ["login", "buy_class", "my", "notice", "purchaseOrder"]
#"sheet_name": ["login", "notice"]
},
"global_variable": {
"global_school_area_id": 3015,
"student_id": "5878455"
}
}
No preview for this file type
[host]
host = geek.jkwljy.com
[ding_ding_url]
web_hook = https://oapi.dingtalk.com/robot/send?access_token=94b76afb5b538437e9986e95bd9e4c882cfcf3c75e8c1b3a6f209cac403b8e00BBBBB
[universal_password]
is_init = Y
universal_password = A0S711e344d7-36e
[login_conf]
uri = /service-user/app/auth
body = {"account":"16688888888","password":"88888888","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.eyJ1aWQiOiIzMTE2ODEiLCJ0ZXJtaW5hbCI6ImFwcCIsInV1aWQiOiIxZjA2ZDE3ZDdmZjA0MjQyYjZhZjdmODBiYzk3Y2MzNyIsInRpbWVzdGFtcCI6MTU5NDM1MDMwMTgzN30.cuy-Z4mcrPwO2c202axQCOV0eSrSAq6jkGe9tu632wc"}
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,homePage,class,buy_class,my,notice,purchaseOrder,homework,learnReport
#sheet_name = login,homePage,learnReport
request_data_path = data/request_data/jky_request_data.xlsx
# coding = utf-8
import requests
import jsonpath
from common.operation_log import Log
from json.decoder import JSONDecodeError
from common import operation_conf
from common import common_util
from urllib3.connectionpool import InsecureRequestWarning
import urllib3
log = Log(__name__).get_logger()
urllib3.disable_warnings(InsecureRequestWarning)
class GetTokenPsd:
def __init__(self, config_path):
self.config_path = config_path
self.header = {
"Content-Type": "application/json;charset=UTF-8"
}
self.host = common_util.get_host(config_path)
self.token = self.get_token()
def get_token(self):
uri = operation_conf.read_conf("login_conf", "uri", self.config_path)
url = self.host + uri
data = operation_conf.read_conf("login_conf", "body", self.config_path)
params = operation_conf.read_conf("login_conf", "params", self.config_path)
if params:
res = requests.post(url=url, data=data, params=params, headers=self.header, verify=False)
else:
res = requests.post(url=url, data=data, headers=self.header, verify=False)
try:
res_j = res.json()
token = jsonpath.jsonpath(res_j, "$.data.token")
if token:
self.header["token"] = "Bearer " + token[0]
return token[0]
else:
print("获取token失败")
except JSONDecodeError as e:
print("json格式错误,token获取失败", e)
def get_universal_password(self):
uri = "/service-user/masterKey/getKey"
url = self.host + uri
data = {"platform": "GuardianAPP"}
response = requests.get(url=url, params=data, headers=self.header, verify=False)
try:
res_j = response.json()
universal_password = res_j["data"]
except JSONDecodeError as e:
print("json格式错误", e)
universal_password = ""
return universal_password
if __name__ == "__main__":
gtp = GetTokenPsd("../data/config/config.conf")
print(gtp.token)
print(gtp.get_universal_password())
# coding = utf-8
from common import operation_header
from main import get_token_password
from common import operation_conf
from common.operation_log import Log
log = Log(__name__).get_logger()
class InitConfig:
def __init__(self, host, config_path):
self.host = host
self.config_path = config_path
self.init_host()
self.gtp = get_token_password.GetTokenPsd(self.config_path)
self.init_header()
is_init_universal_password = operation_conf.read_conf("universal_password", "is_init", self.config_path).strip()
if is_init_universal_password == "Y" or is_init_universal_password == "y":
self.init_universal_password()
def init_header(self):
oh = operation_header.OperationHeader("headers", self.config_path)
oh.set_headers(self.gtp.token)
def init_host(self):
operation_conf.update_conf("host", "host", self.host, self.config_path)
def init_universal_password(self):
universal_password = self.gtp.get_universal_password()
operation_conf.update_conf("universal_password", "universal_password", universal_password, self.config_path)
# coding=utf-8
from base import get_excel_data
from base.get_request_api_suite import GetRequestApiSuite
from base.report_config import ReportData
from base.request_api import RequestApi
from main.run_method import RunMethod
from main import init_conf
import jsonpath
import datetime
import random, os
from common.operation_excel import OperationExcel
from common import common_util, verify_method, send_dingding_message, send_email
from common.operation_header import OperationHeader
from common import operation_conf
from common.operation_log import Log
log = Log(__name__).get_logger()
class Run:
def __init__(self, config_path, path_config_path=None):
log.info("init对象Run的参数config_path:%s, path_config_path;%s" % (config_path, path_config_path))
self.config_path = config_path
self.path_config_path = path_config_path
self.headers = OperationHeader("headers", self.config_path).get_headers()
self.universal_password = operation_conf.read_conf("universal_password", "universal_password", self.config_path).strip()
self.run_method = RunMethod(self.config_path)
self.report_path = common_util.get_report_path(self.config_path)
if os.path.exists(self.report_path):
os.remove(self.report_path)
self.report_excel = OperationExcel(self.report_path, "report")
self.get_request_api_suites = GetRequestApiSuite(self.path_config_path)
self.report_row_num = 1
self.success_num = 0
self.fail_num = 0
self.exception_num = 0
def run(self):
request_api_suites = self.get_request_api_suites.get_request_api_suites()
test_sys_modules = self.get_request_api_suites.get_test_sys_module()
start_time = datetime.datetime.now()
self.run_api_suites(request_api_suites)
end_time = datetime.datetime.now()
summary = self.get_result_summary(start_time, end_time, test_sys_modules)
log.info("用于发送消息的summary: %s" % str(summary))
self.send_result(summary)
def depend_field_add_default(self, fields):
fields["universal_password"] = self.universal_password
random_str = str(random.randint(1000, 10000))
current_date = str(datetime.date.today())
fields["random_str"] = random_str
fields["current_date"] = current_date
return fields
def parse_depend_fields(self, depend_api_fields):
depend_datas = depend_api_fields.split()
depend_ids = set()
depend_list_datas = []
for depend_data in depend_datas:
if depend_data:
try:
depend_list_data = depend_data.split(":")
depend_id = depend_list_data[0]
depend_ids.add(depend_id)
depend_list_datas.append(depend_list_data)
except ValueError:
print("依赖数据格式有误,请检查", ValueError)
data = (depend_ids, depend_list_datas)
return data
def get_depend_fields(self, depend_api_fields: str, request_api: RequestApi) -> dict:
fields = {}
depend_ids, depend_list_datas = self.parse_depend_fields(depend_api_fields)
for depend_id in depend_ids:
if depend_id == request_api.id:
print("依赖的接口id错误,不能与当前执行api的id相同:depend_id:%s,request_api_id:%s" % (depend_id, request_api.id))
log.info("依赖的接口id错误,不能与当前执行api的id相同:depend_id:%s,request_api_id:%s" % (depend_id, request_api.id))
continue
depend_path_vnames = []
request_data_ids = set()
for depend_list_data in depend_list_datas:
if depend_id in depend_list_data:
depend_path = depend_list_data[1]
depend_vname = depend_list_data[2]
if len(depend_list_data) == 4:
request_data_ids.add(depend_list_data[3])
depend_path_vnames.append((depend_path, depend_vname))
if request_data_ids:
request_data_id = request_data_ids.pop()
else:
request_data_id = None
get_data = get_excel_data.GetExcelData(request_api.api_path, request_api.data_path)
depend_request_apis = get_data.get_request_apis_by_id(depend_id, request_api.sheet_name, request_data_id)
if depend_request_apis:
depend_request_api = depend_request_apis[0]
res = self.run_api(depend_request_api, is_depend_api=True)
for depend_path_vname in depend_path_vnames:
field_value = jsonpath.jsonpath(res, depend_path_vname[0])
if field_value:
fields[depend_path_vname[1]] = field_value[0]
return fields
def get_report(self, request_api: RequestApi, res):
request_except = request_api.request_except
log.info("用于测结果校验的参数:request_except:%s, res:%s" % (request_except, res))
result = verify_method.res_verify(request_except, res)
if result:
report = ReportData(request_api, "成功", res)
log.info("测试通过用于写入报告的report_row_num:%s,report:%s" % (str(self.report_row_num), str(vars(report))))
self.report_excel.write_value(self.report_row_num, report)
self.report_row_num += 1
self.success_num += 1
else:
report = ReportData(request_api, "失败", res)
log.info("测试失败用于写入报告的report_row_num:%s,report:%s" % (str(self.report_row_num), str(vars(report))))
self.report_excel.write_value(self.report_row_num, report)
self.report_row_num += 1
self.fail_num += 1
def run_api(self, request_api: RequestApi, is_depend_api=False):
log.info("run_api传入的参数request_api %s,is_depend_api: %s" % (str(vars(request_api)), str(is_depend_api)))
if request_api.is_run == "Y" or is_depend_api:
body_data = request_api.body
depend_api_fields = request_api.depend_api
fields = {}
if depend_api_fields:
fields = self.get_depend_fields(depend_api_fields, request_api)
fields = self.depend_field_add_default(fields)
log.info("生成的fields:%s" % str(fields))
header = request_api.header
if header:
try:
request_api.header = self.headers[header]
except KeyError as e:
print("KeyError", e)
request_api.header = self.headers["header2"]
else:
request_api.header = self.headers["header2"]
uri = request_api.uri
params = request_api.params
if fields:
request_api.uri = common_util.replace_string(uri, fields)
if body_data:
request_api.body = common_util.replace_string(body_data, fields)
if params:
request_api.params = common_util.replace_string(params, fields)
log.info("用于发送请求的request_api数据:%s" % str(vars(request_api)))
res = self.run_method.run_main(request_api)
self.get_report(request_api, res)
return res
def run_apis(self, request_apis: list):
for request_api in request_apis:
self.run_api(request_api)
def run_api_suites(self, request_api_suites):
for request_api_suite in request_api_suites:
request_apis = request_api_suite.request_apis
self.run_apis(request_apis)
def get_result_summary(self, start_time, end_time, test_sys_modules):
summary = {}
duration = common_util.get_time_diff(start_time, end_time)
time = {"start_time": start_time, "end_time": end_time, "duration": duration}
summary["time"] = time
rate = common_util.result_calculate(self.success_num, self.fail_num, self.exception_num)
result = {"total": self.success_num + self.fail_num + self.exception_num,
"success_num": self.success_num,
"fail_num": self.fail_num,
"exception_num": self.exception_num,
"success_rate": rate[0],
"fail_rate": rate[1]
}
summary["result"] = result
result_all = "通过" if self.fail_num == 0 and self.exception_num == 0 else "失败"
summary["result_all"] = result_all
summary["test_sys"] = test_sys_modules[0]
summary["test_modules"] = test_sys_modules[1]
return summary
def send_result(self, summary):
try:
send_dingding_message.send_result_message(summary, self.config_path)
except Exception as e:
log.info("钉钉消息发送异常:%s", e)
try:
send_email.send_test_result_email(self.report_path, self.config_path)
except Exception as e:
log.info("邮件发送异常:%s", e)
if __name__ == "__main__":
config_path = "../data/config/config.conf"
path_config_path = "../data/config/data_path.conf"
init_conf.InitConfig("132.232.15.12", config_path)
Run(config_path, path_config_path).run()
# coding:utf-8
import requests
from json.decoder import JSONDecodeError
from common import common_util
from common.operation_log import Log
from urllib3.connectionpool import InsecureRequestWarning
import urllib3
# import chardet
urllib3.disable_warnings(InsecureRequestWarning)
log = Log(__name__).get_logger()
class RunMethod:
def __init__(self, config_path):
self.base_url = common_util.get_host(config_path)
def run_main(self, api_data):
res_j = None
run_method = api_data.request_method
url = self.base_url + api_data.uri
header = api_data.header
params = api_data.params
if run_method == 'Post' or run_method == 'POST':
body_data = api_data.body
# print("body", type(body_data), body_data)
# code = chardet.detect(body_data.encode())
# print("body", body_data, code["encoding"])
res = requests.post(url, data=body_data.encode(), params=params, headers=header, timeout=60, verify=False)
elif run_method == 'GET' or run_method == 'Get':
res = requests.get(url, params=params, headers=header, verify=False)
elif run_method == 'PUT' or run_method == 'put':
body_data = api_data.body
res = requests.put(url, data=body_data, params=params, headers=header, timeout=60, verify=False)
else:
res = "run_method错误:" + run_method
try:
res_j = res.json()
except JSONDecodeError as e:
res_j = res.text
log.info("请求返回的接口格式错误:%s" % e)
return res_j
if __name__ == "__main__":
r = RunMethod("../data/config/headers.conf")
# coding:utf-8 # coding:utf-8
import sys import sys
import os from hq_framework.main.run_api import Run
cwd_path = os.getcwd() from hq_framework.common.operation_log import Log
env_paths = [cwd_path, cwd_path + r"\main", cwd_path + r"\common", cwd_path + r"\base"] from config import run_setting
for env_path in env_paths:
if env_path not in sys.path:
sys.path.append(env_path)
from main.run_api import Run
from main import init_conf
from common.operation_log import Log
log = Log(__name__).get_logger() log = Log(__name__).get_logger()
class GetSysArgs: def get_host(args: list):
def __init__(self, args: list): log.info("输入的命令行参数args: %s" % repr(args))
if len(args) == 2: return args[1] if len(args) == 2 else "192.168.32.43:3000"
self.ip = args[1]
print(self.ip)
log.info("输入的命令行参数args: %s" % args)
else:
print(args)
self.ip = "132.232.15.12"
log.info("输入的命令行参数args: %s没有ip或参数过多使用: ip: 132.232.15.12" % args)
def get_ip(self):
if self.ip == "geek.jkwljy.com" or self.validate_ip():
return self.ip
else:
log.info("输入的ip:%s有误,使用默认Ip: ip: 132.232.15.12" % self.ip)
return "132.232.15.12"
def validate_ip(self) -> bool:
sep = self.ip.split(':')[0].split(".")
if len(sep) != 4:
return False
for i, x in enumerate(sep):
try:
int_x = int(x)
if int_x < 0 or int_x > 255:
return False
except ValueError:
return False
return True
if __name__ == "__main__": if __name__ == "__main__":
ip = GetSysArgs(sys.argv).get_ip() host = get_host(sys.argv)
print("获取的ip:" + ip) log.info("获取的host:" + host)
log.info("用于初始化config的ip:" + ip) run_setting["host"] = host
config_path = "data/config/config.conf" Run(run_setting).run()
path_config_path = "data/config/data_path.conf"
init_conf.InitConfig(ip, config_path)
Run(config_path, path_config_path).run()
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