接口测试

获取表格内容
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '')))


class GetExcel(object):
"""封装excel读取"""

def __init__(self, tableName, caseName):
self.excel_path = os.path.normpath(
os.path.join(os.path.join(os.path.dirname(os.path.dirname(__file__)), "resources"), "testdata.xls"))
self.table_name = tableName
self.case_name = caseName

def _get_table(self):
excel = xlrd.open_workbook(self.excel_path)
sheet_names = excel.sheet_names()
if self.table_name in sheet_names:
table = excel.sheet_by_name(self.table_name)
return table
else:
logging.error("sheet {} not found in {}".format(self.table_name, self.excel_path))
raise ValueError("sheet {} not found in {}".format(self.table_name, self.excel_path))

def get_content(self):
"""返回一条指定数据"""
table = self._get_table()
line_num = table.nrows
is_found_case = False
result = ""
if line_num < 2:
logging.error("the sheet content is null!")
raise ValueError("the sheet content is null!")
else:
for i in range(1, line_num):
line = table.row_values(i)
if line == "":
pass
elif self.case_name == line[0]:
result = line
logging.debug("find data: {}".format(result))
is_found_case = True
break
if is_found_case:
return result
else:
logging.error("caseName: {} not found!".format(self.case_name))
raise ValueError("caseName: {} not found!".format(self.case_name))


if __name__ == '__main__':
excel_object = GetExcel("ads-sms-send-msg", "sms-send-text")
request_data = excel_object.get_content()[-5].encode("utf-8")
print(request_data)



结果校验
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))


class CheckResult(object):
def __init__(self, result, expect):
self.result = result
self.expect = expect

def _dict_check(self, dictExpect):
for key, value in dictExpect.items():
operator = "=="
expect_value = value
value_type = type(value)
if value_type == tuple:
operator = value[0]
expect_value = value[1]
match_set = extenstep.parse_result(self.result, key)
print json.dumps(match_set[1], ensure_ascii=False)
if not match_set[1]:
self.is_result = False
break
self._operator_check(expect_value, match_set[1], operator)

def _str_check(self, strExpect):
match_set = extenstep.parse_result(self.result, strExpect)
if not match_set[1]:
self.is_result = False

def _operator_check(self, expectValue, resultValues, operatorType):
if type(expectValue) == str: expectValue.decode("utf-8")
if operatorType == "==":
for value in resultValues:
if value != expectValue:
self.is_result = False
break
elif ">" in operatorType or "<" in operatorType:
if ">" in operatorType and "=" in operatorType: expectValue -= 1
if "<" in operatorType and "=" in operatorType: expectValue += 1
for value in resultValues:
if ">" in operatorType and value < expectValue:
self.is_result = False
break
if "<" in operatorType and value > expectValue:
self.is_result = False
break
elif operatorType == "in":
if expectValue not in resultValues:
self.is_result = False
else:
for value in resultValues:
if str(expectValue) not in str(value):
self.is_result = False
break

def check_result(self):
expect_set = []
self.is_result = False
if type(self.expect) != list:
expect_set.append(self.expect)
else:
expect_set.extend(self.expect)
print "实际结果:", json.dumps(self.result, ensure_ascii=False)
checkpoint_num = len(expect_set)
for count, i in enumerate(expect_set):
self.is_result = True
print "检查第{}个期望结果:".format(count + 1), json.dumps(i, ensure_ascii=False)
if type(i) == dict:
self._dict_check(i)
elif type(i) == list:
none = [self._str_check(child_i) for child_i in i]
else:
self._str_check(i)
if self.is_result:
print u"第{}个期望结果: {}".format(count + 1, self.is_result)
break
checkpoint_num -= 1
print u"第{}个期望结果:{} {}.".format(count + 1, self.is_result, u",检查下一个期望结果" if checkpoint_num else "")
assert self.is_result == True
# return self.is_result


if __name__ == '__main__':
result = CheckResult({"a": 1}, {"a": 1})
print(result.check_result())







#封装请求和数据处理



# -*- coding: utf-8 -*-
import functools
import inspect
import json
from collections import namedtuple
from datetime import datetime
from Mytest_Getexcel import GetExcel
import checkResult
import extenstep
import sys
import os
import platform
from common.get_advert_cookie import *

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))

# 使用命名元组,便于理解下标引用含义
col_name = ["caseName", "scheme", "host", "path", "method", "type", "data", "expect", "note", "step", "action"]
col_obj = namedtuple("col", col_name)
col = col_obj(*(i for i in range(len(col_name))))


def excel_data(tableName, caseName):
"""一条excel数据处理"""
global col
excel_obj = GetExcel(tableName, caseName)
data = excel_obj.get_content()
url = (data[col.scheme].lower() + "://" + data[col.host] + data[col.path]).encode("utf-8") # 组装为完整的url
body_type = data[col.type].encode("utf-8") # 获取媒体类型
body = data[col.data].encode("utf-8") # 获取请求参数
print body
expect_str = data[col.expect].encode("utf-8") # 获取期望结果
step = data[col.step].encode("utf-8").strip() != "" # 用例描述
return url, body, expect_str, body_type, step


#
def request_data(tableName, caseName):
"""header与body数据处理"""
url, body, expect_str, body_type, step = excel_data(tableName, caseName)
if step:
body, expect_str = extenstep.update_body(tableName, caseName, body, expect_str) # 请求参数和期望结果进行宏替换处理
# body = body.replace("../materials", "materials")
try:
if 'open(' in body:
body1 = body[body.rfind('open('):]
mater_name = body1[9:body1.find(',') - 1]
if platform.system() == "Windows":
mater_path = os.path.abspath(
os.path.join(os.path.dirname(os.path.dirname(__file__)), mater_name)).replace('\\', '\\\\')
else:
mater_path = os.path.abspath(os.path.join(os.path.dirname(os.path.dirname(__file__)), mater_name))
mater_name2 = body1[6:body1.find(',') - 1]
body = body.replace(mater_name2, mater_path)
exec ("body = " + body) # 转换为字典
except Exception as e:
logging.warning("body: {} exec to dict failed! --- error:{}".format(body, str(e)))
try:
exec ("expect_str = " + expect_str) # 转换为python内置类型
except Exception as e:
pass
header = {}
if 'send-msg' in tableName: # 如果是消息发送相关的就是要 用营销平台鉴权
cookie = get_advert_web_cookie(name='zmm', passwd='123456')

sign = 'JSESSIONID={0};adstk={1};oadsk={2};WEBTOKEN={3}'.format(cookie[0], cookie[1], cookie[2],
cookie[3])

header = {"Content-Type": "application/json", "Cookie": sign}
else: # 不是的话 就默认header
header = {"Content-Type": "application/json"}
# if "auth" in tableName:
# auth = authenticate("1100016110", "999", "2b36b5c92f624af0b557bbce0db5aa65") # 直接使用excel数据无需调整
#
# header = {
# "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
# "Authorization": auth
# }
# elif "cookies" in tableName:
# pass
#
# else:
# header = {
# "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
# }
# if body_type.title() == "Data":
# header["Content-Type"] = "text/plain;charset=UTF-8"
# elif body_type.title() == "Json":
# header["Content-Type"] = "application/json;charset=utf-8"
# body = json.dumps(body, ensure_ascii=False)
# elif body_type.title() == "File":
# header.pop("Content-Type")
return header, body, url, expect_str


step_num = 0
is_step = False


def is_steps(function):
"""判定是否为依赖调用"""

@functools.wraps(function)
def wrapper(*args, **kwargs):
global is_step, step_num
cur_frame = inspect.currentframe()
out_frame = inspect.getouterframes(cur_frame)[1][3] # 获取调用方的名称
# 判断依赖情况,设置is_step值
if out_frame == "steps":
is_step = True
else:
is_step = False
resp, expect, body, header = function(*args, **kwargs)
if out_frame == "steps":
return resp, expect, body
return resp, expect

return wrapper


ignore_status_white_list = ["create_ad_026"]


def check_resp(function):
"""检查响应情况"""

@functools.wraps(function)
def wrapper(*args, **kwargs):
resp, expect, body, header = function(*args, **kwargs)
if resp.status_code != 200 and args[1] not in ignore_status_white_list:
error_info = "服务响应状态码为{}".format(resp.status_code)
raise ValueError(error_info)
try:
resp.json()
except Exception:
error_info = "服务响应媒体类型为{}".format(resp.headers.get("Content-Type"))
raise ValueError(error_info)
return resp.json(), expect, body, header

return wrapper


class PrintInfo(object):
"""打印请求/响应信息"""

def __init__(self, switch=True, level=1):
"""1-依赖简单信息,2-依赖请求/响应请求信息"""
self.switch = switch
self.level = level

def __call__(self, function):
def wrapper(*args, **kwargs):
global is_step, step_num
resp, expect, body, header = function(*args, **kwargs)
is_file = header.get("Content-Type")
# 为文件上传时,请求参数不处理直接打印
body_init = json.dumps(body, ensure_ascii=False) if is_file else body
if is_step and self.switch:
print "依赖__信息: ", args
if self.level == 2:
print "依赖__请求数据: ", body_init
print "依赖__响应: ", resp.content
elif not is_step:
print "请求数据: ", body_init
print "响应: ", resp.content
return resp, expect, body, header

return wrapper


@is_steps
@check_resp
@PrintInfo(switch=True, level=1)
def request_post(tableName, caseName):
"""post请求"""
# proxies = {'http': 'http://localhost:8888', 'https': 'http://localhost:8888'}

header, body, url, expect = request_data(tableName, caseName)
resp = requests.post(url, verify=False, json=body, headers=header)
return resp, expect, body, header


@is_steps
@check_resp
@PrintInfo(switch=True, level=1)
def request_get(tableName, caseName):
"""get请求"""
header, body, url, expect = request_data(tableName, caseName)
if body == "":
resp = requests.get(url, verify=False, headers=header)
else:
resp = requests.get(url, verify=False, params=body, headers=header)
return resp, expect, body, header


def time_consume(function):
"""时间消耗计时器"""

@functools.wraps(function)
def wrapper(*args, **kwargs):
begin_time = datetime.now()
check = function(*args, **kwargs)
end_time = datetime.now()
print(end_time - begin_time)
return check

return wrapper


@time_consume
def debugging(tableName, caseName, methodType="post"):
"""单个用例调试"""
global col
excel_obj = GetExcel(tableName, caseName)
data = excel_obj.get_content()
methodType = data[col.method]
note = ""
if data[col.note] == "":
note += "None"
else:
note += data[col.note].encode("utf-8").strip().replace(":\n", "-").replace(":\n", "-")
print "\n用例信息:", tableName, caseName
print "用例描述:", note
if methodType.lower() == "post":
r, e = request_post(tableName, caseName)
else:
r, e = request_get(tableName, caseName)
print "检查点: ", json.dumps(e, ensure_ascii=False), type(e)
checkResult.CheckResult(r, e).check_result()


if __name__ == '__main__':
debugging("ads-sms-manage-web", "test_card_add_batch", "post")
# request_post("ads-send-msg", "send-text")













#用例编写

def test_log_2(self):
"""
/category/findTree
"""
debugging('ads-send-msg', 'test_log_2') (表格的文件名称、用例名称)
posted @ 2020-11-05 16:10  以泪为证  阅读(252)  评论(0)    收藏  举报