python做自动化测试时,项目中经常用到对环境、对设备等的配置信息,这些配置信息在每次测试时会有所不同,怎样把配置信息集中放在一起,便于后续的修改维护呢,本文介绍三种方式。
第一种:采用 .yaml格式。这是目前功能最强大的格式。
yaml的说明介绍
YAML 是专门用来写配置文件的语言,功能非常强大简洁,要比json格式方便。
YAML 在python语言中有对应的第三方库,名称:pyyaml,下载地址:https://pyyaml.org/ ,安装命令:python -m pip install pyyaml
YAML 语言的设计目标,就是方便人读写,它实质上是一种通用的数据串行化格式。
YAML 语言的基本语法规则如下:
1. 大小写敏感;
2. 使用缩进表示层级关系;
3. 缩进时不允许使用Tab键,只允许使用空格;
4. 缩进的空格数无限制,同一层级的元素缩进相同即可;
5. 注释使用‘#’表示,与python的注释相同;
YAML 支持的数据结构有三种:
1、对象:键值对的集合,又称为映射(mapping)/哈希(hashes)/字典(dictionary);
2、数组:一组按次序排列的值,又称为序列(sequence)/列表(list);
3、纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期等;
上一张YAML的样例图(从他处截取):
读写yaml文件参考链接:读写yaml文件
第二种:采用 .ini 格式
.ini文件格式介绍
Python3 官方 ConfigParser该模块提供了实现基本配置语言的类,该类提供的结构类似于 Microsoft Windows INI 文件中的结构。可以使用它来编写可由最终用户轻松定制的 Python 程序。
ini 语法规则
ConfigParser 的一些问题:
- 不能区分大小写。
- 重新写入的配置文件不能保留原有配置文件的注释。
- 重新写入的配置文件不能保持原有的顺序。
- 不支持嵌套。
- 不支持格式校验。
- 易用性
注意事项
- 配置参数读出来都是字符串类型, 参数运算时,注意类型转换,另外,对于字符型参数,不需要加""
- 只要注意配置文件的参数尽量使用小写/大写,统一即可
ini 常用函数
读取配置文件
- read(filename) 直接读取 ini 文件内容
- sections() 得到所有的 section,并以列表的形式返回
- options(section) 得到该 section 的所有 option
- items(section) 得到该 section 的所有键值对
- get(section,option) 得到 section 中 option 的值,返回为 string 类型
- getint(section,option) 得到 section 中 option 的值,返回为 int 类型
- getfloat(section,option)得到 section 中 option 的值,返回为 float 类型
- getboolean(section, option)得到 section 中 option 的值,返回为 boolean 类型
写入配置文件
- add_section(section) 添加一个新的 section
- has_section(section) 判断是否有 section
- set(section, option, value) 对 section 中的 option 进行设置
- remove_setion(section)删除一个 section
- remove_option(section, option)删除 section 中的 option
- write(fileobject)将内容写入配置文件。
配置文件类型问题
- getint(section,option) 返回 int 类型
- getfloat(section, option) 返回 float 类型
- getboolean(section,option) 返回 boolen 类型
ini 文件样例
[section] # section
option = value # key = val 或 key: val
[user]
username = tom
password = 123456
email = test@host.com
[book]
bookname = python learning
bookprice = 25
bookpress = 人民邮电出版社
[cars]
count = 2
读写ini文件 参考链接:读写ini格式文件
第三种:采用 .properties格式
.properties文件格式介绍
Python 中正好没有解析 properties 文件的现成模块,所以单独编写了一个脚本用于读写 *.properties 文件。
properties 文件样例
restserver.url=http://0.0.0.0:8080
# graphs list with pair NAME:CONF_PATH
graphs=[test01:conf/hugegraphtest01.properties,hugegraph:conf/hugegraph.properties,hugegraph1:conf/hugegraph1.properties,hugegraph2:conf/hugegraph2.properties]
# authentication
#auth.require_authentication=
#auth.admin_token=
#auth.user_tokens=[]