創建test_case.yaml文件
- name: ${
name}
request:
url: 'http://www.baidu.com/'
headers:
content-type: ${
value}
params:
username: ${
user}
password: ${
pwd}
assert:
expect: none
real: none
python解析.yaml用例
def read_testcase_yaml(path: str):
with open(DATAS_YAML_PATH + path, mode='r', encoding='utf-8') as f:
return yaml.load(f, Loader=yaml.FullLoader)
校驗test_case.yaml文件用例編寫格式,是否符合預期,用第一層及第二層參數斷言驗證
def check_info_yaml(case_info):
# 獲取列表所有的key
case_info = case_info[0]
case_info_keys = case_info.keys()
# 首先判斷caseInfo中是否包含必填的字段
if 'name' in case_info_keys and 'request' in case_info_keys and 'assert' in case_info_keys:
# 獲取request中所有的key
request_keys = case_info['request'].keys()
# 判斷request中是否包含url、headers、params
if 'url' in request_keys and 'headers' in request_keys and 'params' in request_keys:
print("yaml用例標准化格式:校驗通過")
# 獲取url
url = case_info['request']['url']
# print(f"獲取yaml文件當中的url為:{url}")
# 獲取headers
headers = case_info['request']['headers']
# print(f"獲取yaml文件當中的headers為:{headers}")
else:
print("二級關鍵詞必須包含:url,headers,params")
else:
print("一級關鍵詞必須包含:name,request,assert")
這裡是主要用框架內部環境變量去做映射,達到替換環境變量的目的
不懂如何設置環境變量的可以參照:https://editor.csdn.net/md/?articleId=124766449
def replace_value(data, *args, **kwargs):
# 判斷data是否存在
print(f"參數data為:{
data}")
if data is not None:
# 判斷data類型是列表及字典類型則用json方法轉為字符串類型
# print("進入到判斷中")
if isinstance(data, list) or isinstance(data, dict):
# print("進入到字典或列表")
str_data = json.dumps(data)
# 判斷data非字典及列表則強轉為字符串即可
else:
# print("進入到其它類型")
str_data = str(data)
length = len(str_data)
# print(f"當前參數:{str_data}")
# 對字符串str_data進行循環,判斷是否存在${},存在則替換所有參數
for rv in range(1, str_data.count("$") + 1): # 這裡判斷替換次數
print(f"{
str_data.count('$')}")
start_index = str_data.index('${')
end_index = str_data.index('}', start_index, length)
print(start_index, end_index)
print(f"當前需要替換值:{
str_data[start_index:end_index + 1:]}")
replace_data = read_environment(f'{
str_data[start_index + 2:end_index:]}')
if replace_data is not None:
str_data = str_data.replace(str_data[start_index:end_index + 1:], replace_data)
else:
print(
f"您要讀取替換的key值:{
str_data[start_index + 2:end_index:]},不存在請前往/test_datas/data_type/yaml/environment.yaml文件中確認")
return eval(str_data)
else:
print(f"您輸入參數有誤要替換的參數項為:{
data}")
4個.yaml文件當中的參數均呗替換成功