Python之读取配置文件
在我们编写基于Appium框架的自动化测试脚本时,我们可以把初始化中用到的参数放到配置文件中来维护读写
一、ConfigParser简介
Python自带的模块,用来读取配置文件的包。
配置文件格式:
[oppo]
platformName = Android
platformVersion = 6.0
deviceName = 2a22cee
appPackage = com.sina.weibo
appActivity = .SplashActivity
url = http://127.0.0.1:4723/wd/hub
其中中括号中的是section
section下是以key=value 格式的键值对
二、常用方法
- 创建ConfigParser实例
config=ConfigParser.ConfigParser()
- 读取配置文件
config.read(filename)
- 返回某个项目中的所有键的序列
config.options(section)
- 返回section中的option的键值
config.get(section,option)
- 添加一个配置文件的section节点
config.add_section(section-name)
- 设置某个section中键名为option的值
config.set(section,option,val)
- 返回配置文件中所有的section
config.section()
- 写入配置文件
config.write(obj_file)
三、应用实例
# -*- coding: utf-8 -*-
import unittest
from time import sleep
from appium import webdriver
import ConfigParser
class TestPlan(unittest.TestCase):
def setUp(self):
conf = ConfigParser.SafeConfigParser()
conf.read("Conf\\config.ini")
desired_caps = {}
desired_caps['platformName'] = conf.get("oppo", "platformName")
desired_caps['deviceName'] = conf.get("oppo", "deviceName")
desired_caps['appPackage'] = conf.get("oppo", "appPackage")
desired_caps['appActivity'] = conf.get("oppo", "appActivity")
self.driver = webdriver.Remote(conf.get("oppo", "url"), desired_caps)
self.driver.implicitly_wait(5)
def testLogin(self):
sleep(10)
self.driver.find_element_by_id(id_="tab_center_layout").click()
el_username = self.driver.find_element_by_id(id_="userName")
el_password = self.driver.find_element_by_id(id_="userPwd")
el_username.send_keys("13800138000")
el_password.send_keys("qwer1234")
self.driver.find_element_by_id(id_="submitbtn").click()
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()