pytest_api/tools/yaml_control.py

103 lines
3.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import yaml.scanner,yaml.parser
import os
from tools.regular_control import regular
class GetYamlData:
def __init__(self, file_dir):
self.fileDir = file_dir
def get_yaml_data(self) -> dict:
"""
获取 yaml 中的数据
:param: fileDir:
:return:
"""
# 判断文件是否存在
if os.path.exists(self.fileDir):
data = open(self.fileDir, 'r', encoding='utf-8')
try:
res = yaml.load(data, Loader=yaml.FullLoader)
return res
except UnicodeDecodeError:
raise ValueError(f"yaml文件编码错误文件路径:{self.fileDir}")
else:
raise FileNotFoundError("文件路径不存在")
def write_yaml_data(self, key: str, value) -> int:
"""
更改 yaml 文件中的值
:param key: 字典的key
:param value: 写入的值
:return:
"""
with open(self.fileDir, 'r', encoding='utf-8') as f:
# 创建了一个空列表,里面没有元素
lines = []
for line in f.readlines():
if line != '\n':
lines.append(line)
f.close()
with open(self.fileDir, 'w', encoding='utf-8') as f:
flag = 0
for line in lines:
left_str = line.split(":")[0]
if key == left_str and '#' not in line:
newline = "{0}: {1}".format(left_str, value)
line = newline
f.write('%s\n' % line)
flag = 1
else:
f.write('%s' % line)
f.close()
return flag
class GetCaseData(GetYamlData):
def get_different_formats_yaml_data(self) -> list:
"""
获取用例的名字
:return:
"""
res_list = []
for i in self.get_yaml_data():
res_list.append(i)
return res_list
def get_yaml_case_data(self):
"""
获取测试用例数据, 转换成指定数据格式
:return:
"""
try:
_yaml_data = self.get_yaml_data()
# 正则处理yaml文件中的数据
re_data = regular(str(_yaml_data))
return eval(re_data)
except yaml.parser.ParserError as e:
raise yaml.parser.ParserError("yaml格式不正确, 请检查下方对应路径中的文件内容 {0}".format(e))
except yaml.scanner.ScannerError as e:
raise yaml.scanner.ScannerError("yaml格式不正确, 请检查下方对应路径中的文件内容 {0}".format(e))
if __name__ == '__main__':
from config.settings import ConfigHandler
print(ConfigHandler.data_path + r'\dmsystem\user\adduser.yaml')
TestData2 = GetCaseData(ConfigHandler.data_path + r'\dmsystem\user\adduser.yaml').get_yaml_data()
print(TestData2)
TestData1 = GetCaseData(ConfigHandler.data_path + r'\dmsystem\user\adduser.yaml').get_different_formats_yaml_data()
print(TestData1)
TestData = GetCaseData(ConfigHandler.data_path + r'\dmsystem\user\adduser.yaml').get_yaml_case_data()
print(TestData)