在自动化测试项目中,可能会碰到一些经常使用的但 很少变化的配置信息,下面就来介绍使用configparser来读取配置信息config.ini
读取的信息(config.ini)如下:
[config]
platformName=Android
appPackage=com.sheinside
appActivity=.module.GuideActivity
baseUrl=http://0.0.0.0:4723/wd/hub
findElementTimes=10
[cmd]
openAppium=node /Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js
stopAppium=pkill node
startServer=abd statr-server
closeServer=abb kill-server
checkPhone=adb get-state
viewPhone=adb devices
viewAndroid=adb shell grep ro.build.version.release /system/build.prop
openPhone=adb shell input keyevent 26
installSoftware=adb install
uninstallSoftware=adb uninstall com.sheinside
###############################################
读取配置文件的代码(readconfig.py):
1 importos2 importconfigparser3 importcodecs4 globalconfigfile_path5
6 prjDir = os.path.split(os.path.realpath(__file__))[0]7 configfile_path = os.path.join(prjDir, "config.ini")# 配置文件的路径8
9
10 classReadConfig:11 def __init__(self):12
13 fd =open(configfile_path)14 data =fd.read()15 #remove BOM
16 if data[:3] ==codecs.BOM_UTF8:17 data = data[3:]18 file = codecs.open(configfile_path, "w")19 file.write(data)20 file.close()21 fd.close()22
23 self.cf =configparser.ConfigParser()24 self.cf.read(configfile_path)25 # 读取config下的信息
26 defgetConfigValue(self, name):27 value = self.cf.get("config", name)28 returnvalue29 # 读取cmd下的信息
30 defgetcmdValue(self, name):31 value = self.cf.get("cmd", name)32 return value
调用执行:
if __name__ == ‘__main__‘:
rf = ReadConfig()
print rf.getConfigValue(‘platformName‘)
print rf.getcmdValue(‘openAppium‘)
结果为:
Android
node /Applications/Appium.app/Contents/Resources/node_modules/appium/bin/appium.js
[Finished in 0.2s]
原文:http://www.cnblogs.com/xiaoshitoutest/p/5592381.html