Ruby+watir自動化測試中實現識別驗證碼圖片


    前幾天做了一個loadrunner結合tesseract-ocr來識別驗證碼,盡管識別精度不是太高,甚至有些驗證碼圖片不能被識別,但是使用循環的方法也是可以得到正確的驗證碼的。性能測試中不建議使用這個方法,因為涉及到大並發壓力的情況。但是在功能自動化測試中我是100%贊成使用的,功能自動化不像性能自動化那樣對同一個操作(登錄)有大並發的出現。

    我們使用的自動化框架是基於ruby+watir搭建的一套UI框架,通過識別UI中的對象來進行功能自動化測試,來達到檢測系統功能健康狀況。

    ruby中也有處理圖片的gem包,比如:rmagick、tesseract-ocr、rtesseract,以及ImageMagick-6.5.6-8-Q8-windows-dll.exe(需要安裝),我用的是ruby1.9.2平台的版本,本人不才,配置了很久還是調試不出來,require "rtesseract"里面的方法都對不上,貌似和ruby的版本有關系,最后放棄這個方法,使用下面的方法來實現的,也不用install任何gem包,反而覺得更簡單啦。

1、安裝tesseract-ocr-setup-3.02.02.exe,自己在網上下載的
2、配置一個批處理文件放到C盤的根目錄下,需要ruby調用這個批處理來執行tesseract.exe
批處理內容:

c:
cd C:\Program Files\Tesseract-OCR
tesseract.exe c:\CheckImg.jpg c:\CheckCode -l

3、ruby腳本,腳本步驟如下:
    a、首先獲取驗證碼的圖片;

    b、調用C盤下的批處理文件;

    c、獲取txt中的驗證碼;
4、把這段腳本做成一個def,登錄的測試用例去調用這個def,返回一個CheckCode

def CheckCode_ok(url,gifurl,CheckCode)
#獲取驗證碼圖片
require 'net/http'
Net::HTTP.start(url) do |http|
resp = http.get(gifurl)
File.open("C:\\CheckImg.jpg", "wb") do |file|
file.write(resp.body)
file.close
end
end
#執行批處理文件
system("c:\\CheckBat.bat")
#獲取txt中的驗證碼
if File.exists?("c:\\CheckCode.txt") ==true
File.open("c:\\CheckCode.txt","r") do |line|
CheckCode=line.readline
line.close
end
end
puts CheckCode
return CheckCode
end

方法如下:

CheckCode(url,gifurl,CheckCode)
url:即存在驗證碼圖片的url,如:https://memberprod.alipay.com/account/reg/index.htm

gifurl:即驗證碼圖片的url,如:https://omeo.alipay.com/service/checkcode?sessionID=fb70db3212e3c44bb5e909b51841adb5&r=0.48708463088160914

CheckCode:ruturn這個驗證碼供返回

優化了一下腳本:把方法中的傳參數精簡到2個

def CheckCode_ok(gifurl,CheckCode)
#獲取驗證碼圖片
require 'net/http'
#Net::HTTP.start(url) do |http|
#resp = http.get(gifurl)
resp = Net::HTTP.get_response(URI(gifurl))
File.open("C:\\CheckImg.jpg", "wb") do |file|
file.write(resp.body)
file.close
end
#end
#執行批處理文件
system("c:\\CheckBat.bat")
#獲取txt中的驗證碼
if File.exists?("c:\\CheckCode.txt") ==true
File.open("c:\\CheckCode.txt","r") do |line|
CheckCode=line.readline
line.close
end
end
puts CheckCode
return CheckCode
end

 調用:

def xxx_www_login(user,pwd)
LoadObject("../../testcase/xxx/xxx.yaml")
times = 0
loop do
times += 1
code = CheckCode_ok("http://xxx.xxxx.com/CheckImg.aspx/CheckImg.gif",code)
puts code
sleep 10 #獲取最新的驗證碼以后,加個sleep等待時間,貌似IE需要時間緩存最新的驗證碼code,否則@b對象獲取不到最新的驗證碼code而登陸失敗
if @b.text.include?(ExpectData("expect1")) == true #是否存在“商家登錄”
 xxx_login(user,pwd,code)
elsif @b.text.include?(ExpectData("expect2")) == true #是否存在“退出”
 xxx_www_logout
xxx_login(user,pwd,code)
end
break if times >= 5 or @b.text.include?(ExpectData("expect2")) == true #是否存在“退出”
 end #loop end 
end

 


免責聲明!

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



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