采用Appium進行自動化的功能性測試最酷的一點是,你可以使用具有最適合你的測試工具的任何一門語言來寫你的測試代碼。大家選擇最多的一個測試編程語言就是Python。 使用Appium和Python為iOS和Android應用編寫測試代碼非常容易。
在這篇博文中我們將詳細講解使用Appium下的Python編寫的測試的例子代碼對一個iOS的樣例應用進行測試所涉及的各個步驟,而對Android應用進行測試所需的步驟與此非常類似。
開始,先自https://github.com/appium/appiumfork并clone Appium,然后按照安裝指南,在你的機器上安裝好Appium。
我還需要安裝Appium的所有依賴并對樣例apps進行編譯。在Appium的工作目錄下運行下列命令即可完成此任務:
1
|
$ . /reset .sh --ios |
編譯完成后,就可以運行下面的命令啟動Appium了:
1
|
$ grunt appium |
現在,Appium已經運行起來了,然后就切換當前目錄到sample-code/examples/python。接著使用pip命令安裝所有依賴庫(如果不是在虛擬環境virtualenv之下,你就需要使用sudo命令):
1
|
$ pip install -r requirements.txt |
接下來運行樣例測試:
1
|
$ nosetests simple.py |
既然安裝完所需軟件并運行了測試代碼,大致了解了Appium的工作過程,現在讓我們進一步詳細看看剛才運行的樣例測試代碼。該測試先是啟動了樣例應用,然后在幾個輸入框中填寫了一些內容,最后對運行結果和所期望的結果進行了比對。首先,我們創建了測試類及其setUp方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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方法,在每個測試完成后發送了退出命令:
1
2
|
deftearDown( self ): self .driver.quit() |
最后,我們定義了用于填寫form的輔助方法和主測試方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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) 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 ]) |
就是這樣啦!Appium的樣例測試代碼中還有許多Python的例子。如果你對使用Nose和Python來運行Appium測試有任何問題或看法,煩請告知。