refactor(): 优化文件读取,变量替换等
- 优化用例加载模块器 - 新增JSON文件读取模块
This commit is contained in:
@@ -9,38 +9,33 @@
|
||||
@date: 2025/3/7 09:31
|
||||
@desc:
|
||||
"""
|
||||
from pathlib import Path
|
||||
from typing import Union
|
||||
|
||||
from yaml_processor import YamlProcessor
|
||||
from json_processor import JsonProcessor
|
||||
from commons.file_processors.yaml_processor import YamlProcessor
|
||||
from commons.file_processors.json_processor import JsonProcessor
|
||||
|
||||
class FileHandle:
|
||||
def __init__(self, filepath: Union[str, Path], data: Union[dict, None] = None):
|
||||
# self.filepath: Path = Path(filepath) # 确保 filepath 是 Path 对象
|
||||
# self.data: Union[dict, None] = data
|
||||
self.processor = get_processor(filepath, data)
|
||||
processors = {
|
||||
'yaml': YamlProcessor,
|
||||
'yml': YamlProcessor,
|
||||
'json': JsonProcessor,
|
||||
|
||||
def load(self) -> None:
|
||||
self.processor.load()
|
||||
|
||||
def to_string(self) -> str:
|
||||
return self.processor.to_string()
|
||||
|
||||
def to_dict(self, data: str) -> None:
|
||||
self.processor.to_dict(data)
|
||||
|
||||
def save(self, new_filepath: Union[str, Path, None] = None):
|
||||
self.processor.save(new_filepath)
|
||||
}
|
||||
|
||||
|
||||
def get_processor(filepath, data):
|
||||
ext = Path(filepath).suffix.lower()[1:] # 获取后缀名,如 'json'
|
||||
processors = {
|
||||
'yaml': YamlProcessor,
|
||||
'yml': YamlProcessor,
|
||||
'json': JsonProcessor,
|
||||
|
||||
}
|
||||
def get_processor(ext):
|
||||
agent_model = processors.get(ext, YamlProcessor) # 代理模式
|
||||
return agent_model(filepath, data) # 默认回退到 Yaml
|
||||
|
||||
return agent_model # 默认回退到 Yaml
|
||||
|
||||
|
||||
FileHandle = get_processor("yaml")
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 示例用法
|
||||
yaml_path = r'E:\PyP\InterfaceAutoTest\TestCases\answer\test_1_status.yaml' # 你的 YAML 文件路径
|
||||
yaml_file = FileHandle(yaml_path)
|
||||
print(yaml_file)
|
||||
print(type(yaml_file))
|
||||
file_string = FileHandle.to_string(yaml_file)
|
||||
print(file_string)
|
||||
file_dict = FileHandle.to_dict(file_string)
|
||||
print(file_dict)
|
||||
|
||||
Reference in New Issue
Block a user