配置文件类的封装
在做自动化测试的时候,不管是接口自动化还是UI自动化,都需要把一些常用的数据存放到一个单独的文件,其实就是所谓的配置文件。
配置文件不仅方便数据、参数的统一配置管理,同时也增强了代码的可读性、可维护性。
python中提供了ConfigParser类供我们对配置文件进行操作
下面就针对配置文件的常用操作读写进行封装
读操作:根据提供的section和option读取其中的值
写操作:在section中写入option的值
from configparser import ConfigParser, NoSectionError, NoOptionError
class ConfigHandler:
"""封装配置文件类
1、读取配置参数
2、修改配置参数
"""
def __init__(self, filename, encoding='utf-8'):
self.filename = filename
self.encoding = encoding
self.config = ConfigParser()
self.config.read(filename, encoding=encoding)
def read(self, section, option):
# 读取配置文件的某一项
try:
return self.config.get(section, option)
except NoSectionError:
print('没有这个section')
except NoOptionError:
print('没有这个option')
def write(self, section, option, value, mode='w'):
# 往配置文件中写操作
if self.config.has_section(section):
self.config.set(section, option, value)
with open(self.filename, mode=mode, encoding=self.encoding) as f:
self.config.write(f)
根据自身的需要,该封装类中还可以增加其他操作,比如获取所有section,获取section的所有option值等等。

浙公网安备 33010602011771号