做自动化测试的时候,大多数同学会存放在Excel、Yaml、数据库中,接下来我们将编写一个demo,用来读取存放在yaml中的测试数据
-
下载依赖包
pip install PyYAML
2. 导包
'''
@公众号 : 芦荟全栈测开
@File : yamlDataGet.py
@Software: PyCharm
'''
import logging
import yaml
from base.impl.fileManageImpl import FileManageImpl
-
import logging:是我们封装好的日志模块
-
import yaml:导入yaml包
-
from base.impl.fileManageImpl import FileManageImpl:这里是我们对文件是否存在判断的一个实现类(下面要讲)
3.初始化
def __init__(self, yamlPath: str):
"""
:param yamlPath: yaml文件路径
"""
self.__yamlPath = yamlPath
-
yamlPath:yaml文件路径
-
self.__yamlPath:实例属性
4.读取yaml数据
@property
def yamlRead(self)->dict:
"""
yaml文件内容读取
:return:
"""
yamlData = {}
if FileManageImpl.isExistFile(self.__yamlPath):
with open(self.__yamlPath, "r", encoding="utf-8") as yf:
try:
yamlData = yaml.safe_load(yf)
except Exception as e:
logging.error(f"文件->{self.__yamlPath}-->内容读取失败->{e}")
return yamlData
实现思路:
-
判断yaml路径是否存在,若是存在读取yaml数据
-
若是不存在返回空字典
5.完整代码
'''
@公众号 : 芦荟全栈测开
@File : yamlDataGet.py
@Software: PyCharm
'''
import logging
import re
import yaml
from base.impl.fileManageImpl import FileManageImpl
class YamlDataGet:
def __init__(self, yamlPath: str):
"""
yaml文件操作
:param yamlPath: yaml文件路径
"""
self.__yamlPath = yamlPath
@property
def yamlRead(self)->dict:
"""
yaml文件内容读取
:return:
"""
yamlData = {}
if FileManageImpl.isExistFile(self.__yamlPath):
with open(self.__yamlPath, "r", encoding="utf-8") as yf:
try:
yamlData = yaml.safe_load(yf)
except Exception as e:
logging.error(f"文件->{self.__yamlPath}-->内容读取失败->{e}")
return yamlData
6.FileManageImpl代码
'''
@公众号 : 芦荟全栈测开
@File : fileManageImpl.py
@Software: PyCharm
'''
import logging
import os
from base.fileManage import FileManage
class FileManageImpl(FileManage):
@classmethod
def isExistFile(cls, filePath:str)->bool:
"判断文件是否存在"
if not os.path.exists(filePath):
logging.error(f"文件-->{filePath}-->不存在")
return False
return True
@classmethod
def isExistDir(cls, path:str)->bool:
"判断文件目录是否存在,不存在则自动创建"
if not os.path.isdir(path):
try:
os.mkdir(path)
except Exception as e:
logging.error(f"路径->{path}->不存在,自动创建失败->{e}")
return True
else:
logging.debug(f"路径->{path}->不存在,为您自动创建!")
return False
return True
-
FileManage:是一个抽象类,FileManageImpl继承了FileManage
-
os.path.exists:判断路径是否存在
-
os.path.isdir(path):判断是否为目录
7.FileManage代码
'''
@公众号 : 芦荟全栈测开
@File : fileManageImpl.py
@Software: PyCharm
'''
import abc
class FileManage(metaclass=abc.ABCMeta):
@abc. abstractclassmethod
def isExistFile(cls, filePath:str)->bool:
"""
判断文件是否存在
:param filePath: 文件路径
:return:
"""
pass
@abc.abstractclassmethod
def isExistDir(cls, path:str)->bool:
"""
判断目录是否存在,不存在则自动创建
:param path: 目录路径
:return:
"""
pass