路漫漫其修远兮,吾将上下而求索

发布新日志

  • watir_ruby: 读写excel文件【转帖】

    2009-12-11 10:25:42

    ruby: 读写excel文件【转帖】
     
     
     
    测试工作中,批量的数据通常会放到excel表格中,测试输出的数据写回表格中,这样输入输出易于管理,同时清晰明了
    使用ruby来操作excel文件首先需要在脚本里包含以下语句
    require 'win32ole'

    把win32ole包含进来后,就可以通过和windows下的excel api进行交互来对excel文件进行读写了.


    打开excel文件,对其中的sheet进行访问:
    excel = WIN32OLE::new('excel.Application')
    workbook = excel.Workbooks.Open('c:\examples\spreadsheet.xls')
    worksheet = workbook.Worksheets(1) #定位到第一个sheet
    worksheet.Select

    读取数据:
    worksheet.Range('a12')['Value'] #读取a12中的数据
    data = worksheet.Range('a1:c12')['Value'] #将数据读入到一个二维表


    找到第一处a列的值为空值
    line = 1
    while worksheet.Range("a#{line}")['Value']
    line=line+1
    end #line的值为第一处空白行的行数


    将第一列的值读入到一个数组中
    line = '1'
    data = []
    while worksheet.Range("a#{line}")['Value']
    data << worksheet.Range("a#{line}:d#{line}")['Value']
    line.succ!
    end


    将数据写入到excel表格中
    worksheet.Range('e2')['Value'] = Time.now.strftime '%d/%m/%Y' #单个值
    worksheet.Range('a5:c5')['Value'] = ['Test', '25', 'result'] #将一个数组写入


    调用宏定义
    excel.Run('SortByNumber')

    设置背景色
    worksheet.Range('a3:f5').Interior['ColorIndex'] = 36 #pale yellow
    # 将背景色恢复成无色
    worksheet.Range('a3:f5').Interior['ColorIndex'] = -4142 # XlColorIndexNone constant
    # 使用Excel constant 将背景色恢复成无色
    worksheet.Range('a3:f5').Interior['ColorIndex'] = ExcelConst::XlColorIndexNone


    保存
    workbook.Close(1)
    # 或
    workbook.SaveAs 'myfile.xls'
    # 默认路径是系统定义的"我的文档"


    结束会话
    excel.Quit

    一些相对完整的代码片段

    创建一个excel文件并保存
    require 'win32ole'
    excel = WIN32OLE.new("excel.application")
    excel.visible = true # in case you want to see what happens
    workbook = excel.workbooks.add
    workbook.saveas('c:\examples\spreadsheet1.xls')
    workbook.close

    操作excel文件的几个重要元素
    Excel => workbook => worksheet => range(cell)
    我理解的是excel为类名,workbook为一个具体的(excel文件)实例,创建好实例后,worksheet是实例(workbook,工作簿)中的一个工作表,然后可

    以对工作表中的每个单元格(range(cell))进行具体的读写------------------按照这样操作肯定没有错,不过下面的这些语句又让我有些疑惑


    excel.workbooks("Mappe1").worksheets("Tabelle1").range("a1").value #读取名为Mappe1的excel文件中工作表名为Tabelle1的a1单元格中的值
    excel.worksheets("Tabelle1").range("a1").value #作用同第一条语句
    excel.activeworkbook.activesheet.range("a1").value #作用同第一条语句
    excel.activesheet.range("a1").value #作用同第一条语句
    excel.range("a1").value #作用同第一条语句

    excel可以直接操作所有的属性,默认为当前活跃的工作簿/工作表


    对单元格的操作:

    某个单元格: sheet.range("a1")

    a1到c3的值: sheet.range("a1", "c3") 或 sheet.range("a1:c3")

    第一列: sheet.range("a:a")

    第三行: sheet.range("3:3")

    获得单元格的值:
    range.text #读取值,返回为字符串格式,如果单元格内为数字,有可能会被截断小数点后的位数
    sheet.range("a1").text

    range.value #读取值,数字不会截断
    sheet.range("a1").value

    对单元格设置值
    sheet.range("a1").value = 1.2345

    sheet.range("a1").value = '1.2345'

    迭代访问:

    sheet.range("a1:a10").each{|cell|puts cell.value}

    如果范围是一个矩形,则会按行循环迭代访问
    sheet.range("a1:b5").each{|cell|puts cell.value}

    block迭代,并打印出每行的第一个值
    sheet.range("b3:c7").rows.each{|r|puts r.cells(1,1).value}


    原文地址 http://www.51testing.com/?46209/action_viewspace_itemid_82188.html

    ------------------------------------------------------------------------------

    Automating Excel: Creating Charts(摘录)

     


    We'll use the win32ole library for automating Excel, and we'll connect to a running instance of Excel and use the already open 'mlb_stats.xls' workbook:

    require 'win32ole'
    xl = WIN32OLE.connect('Excel.Application')
    wb = xl.Workbooks('mlb_stats.xls')
    ----------新建Excel文档

    Let's define some parameter variables that we'll use later:
    ----------设置Excel属性
    xlColumns = 2
    xlColumnClustered = 51
    xlWhite = 2
    xlRed = 3
    xlBlue = 5
    xlGray = 15

    To add a new Chart object to the workbook's Charts collection, call the Charts.Add method:

    mychart = wb.Charts.Add
    mychart.Name = "MLB Scoring"
    ----------设置Excel charts name
    The Charts.Add method returns a reference to the newly-created Chart object, which we've assigned to the variable mychart.

    To delete an existing Chart object, call the Charts(chart).Delete method, where chart is the name or (1-based) index of the chart to delete:


    wb.Charts("MLB Scoring").Delete
    wb.Charts(1).Delete
    ----------删除Excel charts
     
     

  • watir的1.6.5版本的中文字符问题

    2009-11-30 12:52:41

    watir的1.6.5版本的对中文字符的访问时有些问题的,应该更改win32ole.rb这个文件。具体如下

    C:\ruby\lib\ruby\gems\1.8\gems\watir-1.6.5\lib\watir\win32ole.rb

    更改为:

    require 'win32ole'
    WIN32OLE.codepage =  WIN32OLE::CP_ACP

  • 使用ruby关闭ie进程

    2009-11-30 09:50:16

    使用watir的close_all方法,有时会关闭不掉IE,最好的办法就是直接终止IE进程,可以写一个关闭ie的方法

     

    require 'win32ole'
        # Returns the number of windows processes running with the specified name.
        def  close_ie
          mgmt = WIN32OLE.connect('winmgmts:\\\\.')
          processes=mgmt.instancesof("win32_process")
          processes.each do |process|
              puts process
             if  process.name =="iexplore.exe" then      
              process.terminate()
              end
            end
        end

    这样调用close_ie方法时就可以关闭IE进程了。

     
  • ci_reporter in ruby

    2009-11-27 17:10:19

    使用require 'ci/reporter/rake/test_unit_loader.rb',应该在ruby下安装ci_reporter

    即gem install ci_reporter

  • 使用xpath watir测试中文网站

    2009-11-18 14:41:13

    今天,写了一个测试谷歌中文搜索网站的测试脚本,如下:

    require 'watir'

    ie_site='google.com.cn'

    ie=Watir::IE.new

    ie.goto ie_site

    ie.text_field(:xpath,“//input[@name='q']”).set "test"

    但是脚本一直有错误提示信息,很长的一大串,这里不在拷贝了。

    通过搜索网页和询问朋友,这里有两个解决办法

    1.使用gem list查看watir version,如果是1.6.2,更新为1.6.5。因为1.6.2使用rexml来解析xml,而1.6.5使用nokogiri来解析,能够识别中文网页。

    2.另一种是添加如下代码,

     requir 'win32ole'

     WIN32OLE.codepage=WIN32OLE::CP_UTF8


  • XPath 语法

    2009-11-16 17:56:22

    1:选取节点:XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。

        表达式      描述
       nodename     选取此节点的所有子节点
       /            从根节点选取
       //           从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置
       .            选取当前节点
       ..           选取当前节点的父节点
       @            选取属性

    2:谓语(Predicates):谓语用来查找某个特定的节点或者包含某个指定的值的节点。谓语被嵌在方括号中。

    3:选取未知节点:XPath 通配符可用来选取未知的 XML 元素。

        通配符     描述
        *          匹配任何元素节点
        @*         匹配任何属性节点
        node()     匹配任何类型的节点

    4:选取若干路径:通过在路径表达式中使用“|”运算符,您可以选取若干个路径。

  • Watir系列——在Watir中运用Xpath中级篇

    2009-11-15 17:52:14

    上文中提到,Watir运用xpath在实际运用时遇到了一些问题导致无法继续。具体问题是:使用Watir with Xpath来进行脚本编写,然而首次尝试就出现问题。很简单的一段脚本却总是抛异常,脚本代码如下:

    4

    异常详见附图一,从异常信息分析,是REXML解析网页时出错,同样的脚本换成英文网页却运行正常,问题似乎是在Watir使用的REXML对中文网页的支持上。网上搜索到相关的信息也很少,Watir中运用Xpath似乎对我们日常的脚本工作失去了意义。百般无奈之下发了求助帖,希望有人能研究过类似问题。

    下班之前看到回帖说Watir中的解析器正在由REXML向Nokogiri转变,也许会在Watir下一版本中体现。等到新版本已不知何年何月,于是决定自己做尝试改造一下Watir。

    首先gem安装Nokogiri:gem install nokogiri

    然后从异常信息定位到Watir使用Xpath时调用的方法都在ie-class.rb文件中:

    #Functions written for using xpath for getting the elements.

    #get the Rexml object

    Rexml_document_object

    #create rexml object if it is nil

    Create_rexml_document_object

    #output error xml when exception caught

    Output_rexml_document

    #return the first element that match the xpath

    Element_by_xpath

    #execute xpath and return an array of elements

    Elements_by_xpath

    很直接的思路是将使用Rexml的地方通通替换为Nokogiri,确定方向之后就开始动手。将以上方法替换为以下方法:

    # Functions written for using xpath for getting the elements.—–using nokogiri

    #返回nokogiri文本对象,若对象为空,则创建

    def xmlparser_document_object

    if @xml_parser_doc == nil

    create_xml_parser_doc

    end

    return @xml_parser_doc

    end

    # Create the Nokogiri object if it is nil. This method is private so can be called only

    # from xmlparser_document_object method.

    #创建文本对象

    def create_xml_parser_doc

    require ‘nokogiri’

    if @xml_parser_doc == nil

    htmlSource =”<?xml version=\”1.0\” encoding=\”UTF-8\”?>\n<HTML>\n”

    htmlSource = html_source(document.body,htmlSource,” “)

    htmlSource += “\n</HTML>\n”

    htmlSource = htmlSource.gsub(/&nbsp;/, ‘ ’)

    begin

    @xml_parser_doc = Nokogiri::HTML::Document.parse(htmlSource)

    return @xml_parser_doc

    rescue => e

    output_xml_parser_doc(”error.xml”, htmlSource)

    raise e

    end

    end

    end

    private :create_xml_parser_doc

    def output_xml_parser_doc(name, text)

    file = File.open(name,”w”)

    file.print(text)

    file.close

    end

    private :o utput_xml_parser_doc

    # execute xpath and return an array of elements

    #使用xpath定位,返回符合条件对象元素数组

    def elements_by_xpath(xpath)

    doc = xmlparser_document_object

    modifiedXpath = “”

    selectedElements = Array.new

    doc.xpath(xpath).each do |element|

    modifiedXpath = element.path                   # element = a REXML element

    temp = element_by_absolute_xpath(modifiedXpath) # temp = a DOM/COM element

    selectedElements << temp if temp != nil

    end

    #puts selectedElements.length

    if selectedElements.length == 0

    return nil

    else

    return selectedElements

    end

    end

    将原先的Elements_by_xpath注释掉,再运行那段代码,脚本可以正常运行,至此,Watir可以将Xpath运用于中文页面啦~山寨版Rexml=>Nokogiri改造完毕,至于本系列高级篇会是什么内容,也许是等Watir新版本出来再去解读它的Parser部分源码吧~

    P.S.本山寨版本若使用时遇到各类问题,请积极联系芷兰。

    附图一:异常信息截图

    3

  • Watir系列之——在Watir中运用xpath初级篇

    2009-11-15 17:47:56

    最近看到淘宝测试team的blog,发现了一篇关于Watir Xpath 的文章,相当不错,收藏起来。如下:

    对于Watir操作IE浏览器,目前并没有录制工具来帮助测试人员,一般靠测试人员使用IE Developer Toolbar辅助进行元素识别,然后编写测试脚本。

    在编写脚本过程中,主要通过是使用Watir::IE的一个实例化对象@ie来获得页面上的各种元素,比如button,link…然后可以对这些元素进行操作。(Watir识别HTML元素的方法详见附表一),识别元素时各不同元素支持不同的属性识别,详见附图一,这里不做赘述。

    Watir::IE封装的是一个当前页面的DOM Tree,而不是页面源代码。比如页面如果用javascrīpt动态产生一个元素,在Watir中仍然可以访问。本文主要介绍通过xpath来定位并识别页面元素,达到灵活操作控件的目的。

    首先简单介绍一下xpath,xpath是在xml文档中查找信息的语言,可用来在xml文档中对元素和属性进行遍历。XPath 使用路径表达式来选取 XML 文档中的节点或者节点集。这些路径表达式和我们在常规的电脑文件系统中看到的表达式非常相似。Xpath的运用使得Watir自动化脚本更易于维护、更健壮。

    Watir对xpath的支持提供给测试人员一种识别页面元素更为有效的解决方案,从附图一中可以看出来:xpath是较多document对象所支持的识别属性。从原理上说,是把页面HTML转化成为XHTML,然后REXML来解析他,达到使用xpath表达式语言在文档结构中做查询定位的目的。并且,xpath可以操作html中的扩展tag,或者Watir不支持的tag操作,对于Watir扩展是很有效的,这使得xpath在Watir如何运用的研究变得有那么些意义。

    首先看一下xpath的简单语法以及在Watir中如何运用。

    示例节选代码如下:

    <div id=’firstone’><div>

    <table border=”0″ cellpadding=”0″ cellspacing=”0″>

    <tr>

    <td valign=”top”>

    <a title=”Furniture | Rugs, Carpets | Silver | More” href=”http://antiques.ebay.com/”>Antiques</a>

    <a title=”Paintings | Posters | Prints | More” href=”http://art.ebay.com/”>Art</a>

    <a title=”Drawing | Painting | Scrapbooking | Sewing | More” href=”http://crafts.ebay.com/” >Crafts</a>

    <a title=”DVD | Film | Laserdisc | VHS | More” href=”http://dvd.ebay.com/” >DVDs &amp; Movies</a>

    </td>

    </tr>

    </table>

    </div>

    <div>

    <input tabindex=”1″ id=”_nkw” foo=”bar”>

    <select name=”_sacat” size=”1″ tabindex=”2″>

    <option value=”See-All-Categories” selected=”selected”>All Categories</option>

    <option value=”20081″>Antiques</option><option value=”550″>Art</option>

    <option value=”2984″>Baby</option><option value=”267″>Books</option>

    <option value=”625″>Cameras &amp; Photo</option>

    <option value=”15032″>Cell Phones &amp; PDAs</option>

    <option value=”11450″>Clothing, Shoes &amp; Accessories</option>

    </select>

    <input type=”submit” value=”Search” tabindex=”3″/>

    <object name=”obj”></object>

    </div>

    </div>

    xpath常用路径表达式如下:

    // 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置

    . 选取当前节点

    .. 选取当前节点的父节点

    @ 指定属性

    示例一:使用属性定位识别元素

    //div[@id=’categories’]

    选取id为categories的div,返回所有符合条件节点

    Watir代码:

    @ie.div(:xpath,”//div[@id='categories']“)

    示例二:使用tag以及数组位置定位元素

    //a

    返回所有a子元素,无论它们在文档中的位置

    Watir代码:

    @ie.link(:xpath,”//a”)

    注:watir中使用该xpath自动返回元素集中的第一个元素,该代码与@ie.link(:xpath,”//a[1]”)效果相同。若需要识别其他位置元素,可使用数组方式定位识别,如:@ie.link(:xpath,”//a[2]”).click点击第二个tag为a的元素,@ie.link(:xpath,”//a[last()]”)点击最后一个tag为a的元素

    示例三:使用相对路径识别元素

    //a[1]/../../../../../../div[2]/input

    首先找到第一个a元素,一层层定位到根节点下第二个div,再选取input节点

    Watir代码:

    @ie.text_field(:xpath,”//a[1]/../../../../../../div[2]/input”).set ‘test’

    注:使用相对路径可以去除对id,name等属性的依赖,当页面元素缺乏类似属性来定位识别时,可以使用该方法进行控件操作

    示例四:根据模糊属性定位元素

    //a[contains(@href , ' crafts ')]

    定位到href属性值中含有crafts的a元素

    Watir代码

    @ie.link(:xpath,”//a[contains(@href,'crafts')]“).click

    示例五:属性不被Watir支持,但可通过xpath识别

    //select[@foo='bar')]

    当遇到有属性名为foo的情况,watir并不支持通过该属性来定位查询元素,但可通过xpath查询识别

    Watir代码:

    @ie.select_list(:xpath,”//select[@foo='bar')]“).select ‘Art’

    示例五:使用element_by_xpath扩展Watir不支持的控件

    Watir代码:

    puts @ie.element_by_xpath(”//object”).name

    注:某些页面标签并不被Watir所支持,比如object,可以通过这种方法获取元素

    还有很多其他用法这里不一一举例了,有兴趣的同学可以深入研究xpath语法,并灵活运用到我们的自动化脚本中。当然在使用当中也遇到一些问题,比如在Watir中使用xpath时,中文页面似乎经常会解析出问题,具体问题还在研究当中,也希望对此有了解的同学能给些方向和建议。

  • Watir Methods Supported by HTML Element

    2009-11-14 15:54:40

     Watir Methods Supported by HTML Element

    http://wiki.openqa.org/display/WTR/Watir+Methods+Supported+by+HTML+Element

  • 针对form的watir脚本

    2009-10-19 17:50:51

    require 'watir'
    require 'test/unit'

    class FormTest < Test::Unit::TestCase
      def setup
        
       @ie_site="http://members.shaw.ca/paul_rogers/watir_tests/formTest1.html"
        @ie=Watir::IE.new
        @ie.goto @ie_site
      end
      def teardown
        @ie.close
      end
      def test_ClickMe
        @ie.form(:name,"test1").button(:name,"b1").fire_event("onClick")
        assert(@ie.contains_text("PASS"),"This page should contain PASS,so test failed")
      end
      def test_DisableButton
        t=@ie.form(:name,"test1").button(:name,"b4").attribute_value("disabled")
        puts t
        assert(t==true,"Disabled Button should can not be disabled,so test failed")
      end
      def test_submit
        @ie.form(:name,"test2").button(:index,1).click
        assert("#{@ie.url}"=="http://members.shaw.ca/paul_rogers/watir_tests/pass2.html?","Submit button should goto \"http://members.shaw.ca/paul_rogers/watir_tests/pass2.html?\",so test failed")
        end
    end

  • File_field的watir脚本

    2009-10-19 17:07:56

    我觉得这个列子给的不好,没有太多可测试性的东西,╮(╯▽╰)╭,没有太多的新鲜感,不好玩
    require 'watir'
    require 'win32ole'
    require 'watir/WindowHelper'
    require 'test/unit'

    class FileUpdate < Test::Unit::TestCase
      
      def setup
        @ie_site="http://members.shaw.ca/paul_rogers/watir_tests/fileupload.html"
        @ie=Watir::IE.new
        @file1="C:\\ZQN_RUBY\\Experience\\fileupdate.rb"
        @file2="C:\\ZQN_RUBY\\Experience\\CheckBoxes.rb"
        @file3="C:\\ZQN_RUBY\\Experience\\JavascriptClick.rb"
       @ie.goto @ie_site
       
     end
     def teardown
       @ie.close
     end
     def test_view_field
       @ie.file_fields.each {|f| puts f.to_s}
       puts "================================================="
     end
     
     def test_file_1
       
        @ie.file_field(:name,"file1").click_no_wait
        sleep 5
        autoit=WIN32OLE.new("autoitx3.control")
        res=autoit.WinWait("Choose file","",1)
        ress=autoit.ControlFocus("Choose file","","Edit1")
        resss=autoit.ControlSetText("Choose file","","Edit1",@file1)
        b=autoit.ControlGetText("Choose file","","Edit1")
        assert(b==@file1,"Test Failed")
        puts b
        a=autoit.ControlClick("Choose file","Open","Button2")
        puts "================================================="
      end
       def test_file_2
      
        @ie.file_field(:id,"file2").click_no_wait
        sleep 5
        autoit=WIN32OLE.new("autoitx3.control")
        res=autoit.WinWait("Choose file","",1)
        ress=autoit.ControlFocus("Choose file","","Edit1")
        resss=autoit.ControlSetText("Choose file","","Edit1",@file2)
        b=autoit.ControlGetText("Choose file","","Edit1")
        assert(b==@file2,"Test Failed")
        puts b
        a=autoit.ControlClick("Choose file","Open","Button2")
        puts "================================================="
      end
      
      def test_disable_file
        disabled_file=@ie.file_field(:name,"disabled").attribute_value("disabled")
        puts disabled_file
        assert(disabled_file==true,"This file field should can not be used,so Test Failed")
        puts "================================================="
        end
      def test_file_index3
        @ie.file_field(:name=>"file1",:index=>"2").click_no_wait
        sleep 5
        autoit=WIN32OLE.new("autoitx3.control")
        res=autoit.WinWait("Choose file","",1)
        ress=autoit.ControlFocus("Choose file","","Edit1")
        resss=autoit.ControlSetText("Choose file","","Edit1",@file3)
        b=autoit.ControlGetText("Choose file","","Edit1")
        assert(b==@file3,"Test Failed")
        puts b
        a=autoit.ControlClick("Choose file","Open","Button2")
        
        @ie.button(:name,"upload").click
        assert(@ie.contains_text("PASS"),"Ie should contain PASS, so Test failed")
        puts "================================================="
      end
      
        
    end

  • 针对Div的watir脚本——2

    2009-10-19 14:23:31

    require 'watir'
    require 'test/unit'

    class DivTest < Test::Unit::TestCase
      def testDiv
        ie_site="http://members.shaw.ca/paul_rogers/watir_tests/div.html"
        ie=Watir::IE.new
        ie.goto ie_site
        
        div_1="This text is in a div with an id of div1 and title of test1"
        assert(div_1==ie.div(:id,"div1").text,"Div 1 is not right, test failed")
        
        div_2="This text is in a div with an id of div2"
        assert(div_2==ie.div(:id,"div2").text,"Div 2 is not right, test failed")
        
        for i in 1..10
        ie.div(:id,"div3").fire_event("onClick")
        assert("#{i}"==ie.text_field(:name,"text1").value,"Had been clicked #{i} times")
      end

      ie.div(:id,"buttons1").button(:name,"b1").fire_event("onClick")
      assert("button1"==ie.text_field(:name,"div_text1").value,"Text1 do not output \"button1\"")
      
     ie.div(:id,"buttons2").button(:name,"b2").fire_event("onCLick")
      assert("button2"==ie.text_field(:name,"div_text1").value,"Text1 do not output \"button1\"")
      
      ie.close
    end
    end

  • 针对Div的watir脚本

    2009-10-16 17:12:44

    require 'watir'
    require 'win32ole'
    require 'watir/WindowHelper'
    require 'test/unit'

    class CheckBox < Test::Unit::TestCase
      def test_Checkbox
        
        ie_site="http://members.shaw.ca/paul_rogers/watir_tests/cssTest.html"
        ie=Watir::IE.new
        ie.goto ie_site
        
        #ie.button(:name,"success").click
        ie.show_divs
        
        s_1=ie.div(:id,"successError").attribute_value("className")
        ie.button(:name,"success").click
        s_2=ie.div(:id,"successError").attribute_value("className")
        assert(s_2=="show","Success is not displayed, test failed")
        
        f_1=ie.div(:id,"failureError").attribute_value("className")
        ie.button(:name,"failure").click
        f_2=ie.div(:id,"failureError").attribute_value("className")
        assert(f_2=="show","Success is not displayed, test failed")
        ie.close
      end
    end

  • How do I deal with javascript popup’s?

    2009-10-16 14:46:30

    Q. How do I deal with javascript. popup’s?

    A. Invoke the autoit function library with the .click_no_wait method…
    You will need to install autoit. You can download it here, once installed you can call the function library using the win32OLE extension library.
    Example html:

    <html>
       <head>
       <script language="javascript">
          function msgbox (textstring) {
          alert (textstring) }
       </script>
       </head>
       <body id="test_00test_0107" onload="">
          <form>
             <input name="text1" type=text>
             <input name="submit" type=button value="show me" onclick="msgbox(form.text1.value)">
         </form>
      </body>
    </html>

    Example watir:

    require 'watir'
    require 'rubygems'
    require 'win32ole'
     
    autoit = WIN32OLE.new('AutoItX3.Control')   
    @b.goto('http://justaddwatir.com/watir/test_html/tc_0101_0200/test_0107.html')
    @b.text_field(:name,"text1").set("Justaddwatir")
    @b.button(:name,"submit").click_no_wait
    autoit.WinWaitActive("[Class:#32770]")    
    result =autoit.ControlClick("[Class:#32770]","","Button1")
    puts "successful click =1 unsuccessful =0, the result was "+ result

    In order for the autoit function to execute, you need to use the .click_no_wait method in watir before the autoit function. This is because once the pop up is presented, the focus comes off the IE window and the script. will pause. The .click_no_wait tells the script. to continue running regardless of what happens next.
    You may use the autoit window identifier to get the properties of the pop up and the button attributes.

  • 针对Table and CheckBox的watir脚本

    2009-10-15 16:06:37

    require 'watir'
    require 'win32ole'
    require 'watir/WindowHelper'
    require 'test/unit'

    class CheckBox < Test::Unit::TestCase
      def test_Checkbox
        
        ie_site="http://members.shaw.ca/paul_rogers/watir_tests/checkboxes1.html"
        ie=Watir::IE.new
        ie.goto ie_site
        
        ie.show_tables
        
        my_table=ie.table(:index,1)
        my_table.each {|row| p row.to_s}
        
        if ie.checkboxes[1].checked?
          puts "Failed"
          else
            puts "The checkbox1 is not checked in default"
          end
        
        #assert(ie.checkboxes[1].checked,"Test Failed")
        
        for i in 0..1
        ie.checkboxes[1].click
        if ie.checkboxes[1].checked?
          puts "The Checkbox 1 is checked"
          else
            puts "The Checkbox 1 is not checked"
          end
        end
        
        puts "===================================="
        
        if ie.checkboxes[2].disabled==true
          puts "Disabled's checkbox can not be used"
          else
            puts "Disabled's checkbox should not be used"
          end
          
          assert(ie.checkboxes[2].disabled==true,"Test Failed")
          
          puts "===================================="
          
          for i in 0..1
          if ie.checkboxes[3].checked?
            puts "The set checkbox is checked"
            ie.checkboxes[3].click
            puts "#{my_table[3][0].text}"
            else
              puts "Clicked the set checkboxes"
            end
          end
          
          assert(ie.checkboxes[3].disabled==false,"Checkbox 3 is not disabled,Test Failed")
          
          puts "===================================="
          
          my_table[4][0].text
          for i in 4..7
          if ie.checkboxes[i].checked?
            puts "The checkbox #{i} is checked in default"
            else
              puts "The checkbox #{i} is not checked in default"
            end
            assert(ie.checkboxes[i].value=="#{i-3}","Checkbox #{i}'s values do not equal to #{i-3}Test Failed")
          end
          
          assert(ie.checkboxes[8].disabled==true,"Checkbox 8 is not disable,Test Failed")
          
          puts "===================================="
          
          my_table[5].text
          assert(ie.button(:name,"foo").disabled==true,"Button foo is not disabled ,so Test Failed")
          ie.close
          
        end
      end
      
  • 针对Table的watir脚本

    2009-10-14 18:32:25

    require 'watir'
    require 'win32ole'
    require 'watir/WindowHelper'
    require 'test/unit'

    class Button1  < Test::Unit::TestCase
      def setup
        @ie_site="http://members.shaw.ca/paul_rogers/watir_tests/buttons1.html"
        @ie=Watir::IE.new
        @ie.goto @ie_site
      end
      def teardown
        @ie.close
      end
      def test_ClickMe
        
        @ie.button(:id,"b2").click_no_wait
        sleep 7
        
       
        if @ie.contains_text("PASS") 
          puts "Passed:test passed"
        end
        
        
        ie_body=@ie.text
        ie_text=ie_body[(@ie.title).length,ie_body.length]
        puts ie_text
        
        puts "======================================="
      end
      def test_DisableButton
        
        hidden=@ie.hidden(:id,"b5").value
        p hidden
        

         my_table=@ie.table(:index,1)
        my_table.each do |row|
          p row.text
        end
        puts "======================================="
      end
      def test_Submit
        
        @ie.form(:name,"test2").submit
        
        
        new_html="http://members.shaw.ca/paul_rogers/watir_tests/pass2.html?"
         if new_html==@ie.url
          puts "Test Passed"
          end
        
        puts "======================================="
        
      end
      def test_image
        
        @ie.button(:name,"sub3").click
        
         new_html="http://members.shaw.ca/paul_rogers/watir_tests/pass3.html?sub3.x=0&sub3.y=0"
         if new_html==@ie.url
          puts "Test Passed"
          end
        
        puts "======================================="
        end
      
    end

  • 针对popups类对话框的watir处理方法

    2009-10-13 18:29:19

    写了一个小脚本,如下
    require 'watir'
    require 'win32ole'
    require 'watir/WindowHelper'
    require 'test/unit'

    class TestJavascriptClick < Test::Unit::TestCase
      
      def setup
        
        @ie_site="http://members.shaw.ca/paul_rogers/watir_tests/"
        @ie=Watir::IE.new
        @ie.goto @ie_site
        @ie_site_1="http://members.shaw.ca/paul_rogers/watir_tests/JavascriptClick.htm"
        @ie.link(:href,@ie_site_1).click
      end
      def teardown
        @ie.close
        end
      def test_Alert_OK
        
        @ie.button(:id,"btnAlert").click_no_wait
        sleep(7)
        
        autoit=WIN32OLE.new("autoitx3.control")
        a=autoit.WinWait("Microsoft Internet Explorer","",1)
        b=autoit.ControlGetText("Microsoft Internet Explorer","","Static2")
        c=autoit.ControlClick("Microsoft Internet Explorer","OK","Button1")
        
        ie_contant_1="You pressed the Alert OK button!"
        assert_equal(ie_contant_1,@ie.text_field(:id,"testResult").value,"Yor pressed the Alert OK button!")
        
      end
      def test_Confirm_OK
        
        @ie.button(:id,"btnInformation").click_no_wait
        sleep(7)
        
        autoit=WIN32OLE.new("autoitx3.control")
        a=autoit.WinWait("Microsoft Internet Explorer","",1)
        b=autoit.ControlGetText("Microsoft Internet Explorer","","Static2")
        c=autoit.ControlClick("Microsoft Internet Explorer","OK","Button1")
        puts c
        
        ie_contant="You pressed the Confirm OK button!"
        assert_equal(ie_contant,@ie.text_field(:id,"testResult").value,"You pressed the Confirm OK button!")
      end
       def test_Confirm_Cancel
        
        @ie.button(:id,"btnInformation").click_no_wait
        sleep(7)
        
        autoit=WIN32OLE.new("autoitx3.control")
        a=autoit.WinWait("Microsoft Internet Explorer","",1)
        b=autoit.ControlGetText("Microsoft Internet Explorer","","Static2")
        c=autoit.ControlClick("Microsoft Internet Explorer","Cancel","Button2")
        puts c
        
        ie_contant="You pressed the Confirm Cancel button!"
        assert_equal(ie_contant,@ie.text_field(:id,"testResult").value,"You pressed the Confirm cancel button!")
      end
      
    end

        
372/2<12
Open Toolbar