溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python如何解析配置文件并應(yīng)用到項(xiàng)目中

發(fā)布時(shí)間:2020-08-22 20:15:07 來源:腳本之家 閱讀:173 作者:linux超 欄目:開發(fā)技術(shù)

配置文件的類型

通常自動(dòng)化測(cè)試中的配置文件是以.ini 和 .conf 為后綴的文件

配置文件的組成

1.section

2.option

3.value

配置文件的格式

[section_name]
# =號(hào)可以使用:號(hào)代替
option_name=value

配置文件的注釋

通常使用#號(hào)或者;分號(hào)注釋,有一點(diǎn)一定要注意,注釋最好不要寫到option_name=value行的后面,否則你會(huì)遇到意想不到的錯(cuò)誤

配置文件的作用

那么我們的配置文件主要來干些什么呢?

1.可以存儲(chǔ)測(cè)試中測(cè)試用例使用的測(cè)試數(shù)據(jù)

2.可以存儲(chǔ)測(cè)試中用到的資源數(shù)據(jù),比如數(shù)據(jù)庫的地址,用戶,密碼等等

3.可以作為ui對(duì)象庫使用,存儲(chǔ)我們ui自動(dòng)化測(cè)試項(xiàng)目中的頁面元素信息

4.可以存儲(chǔ)項(xiàng)目使用的全局變量,比如項(xiàng)目的根目錄,日志,報(bào)告的路徑等等

以上這些數(shù)據(jù)均可以存放在配置文件中,方便的我們讀取,當(dāng)項(xiàng)目的一些配置信息改變時(shí),我們只要修改配置文件即可,而不用修改具體代碼,大大減小項(xiàng)目的維護(hù)成本!

ok,既然我都標(biāo)題黨了,那么現(xiàn)在就告訴你怎么1分鐘應(yīng)用到項(xiàng)目中。有配置文件我們必定要先解析文件才行,我們現(xiàn)在有這樣一個(gè)配置文件,存放如下內(nèi)容

[126mail_login]
loginPage.frame=xpath>//div[@id='loginDiv']/iframe
loginPage.username=xpath>//input[@name='email']
loginPage.password=xpath>//input[@name='password']
loginPage.loginBtn=xpath>//a[@id='dologin']
[126mail_homePage]
homePage.addressbook=id>_mail_tabitem_1_4text
[126mail_addContactPage]
addContactPage.newContact=xpath>//span[text()='新建聯(lián)系人']
addContactPage.newName=id>input_N
addContactPage.newMail=xpath>//div[@id='iaddress_MAIL_wrap']//input[@class='nui-ipt-input']
addContactPage.newMark=xpath>//span[@class='nui-chk-text']/preceding-sibling::span/b
addContactPage.newPhone=xpath>//div[@id='iaddress_TEL_wrap']//input[@class='nui-ipt-input']
addContactPage.newComment=id>input_DETAIL
addContactPage.newCommit=xpath>//span[text()='確 定']

封裝代碼

下面這個(gè)封裝是我之前寫的,不算是很通用的功能,但是如果你的配置文件和我上面的一樣用來存儲(chǔ)ui對(duì)象庫的話就完全適用了。

"""
------------------------------------
@Time : 2019/5/16 10:56
@Auth : linux超
@File : ParseConfigOld.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
------------------------------------
"""
from configparser import (
ConfigParser,
NoSectionError,
NoOptionError
)
filename = 'configfile.ini'
class ParseConfigFile(object):
"""
解析ini配置文件
"""
def __init__(self):
try:
self.cf = ConfigParser() # 獲取配置文件對(duì)象
self.cf.read(filename, encoding='utf-8') # 加載配置文件到內(nèi)存中
except Exception as e:
raise e
def getItemsSection(self, section):
"""
獲取section下面所有section的鍵值
:param sectionName:
:return:
"""
try:
value = dict(self.cf.items(section))
except (NoSectionError, KeyError):
print('{} not exit'.format(section))
except Exception as e:
raise e
else:
return value
def getElementValue(self, section, option):
"""根據(jù)自己的需要修改這部分代碼"""
try:
# 我配置文件是用這個(gè)符號(hào)來分割的,所有解析的時(shí)候要使用這個(gè)符號(hào)分割,得到元素
locator = self.cf.get(section, option).split('>')
except (NoSectionError, NoOptionError, KeyError):
print('section:{} or option:{} not exit'.format(section, option))
except Exception as e:
raise e
else:
return locator # 獲取option鍵對(duì)應(yīng)的value
def getAllSections(self):
try:
all_sections = self.cf.sections()
except Exception as e:
raise e
else:
return all_sections # 所有的sections返回值是個(gè)列表
if __name__=='__main__':
cf = ParseConfigFile()
locator = cf.getElementValue('126mail_login','loginPage.username')
print(locator)
print(cf.getItemsSection('126mail_login'))
print(cf.getAllSections())

封裝改進(jìn)

下面的封裝幾乎可以完成任何自動(dòng)化測(cè)試項(xiàng)目中配置文件存儲(chǔ)任何數(shù)據(jù)類型的數(shù)據(jù)解析

"""
------------------------------------
@Time : 2019/5/16 9:11
@Auth : linux超
@File : ParseConfigFile.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
------------------------------------
"""
from configparser import (
ConfigParser,
NoOptionError,
NoSectionError
)
class ParseConfigFile(ConfigParser):
def __init__(self, filename):
super().__init__()
try:
self.filename = filename
self.read(filename, encoding='utf-8')
except Exception as e:
raise e
def get_all_option(self, section='DEFAULT'):
"""獲取指定section下所有的option"""
try:
options = self.options(section)
return options
except NoSectionError:
print('NoSectionError : {} not exist'.format(section))
except Exception as e:
raise e
def get_value(self, section='DEFAULT'):
"""獲取指定section中所有的option和value,返回一個(gè)字典"""
try:
value = dict(self.items(section))
return value
except (NoSectionError, KeyError):
print('{} not exist'.format(section))
except Exception as e:
raise e
def get_option_value(self, section, option, flag=False):
"""
獲取指定section和option對(duì)應(yīng)的數(shù)據(jù)
如果option對(duì)應(yīng)數(shù)據(jù)為數(shù)字,則自動(dòng)轉(zhuǎn)換為int或者float
如果option對(duì)應(yīng)的數(shù)據(jù)是個(gè)可以使用eval轉(zhuǎn)換的類型,則傳遞flag為True時(shí),自動(dòng)轉(zhuǎn)換,否則輸出str
"""
try:
value = self.get(section, option)
if value.isdigit():
return int(value)
try:
return float(value)
except Exception:
pass
if isinstance(flag, bool) and flag:
return eval(value)
return value
except (NoSectionError, NoOptionError, KeyError):
print('no option "{}" or section "{}"'.format(option, section))
except Exception as e:
raise e
def __call__(self, section='DEFAULT', option=None, flag_eval=False, flag_bool=False):
"""
對(duì)象當(dāng)成函數(shù)使用的時(shí)候會(huì)默認(rèn)調(diào)用這個(gè)方法
這個(gè)方法可以實(shí)現(xiàn)上面多數(shù)功能
:param section:
:param option:
:param flag_eval: 如果為True 我們使用eval轉(zhuǎn)換類型
:param flag_bool: 如果為True 我們使用把數(shù)據(jù)轉(zhuǎn)換為bool
:return:
"""
if option is None:
return dict(self[section])
if isinstance(flag_bool, bool):
if flag_bool:
return self.getboolean(section, option)
else:
raise ValueError('{} must be type bool'.format(flag_bool))
data = self.get(section, option)
if data.isdigit():
return int(data)
try:
return float(data)
except Exception:
pass
if isinstance(flag_eval, bool):
if flag_eval:
return eval(data)
else:
raise ValueError('{} must be type bool'.format(flag_eval))
return data
if __name__ == '__main__':
conf = ParseConfigFile('configfile.ini')
print('所有的option', conf.get_all_option('FilePath'))
print('獲取section:{},option:{}對(duì)應(yīng)的數(shù)據(jù):{}'.
format('FilePath', 'TestCase', conf.get_option_value('FilePath', 'TestCase')))
print('獲取section:{}下所有的鍵值{}'.format('FilePath', conf.get_value('ExcelNum')))
print(conf())
print(conf(section='FilePath', option='TestCase'))
print(conf(option='a', flag_bool=True))
print(conf(section='ExcelNum', option='Actual_Column_Num', flag_eval=True))

1分鐘應(yīng)用到項(xiàng)目中

啥? 你還不知道怎么一分鐘應(yīng)用到項(xiàng)目中?

好吧,看來是逃不過去了。 我要說了..... 首先復(fù)制代碼,當(dāng)然你已經(jīng)知道上述代碼的含義, 在你的項(xiàng)目中新建py文件,拷貝代碼到你的文件中,ok接下來你可能已經(jīng)知道怎么用了。這能有1分鐘嗎?

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI