Python自動化測試工具Splinter簡介和使用實例


Splinter 快速介紹

官方網站:http://splinter.cobrateam.info/

官方介紹:

Splinter is an open source tool for testingweb applications using Python. It lets you automate browser actions, such asvisiting URLs and interacting with their items

特性:

1、可以模擬瀏覽器行為,訪問指定的URL,並且可以指定不同的瀏覽器類型。比如firefox或者chrome等。不同的瀏覽器只要在本地安裝對應的驅動,就可以在代碼中通過名稱指定來訪問。
2、支持cookie操作,可以很方便的添加和刪除cookie;
3、支持模擬鼠標的動作,比如滑動到某個按鈕上,焦點離開某個按鈕等等,對於帶有動態提示的頁面,如搜索引擎的關鍵字輸入框的動態提示,可以非常方便的測試。
4、支持模擬鍵盤的輸入操作,對input等控件的輸入可以模擬用戶的type過程。
5、支持直接運行js或者調用頁面的js。
6、支持模擬上傳文件。
7、對radio和checkbox有專門的api支持,非常方便;
8、支持快速的獲取頁面的元素或者判斷是否存在文本,用於開發判斷頁面提示信息是否准確非常方便。
9、最重要的,splinter的API非常簡單,配合官方的文檔學習成本幾乎是0,當然你得懂一些python語法。如果你比較了解js和css,你可能會像喜歡jquery一樣喜歡它;

功能:

Splinter執行的時候會自動打開你指定的瀏覽器,訪問指定的URL。
然后你所開發的模擬的任何行為,都會自動完成,你只需要坐在電腦面前,像看電影一樣看着屏幕上各種動作自動完成然后收集結果即可。


舉個例子,我們要回歸登錄功能,首先要開發如下模擬登錄行為的腳本:

 1 #!/usr/bin/py2
 2 # -*- coding: utf-8 -*-
 3 #encoding=utf-8
 4 import sys, re
 5 from splinter.browser import Browser 
 6 CLOASE_AFTER_TEST = False
 7 reload(sys)
 8 sys.setdefaultencoding('utf8')
 9 encoding = lambda x:x.encode('gbk') 
10 def testLogin(desc, username, password, result):
11     output(desc)      
12     browser.fill('TPL_username',username.decode('utf8'))
13     browser.fill('TPL_password',password.decode('utf8'))
14     browser.find_by_value('登錄').first.click()
15     checkresult(result) 
16 def output(x):
17     print encoding(x) 
18 def resultMsg(x):
19     if x == True:
20         print 'pass'
21     else:
22         print '[X]not pass'
23 def checkresult(x):
24     """  check result message, x : the error message u want  """
25     resultMsg(browser.is_text_present(x)) 
26 __testUrl = 'http://waptest.taobao.com/login/login.htm?tpl_redirect_url=http%3A%2F%2Fm.taobao.com%2F' 
27 # chrome driver : http://code.google.com/p/selenium/wiki/ChromeDriver
28 browser = Browser()  # already support firefox
29 browser.visit(__testUrl)
30 output("測試頁面:"+browser.title) 
31 try:
32     # test login
33     testLogin('測試未輸入用戶名','','','請輸入會員名')
34     testLogin('測試未輸入密碼','qd_test_001','','請輸入密碼')
35     testLogin('測試帳戶不存在','這是一個不存在的名字哦','xxxxxxx','該賬戶名不存在')
36     testLogin('測試成功登錄','qd_test_001','taobao1234','繼續登錄前操作') 
37     # test find password
38     output("測試[找回密碼]鏈接")
39     browser.visit(__testUrl)
40     backPasswordLink = browser.find_link_by_text('取回密碼')
41     if 1 == len(backPasswordLink):
42         backPasswordLink.first.click()
43         ru = re.findall(re.compile(".*(reg/gp.htm).*", re.IGNORECASE), browser.url)
44         if ru is not None:
45             checkresult('找回密碼')
46         else:
47             output("測試找回密碼鏈接失敗") 
48 except Exception,x:
49     print x 
50 if CLOASE_AFTER_TEST:
51     browser.quit()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM