如何使用Python和Nose實現自動化測試?
本文我將詳細介紹使用Appium下的Python編寫的測試的例子代碼對一個iOS的樣例應用進行測試所涉及的各個步驟,而對Android應用進行測試所需的步驟與此非常類似。
開始,先自https://github.com/appium/appiumfork並clone Appium,然后按照安裝指南,在你的機器上安裝好Appium。
我還需要安裝Appium的所有依賴並對樣例apps進行編譯。在Appium的工作目錄下運行下列命令即可完成此任務:
$ ./reset.sh --ios |
編譯完成后,就可以運行下面的命令啟動Appium了:
$ grunt appium |
現在,Appium已經運行起來了,然后就切換當前目錄到sample-code/examples/python。接着使用pip命令安裝所有依賴庫(如果不是在虛擬環境virtualenv之下,你就需要使用sudo命令):
$ pip install -r requirements.txt |
接下來運行樣例測試:
$ nosetests simple.py |
既然安裝完所需軟件並運行了測試代碼,大致了解了Appium的工作過程,現在讓我們進一步詳細看看剛才運行的樣例測試代碼。該測試先是啟動了樣例應用,然后在幾個輸入框中填寫了一些內容,最后對運行結果和所期望的結果進行了比對。首先,我們創建了測試類及其setUp方法:
classTestSequenceFunctions(unittest.TestCase): defsetUp(self): app=os.path.join(os.path.dirname(__file__), '../../apps/TestApp/build/Release-iphonesimulator', 'TestApp.app') app=os.path.abspath(app) self.driver=webdriver.Remote( command_executor='http://127.0.0.1:4723/wd/hub', desired_capabilities={ 'browserName':'iOS', 'platform':'Mac', 'version':'6.0', 'app': app }) self._values=[] |
“desired_capabilities”參數用來指定運行平台(iOS 6.0)以及我們想測試的應用。接下來我們還添加了一個tearDown方法,在每個測試完成后發送了退出命令:
deftearDown(self): self.driver.quit() |
最后,我們定義了用於填寫form的輔助方法和主測試方法:
def_populate(self): # populate text fields with two random number elems=self.driver.find_elements_by_tag_name('textField') foreleminelems: rndNum=randint(0,10) elem.send_keys(rndNum) self._values.append(rndNum) www.test-edu.com deftest_ui_computation(self): # populate text fields with values self._populate() # trigger computation by using the button buttons=self.driver.find_elements_by_tag_name("button") buttons[0].click() # is sum equal ? texts=self.driver.find_elements_by_tag_name("staticText") self.assertEqual(int(texts[0].text),self._values[0]+self._values[1]) |
本文介紹到此,相信很多朋友都已經明白了。但是如果你對Nose和Python來運行Appium測試有任何問題或看法,可以給我留言,我們可以繼續交流。
相關閱讀:軟件測試自動化如何實現前后台交互?