1. 程式人生 > >python+selenium的unittest框架通過讀取properties檔案自定義選擇IE/Firefox/Chrome瀏覽器

python+selenium的unittest框架通過讀取properties檔案自定義選擇IE/Firefox/Chrome瀏覽器

Browser.properties

browser=Chrome

main.py

class Properties:
    fileName = ""

    def __init__(self, fileName):
        self.fileName = fileName

    def getProperties(self):

        try:
            pro_file = open(self.fileName, 'r')
            properties = {}
            for line in pro_file:
                if line.find('=') > 0:
                    strs = line.replace('\n', '').split('=')
                properties[strs[0]] = strs[1]
        except Exception, e:
            raise e
        else:
            pro_file.close()

    return properties

    def getProperty(self, key):  # key傳進來的值是browser
        dict = self.getProperties()  # 字典格式,這裡dict的結果就是{"browser": "Chrome"}
        return dict.get(key)  # 這裡返回的結果就是Chrome


寫在基類中:
def getProperty(self, key):
	path = util.getProjectRootPath()  #外面的util類負責獲取專案根路徑
	properties = Properties(path + 'Browser.properties')   #獲取這個Browser.properties的物理路徑
	return properties.getProperty(key)

封裝瀏覽器的py檔案:
def __setupFirefox(self):
	driver = webdriver.Firefox()
	return driver

def __setupChrome(self):
	driver = webdriver.Chrome()
	return driver

在寫用例case裡面用到的py檔案,呼叫封裝的方法:
def setUp(self):
	browser = self.getProperty('browser')
	if browser.lower() == 'chrome':
		self.driver = self.__setupChrome()
	elif browser.lower() == 'firefox':
		self.driver = self.__setupFirefox()
	else:
		self.driver = self.__setupChrome()