python3+requests库框架设计04-配置文件

python3配置文件的增删改查等操作可以使用内置的ConfigParser模块,可以自行百度学习,也可以看 Python3学习笔记27-ConfigParser模块

配置文件一般存放着环境信息,比如url和一些测试过程中后续需要用到的字段。还有测试中需要导入,导出的一些文件。在项目下新建Config文件夹,文件夹下新建config,ini文件。项目结构如下

实际项目接口测试中,接口url前面很大一部分都是相同的,只有后面一小部分是不同的,那可以把相同部分放在配置文件中,这样就可以通过配置文件去控制,想要测试 测试环境 还是 生产环境。

那我们就需要对配置文件的增删改查进行封装

在Common文件夹下,对Base_test.py文件添加全局变量

path = getcwd.get_cwd()
config_path = os.path.join(path, 'Config/config.ini')

上面代码是为了提供配置文件的路径,接下来是封装配置的文件的增删改查

    def config_get(self,section,key,url=None):
        '''读取配置文件字段的值并返回'''
        config = configparser.ConfigParser()
        config.read(config_path,encoding="utf-8-sig")
        if key =='url':
            config_url = config.get(section,key)
            url = config_url+url
            log1.info("请求的url:%s" % url)
            return url
        else:
            config_get = config.get(section,key)
            return  config_get


    def config_write(self,section,key = None,value = None):
        '''往配置文件写入键值'''
        config = configparser.ConfigParser()
        config.read(config_path,encoding="utf-8-sig")
        if key is not None and value is not None:
            config.set(section,key,value)
            with open(config_path,'w',encoding='utf-8')as f :
                config.write(f)
        else:
            config.add_section(section)
            with open(config_path,'w',encoding='utf-8')as f :
                config.write(f)


    def config_delete(self,section,key = None):
        '''删除配置文件字段'''
        config = configparser.ConfigParser()
        config.read(config_path,encoding="utf-8-sig")
        if key is not None :
            config.remove_option(section,key)
            with open(config_path,'w',encoding='utf-8')as f :
                config.write(f)
        else:
            config.remove_section(section)
            with open(config_path,'w',encoding='utf-8')as f :
                config.write(f)

并没有加日志,有需要的可以自己加,中间encoding都是防止对配置文件进行中文的操作,不加这些会报错的。那接下来测试一下看看

from Common.Base_test import webrequests
from Logs.log import log1

section = 'login'
username = '测试'
password = '一下'

s = webrequests()

s.config_write(section)
log1.info("写入section:%s" % section)
s.config_write(section,'username',username)
log1.info("写入%s下的用户名是:%s" %(section,username))
s.config_write(section,'password',password)
log1.info("写入%s下的密码是:%s" %(section,password))

url = s.config_get('test','url',url='test/test1')
get_username = s.config_get(section,'username')
log1.info("读取的用户名:%s" % get_username)
get_password = s.config_get(section,'password')
log1.info("读取的密码:%s" % get_password)

s.config_delete(section,'usrename',)
log1.info("删除%s下的username" % section)
s.config_delete(section,'password')
log1.info("删除%s下的password" % section)
s.config_delete(section)
log1.info("删除%s" % section)

可以先写,再读,最后删除,把操作分开,看控制台输出和配置文件中的变化会更加直观。我这里懒得一步步截图了

原文地址:https://www.cnblogs.com/myal/p/9337374.html