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

發表于:2013-03-21來源:博客園作者:ZhuQue點擊數: 標簽:自動化測試
前幾天做了一個loadrunner結合tesseract-ocr來識別驗證碼,盡管識別精度不是太高,甚至有些驗證碼圖片不能被識別,但是使用循環的方法也是可以得到正確的驗證碼的。性能測試中不建議使用這個方法,因為涉及到大并發壓力的情況。但是在功能自動化測試中我是100

  前幾天做了一個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

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97