feat(core): 增强 Exchange,实现智能变量替换与类型保持
- 优化 conftest.py 增加异常日志记录和测试报告环境信息 - 其他优化
This commit is contained in:
@@ -1,80 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
|
||||
"""
|
||||
@author: CNWei
|
||||
@Software: PyCharm
|
||||
@contact: t6i888@163.com
|
||||
@file: case_handler
|
||||
@date: 2025/5/26 22:13
|
||||
@desc:
|
||||
"""
|
||||
import json
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass, asdict
|
||||
from commons.models import TestCaseModel
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TestCaseHandle(TestCaseModel):
|
||||
|
||||
@classmethod
|
||||
def new(cls, testcase: dict) -> 'TestCaseHandle':
|
||||
|
||||
try:
|
||||
instance = cls(**testcase)
|
||||
return instance
|
||||
except (TypeError, ValueError) as e:
|
||||
logger.warning(f"解析错误:{e}")
|
||||
raise e
|
||||
|
||||
def to_string(self) -> str:
|
||||
"""
|
||||
将 字典 转换为 json 格式的字符串。
|
||||
|
||||
:return:
|
||||
json 格式的字符串。
|
||||
"""
|
||||
try:
|
||||
res = json.dumps(asdict(self), ensure_ascii=False)
|
||||
return res
|
||||
except TypeError as e:
|
||||
logger.error(f"将数据转换为 json 字符串时出错: {e}")
|
||||
raise e
|
||||
|
||||
@staticmethod
|
||||
def to_dict(json_str: str) -> dict:
|
||||
"""
|
||||
将 json 格式的字符串转换为 字典.
|
||||
|
||||
:param
|
||||
json_str: json 格式的字符串。
|
||||
:return:
|
||||
"""
|
||||
try:
|
||||
res = json.loads(json_str)
|
||||
return res
|
||||
except json.JSONDecodeError as e:
|
||||
logger.error(f"将 json 字符串转换为字典时出错: {e}")
|
||||
raise e
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from pathlib import Path
|
||||
from commons.file_processors import processor_factory
|
||||
|
||||
test_data = Path(r"E:\PyP\InterfaceAutoTest\TestCases\test_1_user.yaml")
|
||||
yaml_data = processor_factory.get_processor_class(test_data)
|
||||
case_info = TestCaseHandle.new(yaml_data.load())
|
||||
print(case_info.to_string())
|
||||
print(type(case_info.to_string()))
|
||||
print(case_info.to_dict(case_info.to_string()))
|
||||
print(type(case_info.to_dict(case_info.to_string())))
|
||||
print(type(case_info))
|
||||
print(case_info.parametrize)
|
||||
|
||||
for i in case_info.parametrize:
|
||||
print(i)
|
||||
@@ -1,98 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
|
||||
"""
|
||||
@author: chen wei
|
||||
@Software: PyCharm
|
||||
@contact: t6i888@163.com
|
||||
@file: files.py
|
||||
@date: 2024 2024/9/15 21:28
|
||||
@desc: 读取和保存yaml文件
|
||||
"""
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class YamlFile(dict):
|
||||
def __init__(self, path=None, data=None):
|
||||
super().__init__()
|
||||
self.path = Path(path) if path else None
|
||||
|
||||
if data:
|
||||
self.update(data)
|
||||
elif self.path:
|
||||
if self.path.is_dir():
|
||||
raise IsADirectoryError(f"The path {self.path} is a directory, not a file.")
|
||||
self.load()
|
||||
|
||||
def load(self):
|
||||
if not self.path:
|
||||
logger.warning("No path specified for YamlFile, cannot load.")
|
||||
return self
|
||||
|
||||
if self.path.exists() and self.path.is_file():
|
||||
with open(self.path, "r", encoding="utf-8") as f:
|
||||
loaded_data = yaml.safe_load(f) or {}
|
||||
self.clear()
|
||||
self.update(loaded_data)
|
||||
else:
|
||||
logger.warning(f"File not found at {self.path}, YamlFile initialized as empty.")
|
||||
self.clear()
|
||||
return self
|
||||
|
||||
def to_yaml(self) -> str:
|
||||
return yaml.safe_dump(
|
||||
dict(self),
|
||||
allow_unicode=True,
|
||||
sort_keys=False
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def by_yaml(cls, yaml_str):
|
||||
data = yaml.safe_load(yaml_str) or {}
|
||||
return cls(data=data)
|
||||
|
||||
def save(self):
|
||||
if not self.path:
|
||||
raise ValueError("Cannot save YamlFile instance without a specified path.")
|
||||
|
||||
# 确保父目录存在
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(self.path, "w", encoding="utf-8") as f:
|
||||
yaml.safe_dump(
|
||||
dict(self),
|
||||
stream=f,
|
||||
allow_unicode=True,
|
||||
sort_keys=False
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from core.models import CaseInfo
|
||||
from core.settings import TEST_CASE_DIR
|
||||
|
||||
# 1. 创建一个用于测试的临时yaml文件
|
||||
dummy_path = TEST_CASE_DIR / "test_model_demo.yaml"
|
||||
dummy_data = {
|
||||
"title": "Get user info",
|
||||
"request": {"method": "GET", "url": "/users/1"},
|
||||
"validate": [{"equals": ["status_code", 200]}]
|
||||
}
|
||||
YamlFile(path=dummy_path, data=dummy_data).save()
|
||||
print(f"--- 已创建临时测试文件: {dummy_path}")
|
||||
|
||||
# 2. 加载文件并使用Pydantic模型进行校验
|
||||
yaml_case = YamlFile(dummy_path)
|
||||
print("\n--- 已加载YAML内容 ---\n", yaml_case.to_yaml())
|
||||
case_model = CaseInfo(**yaml_case)
|
||||
print("\n--- Pydantic模型校验成功 ---")
|
||||
print(case_model.model_dump_json(indent=2, by_alias=True))
|
||||
|
||||
# 3. 清理临时文件
|
||||
dummy_path.unlink()
|
||||
print(f"\n--- 已清理临时文件: {dummy_path}")
|
||||
Reference in New Issue
Block a user