Module: Awetestlib::Regression::Browser

Included in:
Runner
Defined in:
lib/awetestlib/regression/browser.rb

Overview

Methods to manage browser windows: open, close, attach, verify health, and clean up.

Browser collapse

Login collapse

Error Handling collapse

Backward compatible usages collapse

Instance Method Details

#attach_browser(browser, how, what, desc = '') ⇒ Watir::Browser

TODO:

Update to work with webdriver for IE.

Return a reference to a browser window. Used to attach a browser window to a variable which can then be passed to methods that require a browser parameter.

Examples:

mainwindow = open_browser('www.google.com')
click(mainwindow, :button, :id, 'an id string')  # click a button that opens another browser window
popup = attach_browser(mainwindow, :url, '[url of new window]')   #*or*
popup = attach_browser(mainwindow, :title, '[title of new window]')

Parameters:

  • browser (Watir::Browser)

    A reference to the current browser window.

  • how (Symbol)

    The element attribute used to identify the window: :title or :url.

  • what (String|Regexp)

    A string or a regular expression to be found in the how attribute that uniquely identifies the element.

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output

Returns:

  • (Watir::Browser)

    Internet Explorer



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/awetestlib/regression/browser.rb', line 135

def attach_browser(browser, how, what, desc = '')
  debug_to_log("Attaching browser window :#{how}=>'#{what}' #{desc}")
  uri_decoded_pattern = ::URI.encode(what.to_s.gsub('(?-mix:', '').gsub(')', ''))

  if $watir_script
    tmpbrowser = Watir::IE.attach(how, what)
    browser.visible = true
    if tmpbrowser
      tmpbrowser.visible = true
      tmpbrowser.speed   = :fast
    else
      raise "Browser window :#{how}=>'#{what}' has at least one doc not in completed ready state."
    end
  else
    browser.driver.switch_to.window(browser.driver.window_handles[0])
    browser.window(how, /#{uri_decoded_pattern}/).use
    tmpbrowser = browser
  end

  # case @browserAbbrev
  #   when 'IE'
  #     tmpbrowser      = Watir::IE.attach(how, what)
  #     browser.visible = true
  #     if tmpbrowser
  #       tmpbrowser.visible = true
  #       tmpbrowser.speed   = :fast
  #     else
  #       raise "Browser window :#{how}=>'#{what}' has at least one doc not in completed ready state."
  #     end
  #   when 'FF'
  #     #TODO: This may be dependent on Firefox version if webdriver doesn't support 3.6.17 and below
  #     browser.driver.switch_to.window(browser.driver.window_handles[0])
  #     browser.window(how, /#{uri_decoded_pattern}/).use
  #     tmpbrowser = browser
  #   when 'S'
  #     Watir::Safari.attach(how, what)
  #     tmpbrowser = browser
  #   when 'C', 'GC'
  #     browser.window(how, /#{uri_decoded_pattern}/).use
  #     tmpbrowser = browser
  # end


  debug_to_log("#{__method__}: tmpbrowser:#{tmpbrowser.inspect}")
  tmpbrowser
end

#attach_browser_by_url(browser, what, desc = '') ⇒ Watir::Browser Also known as: attach_browser_with_url

Returns a reference to a browser window using the window’s :url attribute. Calls attach_browser().

Examples:

mainwindow = open_browser('www.google.com')
click(mainwindow, :button, :id, 'an id string')  # click a button that opens another browser window
popup = attach_browser_by_url(mainwindow, '[url of new window]')

Parameters:

  • browser (Watir::Browser)

    A reference to the current browser window.

  • what (String, Regexp)

    The value in the targeted attribute that uniquely identifies the new window

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output

Returns:

  • (Watir::Browser)


1338
1339
1340
# File 'lib/awetestlib/regression/browser.rb', line 1338

def attach_browser_by_url(browser, what, desc = '')
  attach_browser(browser, :url, what, desc)
end

#attach_popup(browser, how, what, desc = '') ⇒ Watir::Browser

Returns a reference to a new browser window. Used to attach a new browser window to a variable which can then be passed to methods that require a browser parameter. Calls attach_browser().

Examples:

mainwindow = open_browser('www.google.com')
click(mainwindow, :button, :id, 'an id string')  # click a button that opens another browser window
popup = attach_popup(mainwindow, :url, '[url of new window]') *or*
popup = attach_popup(mainwindow, :title, '[title of new window]')

Parameters:

  • browser (Watir::Browser)

    A reference to the current browser window.

  • how (Symbol)

    The element attribute used to identify the window: :title or :url.

  • what (String, Regexp)

    A string or a regular expression to be found in the how attribute that uniquely identifies the element.

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output

Returns:

  • (Watir::Browser)

    The new browser window.



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/awetestlib/regression/browser.rb', line 195

def attach_popup(browser, how, what, desc = '')
  msg   = "Attach popup :#{how}=>'#{what}'. #{desc}"
  popup = attach_browser(browser, how, what, desc)
  sleep_for(1)
  debug_to_log("#{popup.inspect}")
  if is_browser?(popup)
    title = popup.title
    passed_to_log("#{msg} title='#{title}'")
    return popup
  else
    failed_to_log(msg)
  end
rescue
  failed_to_log("Unable to attach popup :#{how}=>'#{what}'. #{desc} '#{$!}' (#{__LINE__})")
end

#attach_popup_by_title(browser, what, desc = '') ⇒ Object

Returns a reference to a new browser window identified by its :title attribute. Used to attach a new browser window to a variable which can then be passed to methods that require a browser parameter. Calls attach_browser().

Parameters:

  • browser (Watir::Browser)

    A reference to the current browser window.

  • what (String, Regexp)

    The value in the targeted attribute that uniquely identifies the new window

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output



1347
1348
1349
# File 'lib/awetestlib/regression/browser.rb', line 1347

def attach_popup_by_title(browser, what, desc = '')
  attach_popup(browser, :title, what, desc)
end

#attach_popup_by_url(browser, what, desc = '') ⇒ Object Also known as: get_popup_with_url, attach_popup_with_url, attach_iepopup

Returns a reference to a new browser window identified by its :url attribute. Used to attach a new browser window to a variable which can then be passed to methods that require a browser parameter. Calls attach_browser().

Parameters:

  • browser (Watir::Browser)

    A reference to the current browser window.

  • what (String, Regexp)

    The value in the targeted attribute that uniquely identifies the new window

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output



1354
1355
1356
# File 'lib/awetestlib/regression/browser.rb', line 1354

def attach_popup_by_url(browser, what, desc = '')
  attach_popup(browser, :url, what, desc)
end

#bail_out(browser, lnbr, desc) ⇒ Object

Exit more or less gracefully from script when errors are too severe to continue. Normally not called in a test script or project library.

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • lnbr (Fixnum)

    Line number in calling script.

  • desc (String)

    Contains a message or description intended to appear in the log and/or report output

Raises:

  • (RuntimeError)


328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/awetestlib/regression/browser.rb', line 328

def bail_out(browser, lnbr, desc)
  ts  = Time.new
  msg = "Bailing out at util line #{lnbr} #{ts} " + desc
  puts "#{msg}"
  fatal_to_log(msg, lnbr)
  debug_to_log(dump_caller(lnbr))
  if is_browser?(browser)
    if @browserAbbrev == 'IE'
      hwnd = browser.hwnd
      kill_browser(hwnd, lnbr, browser)
      raise(RuntimeError, msg, caller)
    elsif @browserAbbrev == 'FF'
      debug_to_log("#{browser.inspect}")
      debug_to_log("#{browser.to_s}")
      raise(RuntimeError, msg, caller)
    end
  end
  @status = 'bailout'
  raise(RuntimeError, msg, caller)
end

#basic_auth(browser, user, password, url, bypass_validate = false) ⇒ Object

Logon to webpage using Basic Authorization type of logon. Uses AutoIt which checks the health of the browser, is skipped..

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • user (String)

    Login ID for the user.

  • password (String)

    Password for the user.

  • url (String)

    The URL to log on to.

  • bypass_validate (Boolean) (defaults to: false)

    When set to true, the call to validate(),



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/awetestlib/regression/browser.rb', line 270

def basic_auth(browser, user, password, url, bypass_validate = false)
  mark_testlevel("Basic Authorization Login", 0)

  message_to_report ("Login:    #{user}")
  message_to_report ("URL:      #{url}")
  message_to_report ("Password: #{password}")

  @login_title = "Connect to"

  a = Thread.new {
    browser.goto(url)
  }

  sleep_for(2)
  message_to_log("#{@login_title}...")

  if (@ai.WinWait(@login_title, "", 90) > 0)
    win_title = @ai.WinGetTitle(@login_title)
    debug_to_log("Basic Auth Login window appeared: '#{win_title}'")
    @ai.WinActivate(@login_title)
    @ai.ControlSend(@login_title, '', "[CLASS:Edit; INSTANCE:2]", '!u')
    @ai.ControlSend(@login_title, '', "[CLASS:Edit; INSTANCE:2]", user, 1)
    @ai.ControlSend(@login_title, '', "[CLASS:Edit; INSTANCE:3]", password.gsub(/!/, '{!}'), 1)
    @ai.ControlClick(@login_title, "", '[CLASS:Button; INSTANCE:1]')
  else
    debug_to_log("Basic Auth Login window did not appear.")
  end
  a.join

  validate(browser, @myName) unless bypass_validate

  message_to_report("URL: [#{browser.url}] User: [#{user}]")

end

#check_for_and_clear_other_browsersObject

Check for the presence of IE browser instances and close all that are found.



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/awetestlib/regression/browser.rb', line 361

def check_for_and_clear_other_browsers
  if @targetBrowser.abbrev == 'IE'
    debug_to_log("#{__method__}:")
    cnt1 = find_other_browsers
    cnt2 = Watir::IE.process_count
    debug_to_log("#{__method__}: cnt1: #{cnt1} cnt2: #{cnt2}")
    begin
      Watir::IE.each do |ie|
        pid = Watir::IE::Process.process_id_from_hwnd(ie.hwnd)
        debug_to_log("#{__method__}: Killing browser process: hwnd #{ie.hwnd} pid #{pid} title '#{ie.title}' (#{__LINE__})")
        do_taskkill(INFO, pid)
        sleep_for(10)
      end
        #Watir::IE.close_all()
    rescue
      debug_to_log("#{__method__}: #{$!}  (#{__LINE__})")
    end
    sleep(3)
    cnt1 = find_other_browsers
    cnt2 = Watir::IE.process_count
    if cnt1 > 0 or cnt2 > 0
      debug_to_log("#{__method__}:cnt1: #{cnt1} cnt2: #{cnt2}")
      begin
        Watir::IE.each do |ie|
          pid = Watir::IE::Process.process_id_from_hwnd(ie.hwnd)
          debug_to_log("#{__method__}: Killing browser process: hwnd #{ie.hwnd} pid #{pid} title '#{ie.title}' (#{__LINE__})")
          do_taskkill(INFO, pid)
          sleep_for(10)
        end
          #Watir::IE.close_all()
      rescue
        debug_to_log("#{__method__}:#{$!}  (#{__LINE__})")
      end
    end
  end
rescue
  error_to_log("#{__method__}: #{$!}  (#{__LINE__})\n#{Kernel.caller.to_yaml}")
end

#check_for_other_browsersFixnum

Check for the presence of IE browser instances.

Returns:

  • (Fixnum)

    The number of IE browser instances encountered.



352
353
354
355
356
357
358
# File 'lib/awetestlib/regression/browser.rb', line 352

def check_for_other_browsers
  cnt1 = find_other_browsers
  cnt2 = Watir::Process.count 'iexplore.exe'
  debug_to_log("check_for_other_browsers: cnt1: #{cnt1} cnt2: #{cnt2}")
rescue
  error_to_log("#{$!}  (#{__LINE__})\n#{Kernel.caller.to_yaml}")
end

#close_modal(browser, title = "", button = "OK", text = '', side = 'primary', wait = WAIT) ⇒ Object

Close a modal dialog. with Internet Explorer (regular expressions will fail). Use enough of beginning of the text string, in quotes, to assure the correct modal is found. This will give best portability.

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • title (String) (defaults to: "")

    The title of the window to be closed. Matched from beginning of string.

  • button (String) (defaults to: "OK")

    The display name of the button to be clicked.

  • text (String) (defaults to: '')

    The text of the window to be closed. Matched from beginning of string in Windows

  • side (String) (defaults to: 'primary')

    A string identifying which mouse button to click.

  • wait (Fixnum) (defaults to: WAIT)

    Number of seconds to wait for the popup to be seen.



721
722
723
724
725
726
727
728
729
730
731
732
# File 'lib/awetestlib/regression/browser.rb', line 721

def close_modal(browser, title="", button="OK", text='', side = 'primary', wait = WAIT)
  case @targetBrowser.abbrev
    when 'IE'
      close_modal_ie(browser, title, button, text, side, wait)
    when 'FF'
      close_modal_ff(browser, title, button, text, side)
    when 'S'
      close_modal_s
    when 'C', 'GC'
      close_modal_c(browser, title)
  end
end

#close_modal_c(browser, url) ⇒ Object

Close a Chrome modal popup by :url.



736
737
738
# File 'lib/awetestlib/regression/browser.rb', line 736

def close_modal_c(browser, url)
  browser.window(:url, url).close
end

#close_modal_ff(browser, title = "", button = nil, text = '', side = '') ⇒ Boolean

Close a Firefox modal popup by its title.

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • title (String) (defaults to: "")

    The title of the window to be closed. Matched from beginning of string.

  • button (String) (defaults to: nil)

    The display name of the button to be clicked.

  • text (String) (defaults to: '')

    The text of the window to be closed. Matched from beginning of string.

  • side (String) (defaults to: '')

    A string identifying which mouse button to click.

Returns:

  • (Boolean)

    True if the modal is successfully closed.



843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
# File 'lib/awetestlib/regression/browser.rb', line 843

def close_modal_ff(browser, title="", button=nil, text='', side='')
  title = translate_popup_title(title)
  msg   = "Modal dialog (popup): title=#{title} button='#{button}' text='#{text}' side='#{side}':"
  modal = browser.modal_dialog(:timeout => WAIT)
  if modal.exists?
    modal_text = modal.text
    if text.length > 0
      if modal_text =~ /#{text}/
        passed_to_log("#{msg} appeared with match on '#{text}'.")
      else
        failed_to_log("#{msg} appeared but did not match '#{text}' ('#{modal_text}).")
      end
    else
      passed_to_log("#{msg} appeared.")
    end
    if button
      modal.click_button(button)
    else
      modal.close
    end
    if modal.exists?
      failed_to_log("#{msg} close failed. (#{__LINE__})")
    else
      passed_to_log("#{msg} closed successfully.")
      true
    end
  else
    failed_to_log("#{msg} did not appear after #{WAIT} seconds. (#{__LINE__})")
  end
rescue
  failed_to_log("#{msg} Unable to validate modal popup: '#{$!}'. (#{__LINE__})")
end

#close_modal_ie(browser, title = "", button = "OK", text = '', side = 'primary', wait = WAIT, desc = '', quiet = false) ⇒ Object

Close an IE modal popup by its title using AutoItX3. Windows only.

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • title (String) (defaults to: "")

    The title of the window to be closed. Matched from beginning of string.

  • button (String) (defaults to: "OK")

    The display name of the button to be clicked.

  • text (String) (defaults to: '')

    The text of the window to be closed. Matched from beginning of string. Do not use regular expression

  • side (String) (defaults to: 'primary')

    A string identifying which mouse button to click.

  • wait (Fixnum) (defaults to: WAIT)

    Number of seconds to wait for the popup to be seen.

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output

  • quiet (Boolean) (defaults to: false)

    If true, fewer messages and pass/fail validations are logged.



757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
# File 'lib/awetestlib/regression/browser.rb', line 757

def close_modal_ie(browser, title="", button="OK", text='', side = 'primary', wait = WAIT, desc = '', quiet = false)
  #TODO needs simplifying, incorporating text verification, and debug code cleaned up
  title = translate_popup_title(title)
  msg   = "Modal window (popup) '#{title}'"
  if @ai.WinWait(title, text, wait) > 0
    myHandle = @ai.WinGetHandle(title, text)
    if myHandle.length > 0
      debug_to_log("hwnd: #{myHandle.inspect}")
      passed_to_log("#{msg} appeared.") unless quiet
      window_handle = "[HANDLE:#{myHandle}]"
      sleep_for(0.5)
      @ai.WinActivate(window_handle)
      if @ai.WinActive(window_handle) > 0
        debug_to_log("#{msg} activated.")
        controlHandle = @ai.ControlGetHandle(title, '', "[CLASS:Button; TEXT:#{button}]")
        if not controlHandle.length > 0
          button        = "&#{button}"
          controlHandle = @ai.ControlGetHandle(title, '', "[CLASS:Button; TEXT:#{button}]")
        end
        debug_to_log("Handle for button '#{button}': [#{controlHandle}]")
        debug_to_log("#{msg} focus gained.")
        if @ai.ControlClick(title, '', "[CLASS:Button; TEXT:#{button}]") > 0
          passed_to_log("#{msg} #{side} click on '[CLASS:Button; TEXT:#{button}]' successful.")
          sleep_for(0.5)
          if @ai.WinExists(window_handle) > 0
            debug_to_log("#{msg} close popup failed on click '#{button}'. Trying WinClose. (#{__LINE__})")
            @ai.WinClose(title, text)
            if @ai.WinExists(window_handle) > 0
              debug_to_log("#{msg} close popup failed with WinClose(#{window_handle}). (#{__LINE__})")
              @ai.WinKill(window_handle)
              if @ai.WinExists(window_handle) > 0
                debug_to_log("#{msg} close popup failed with WinKill(#{window_handle}). (#{__LINE__})")
              else
                debug_to_log("#{msg} closed successfully with WinKill(#{window_handle}).")
              end
            else
              debug_to_log("#{msg} closed successfully with WinClose(#{window_handle}).")
            end
          else
            passed_to_log("#{msg} closed successfully.")
          end
        else
          failed_to_log("#{msg} #{side} click on '[CLASS:Button; TEXT:#{button}]' failed. (#{window_handle}) (#{__LINE__})")
        end
      else
        failed_to_log("#{msg} Unable to activate (#{window_handle}) (#{__LINE__})")
      end
    else
      failed_to_log("#{msg} did not appear after #{wait} seconds. (#{window_handle}) (#{__LINE__})")
    end
  else
    failed_to_log("#{msg} did not appear after #{wait} seconds.(#{window_handle}) (#{__LINE__})")
  end
rescue
  failed_to_log("Close popup title=#{title} failed: '#{$!}' (#{__LINE__})")
end

#close_modal_sObject

Close a Safari modal popup by closing the frontmost Safari dialog. Mac OSX only.



742
743
744
745
746
# File 'lib/awetestlib/regression/browser.rb', line 742

def close_modal_s
  # simply closes the frontmost Safari dialog
  Appscript.app("Safari").activate
  Appscript.app("System Events").processes["Safari"].key_code(52)
end

#close_new_window_popup(popup) ⇒ Object

Close a browser popup window. Does not apply to modal popups.

Parameters:

  • popup (Watir::Browser)

    Reference to the popup to be closed



576
577
578
579
580
581
582
583
# File 'lib/awetestlib/regression/browser.rb', line 576

def close_new_window_popup(popup)
  if is_browser?(popup)
    url = popup.url
    debug_to_log("Closing popup '#{url}' ")
    popup.close

  end
end

#close_panel_by_text(browser, panel, what = 'Close') ⇒ Object

Close an HTML panel or division by clicking a link within it identified by the :text value of the link.

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • panel (Watir::Browser)

    Reference to the panel (usually a div element) to be closed



588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
# File 'lib/awetestlib/regression/browser.rb', line 588

def close_panel_by_text(browser, panel, what = 'Close')
  if validate(browser, @myName, __LINE__)
    if @browserAbbrev == 'IE'
      panel.link(:text, what).click!
    elsif $USE_FIREWATIR
      begin
        panel.link(:text, what).click
      rescue => e
        unless rescue_me(e, __method__, rescue_me_command(:link, :id, what, :click), "#{panel.class}")
          raise e
        end
      end
    else
      panel.link(:text, what).click(:wait => false)
    end
    sleep_for(1)
    if validate(browser, @myName, __LINE__)
      passed_to_log("Panel '#{what}' (by :text) closed.")
      true
    end
  else
    failed_to_log("Panel '#{strg}' (by :text) still open.")
  end
rescue
  failed_to_log("Click on '#{strg}'(by :text) failed: '#{$!}' (#{__LINE__})")
end

#close_popup(title = '', button = 'OK', text = '', side = 'primary', wait = WAIT, desc = '', quiet = false) ⇒ Object Also known as: close_popup_validate_text

Deprecated.

Use close_modal.

Close an Internet Explorer modal popup by its title. Calls close_modal_ie. Windows only.

Parameters:

  • title (String) (defaults to: '')

    The title of the window to be closed. Matched from beginning of string.

  • button (String) (defaults to: 'OK')

    The display name of the button to be clicked.

  • text (String) (defaults to: '')

    The text of the window to be closed. Matched from beginning of string.

  • side (String) (defaults to: 'primary')

    A string identifying which mouse button to click.

  • wait (Fixnum) (defaults to: WAIT)

    Number of seconds to wait for the popup to be seen.

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output

  • quiet (Boolean) (defaults to: false)

    If true, fewer messages and pass/fail validations are logged.



828
829
830
831
832
# File 'lib/awetestlib/regression/browser.rb', line 828

def close_popup(title = '', button = 'OK', text = '', side = 'primary',
                wait = WAIT, desc = '', quiet = false)
  debug_to_log("#{__method__} begin")
  close_modal_ie(@myBrowser, title, button, text, side, wait, desc, quiet)
end

#close_popup_by_button_title(popup, what, desc = '') ⇒ Boolean

Close a popup browser window (non-modal) by clicking on a link with :title what. This method does not check to make sure the popup is actually closed.

Parameters:

  • popup (Watir::Browser)

    A reference to the current popup browser window.

  • what (String, Regexp)

    The value in the targeted attribute that uniquely identifies the new window

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output

Returns:

  • (Boolean)

    True if the click is successful.



1368
1369
1370
# File 'lib/awetestlib/regression/browser.rb', line 1368

def close_popup_by_button_title(popup, what, desc = '')
  click(popup, :link, :title, what, desc)
end

#close_popup_by_text(popup, what = 'Close', desc = '') ⇒ Object

Close an browser window (popup) by clicking a link within it identified by the :text value of the link.

Parameters:

  • popup (Watir::Browser)

    A reference to the browser window or container element to be closed.

  • what (String) (defaults to: 'Close')

    Uniquely identify the :link element within the popup by the value in its :text attribute.

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output



687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
# File 'lib/awetestlib/regression/browser.rb', line 687

def close_popup_by_text(popup, what = 'Close', desc = '')
  count = 0
  url   = popup.url
  if validate(popup, @myName, __LINE__)
    count = string_count_in_string(popup.text, what)
    if count > 0
      begin
        popup.link(:text, what).click
      rescue => e
        unless rescue_me(e, __method__, rescue_me_command(:link, :text, what, :click), "#{popup.class}")
          raise e
        end
      end
      passed_to_log("Popup #{url} closed by clicking link with text '#{what}'. #{desc}")
      true
    else
      failed_to_log("Link :text=>'#{what}' for popup #{url} not found. #{desc}")
    end
  end
rescue
  failed_to_log("Close popup #{url} with click link :text+>'#{what}' failed: '#{$!}' (#{__LINE__})")
  debug_to_log("#{strg} appears #{count} times in popup.text.")
  raise
end

#close_window_by_title(browser, title, desc = '', text = '') ⇒ Object

Close a browser window identified by its title. Uses AutoIt. Windows only.

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • title (String)

    The title of the window to be closed. Matched from beginning of string.

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output

  • text (String) (defaults to: '')

    (optional) The text of the window to be closed. Matched from beginning of string.



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# File 'lib/awetestlib/regression/browser.rb', line 484

def close_window_by_title(browser, title, desc = '', text = '')
  msg = "Window '#{title}':"
  if @ai.WinWait(title, text, WAIT) > 0
    passed_to_log("#{msg} appeared. #{desc}")
    myHandle  = @ai.WinGetHandle(title, text)
    full_text = @ai.WinGetText(title)
    debug_to_log("#{msg} hwnd: #{myHandle.inspect}")
    debug_to_log("#{msg} title: '#{title}' text: '#{full_text}'")
    if @ai.WinClose(title, text) > 0
      passed_to_log("#{msg} closed successfully. #{desc}")
    else
      failed_to_log("#{msg} close failed. (#{__LINE__}) #{desc}")
    end
  else
    failed_to_log("#{msg} did not appear after #{WAIT} seconds. (#{__LINE__}) #{desc}")
  end
rescue
  failed_to_log("#{msg}: Unable to close: '#{$!}'. (#{__LINE__}) #{desc}")
end

#find_other_browsersObject

Locate and close instances of IE browsers



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/awetestlib/regression/browser.rb', line 212

def find_other_browsers
  cnt = 0
  if @targetBrowser.abbrev == 'IE'
    Watir::IE.each do |ie|
      debug_to_log("#{ie.inspect}")
      ie.close()
      cnt = cnt + 1
    end
  end
  debug_to_log("Found #{cnt} IE browser(s).")
  return cnt
rescue
  error_to_log("#{$!}  (#{__LINE__})\n#{Kernel.caller.to_yaml}", __LINE__)
  return 0
end

#find_popup(browser, how, what, desc = '') ⇒ Watir::IE

Return a reference to an IE browser window based on one of its attributes.

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • how (Symbol)

    The element attribute used to identify the window: :url, :title, or :hwnd.

  • what (String, Regexp)

    A string or a regular expression to be found in the how attribute that uniquely identifies the element.

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output

Returns:



967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
# File 'lib/awetestlib/regression/browser.rb', line 967

def find_popup(browser, how, what, desc = '')
  msg   = "Find popup :#{how}=>'#{what}'. #{desc}"
  popup = Watir::IE.find(how, what) # TODO: too browser specific
  sleep_for(1)
  debug_to_log("#{popup.inspect}")
  if is_browser?(popup)
    #      title = popup.title
    passed_to_log(msg)
    return popup
  else
    failed_to_log(msg)
  end
rescue
  failed_to_log("Unable to find popup :#{how}=>'#{what}'. #{desc} '#{$!}' (#{__LINE__})")
end

#go_to_url(browser, url = nil) ⇒ Boolean

Instruct browser to navigate to a specific URL and the instance variable @myURL will be set to this value.

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • url (String) (defaults to: nil)

    When provided, the browser will go to this url.

Returns:

  • (Boolean)

    True when navigation to url succeeds.



111
112
113
114
115
116
117
118
119
120
# File 'lib/awetestlib/regression/browser.rb', line 111

def go_to_url(browser, url = nil)
  if url
    @myURL = url
  end
  message_to_report("URL: #{@myURL}")
  browser.goto(@myURL)
  true
rescue
  fatal_to_log("Unable to navigate to '#{@myURL}': '#{$!}'")
end

#go_to_wd_url(browser, url) ⇒ Object Also known as: goto_wd_url

Note:

webdriver specific - still work in progress



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/awetestlib/regression/browser.rb', line 21

def go_to_wd_url(browser, url)

  Watir::Browser.class_eval do
    def goto(uri)
      uri = "http://#{uri}" unless uri =~ URI.regexp
      @driver.navigate.to uri
      run_checkers
    end
  end
  browser.goto(url)

  #in basic_auth1 edit:
  #a = Thread.new {
  #    goto_wd_url(browser, @myURL)
  #  }

end

#handle_popup(title, text = '', button = 'OK', side = 'primary', wait = WAIT, desc = '') ⇒ Boolean

Wait for a modal popup to appear and then close it. Used when modal popup in response to browser action is intermittent or unpredictable.

Parameters:

  • title (String)

    The title of the window to be closed. Matched from beginning of string.

  • text (String) (defaults to: '')

    The text of the window to be closed. Matched from beginning of string.

  • button (String) (defaults to: 'OK')

    The display name of the button to be clicked.

  • side (String) (defaults to: 'primary')

    A string identifying which mouse button to click.

  • wait (Fixnum) (defaults to: WAIT)

    Number of seconds to wait for the popup to be seen.

  • desc (String) (defaults to: '')

    Contains a message or description intended to appear in the log and/or report output

Returns:

  • (Boolean)

    True if the modal is successfully closed.



885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
# File 'lib/awetestlib/regression/browser.rb', line 885

def handle_popup(title, text = '', button= 'OK', side = 'primary', wait = WAIT, desc = '')
  title = translate_popup_title(title)
  msg   = "'#{title}'"
  if text.length > 0
    msg << " with text '#{text}'"
  end
  @ai.Opt("WinSearchChildren", 1) # match title from start, forcing default

  if button and button.length > 0
    if button =~ /ok|yes/i
      id = '1'
    else
      id = '2'
    end
  else
    id = ''
  end

  if @ai.WinWait(title, '', wait) > 0
    myHandle      = @ai.WinGetHandle(title, '')
    window_handle = "[HANDLE:#{myHandle}]"
    full_text     = @ai.WinGetText(window_handle)
    debug_to_log("Found popup handle:'#{myHandle}', title:'#{title}', text:'#{full_text}'")

    controlHandle = @ai.ControlGetHandle(window_handle, '', "[CLASS:Button; TEXT:#{button}]")
    if not controlHandle
    #        button        = "&#{button}"
      controlHandle = @ai.ControlGetHandle(window_handle, '', "[CLASS:Button; TEXT:&#{button}]")
    end

    if text.length > 0
      if full_text =~ /#{text}/
        passed_to_log("Found popup handle:'#{myHandle}', title:'#{title}', text includes '#{text}'. #{desc}")
      else
        failed_to_log("Found popup handle:'#{myHandle}', title:'#{title}', text does not include '#{text}'. Closing it. #{desc}")
      end
    end

    @ai.WinActivate(window_handle, '')
    @ai.ControlClick(window_handle, '', id, side)
    if @ai.WinExists(title, '') > 0
      debug_to_log("#{msg} @ai.ControlClick on '#{button}' (ID:#{id}) with handle '#{window_handle}' failed to close window. Trying title.")
      @ai.ControlClick(title, '', id, side)
      if @ai.WinExists(title, '') > 0
        debug_to_report("#{msg} @ai.ControlClick on '#{button}' (ID:#{id}) with title '#{title}' failed to close window.  Forcing closed.")
        @ai.WinClose(title, '')
        if @ai.WinExists(title, '') > 0
          debug_to_report("#{msg} @ai.WinClose on title '#{title}' failed to close window.  Killing window.")
          @ai.WinKill(title, '')
          if @ai.WinExists(title, '') > 0
            failed_to_log("#{msg} @ai.WinKill on title '#{title}' failed to close window")
          else
            passed_to_log("Killed: popup handle:'#{myHandle}', title:'#{title}'. #{desc}")
            true
          end
        else
          passed_to_log("Forced closed: popup handle:'#{myHandle}', title:'#{title}'. #{desc}")
          true
        end
      else
        passed_to_log("Closed on '#{button}': popup handle:'#{myHandle}', title:'#{title}'. #{desc}")
        true
      end
    else
      passed_to_log("Closed on '#{button}': popup handle:'#{myHandle}', title:'#{title}'. #{desc}")
      true
    end

  else
    failed_to_log("#{msg} did not appear after #{wait} seconds. #{desc} (#{__LINE__})")
  end
rescue
  failed_to_log("Unable to handle popup #{msg}: '#{$!}' #{desc} (#{__LINE__})")

end

#is_browser?(browser) ⇒ Boolean Also known as: is_browser

Confirm that the object passed in browser is actually a Browser object.

Parameters:

  • browser (Watir::Browser)

    A reference to the window or container element to be tested.

Returns:

  • (Boolean)


985
986
987
988
989
990
991
992
993
994
995
996
997
# File 'lib/awetestlib/regression/browser.rb', line 985

def is_browser?(browser)
  myClass = browser.class.to_s
  case @targetBrowser.abbrev
    when 'IE'
      myClass =~ /Watir::IE|Watir::Browser/i
    when 'FF'
      myClass =~ /Watir::Browser/i
    when 'S'
      myClass =~ /Watir::Browser/i
    when 'C'
      myClass =~ /Watir::Browser/i
  end
end

#kill_browser(hwnd, lnbr, browser = nil, doflag = false) ⇒ Object

Force browser instance to close, one way or the other. Instance is identified by hwnd, the Windows OS handle for the process.

Parameters:

  • hwnd (String)

    The value for the window handle for the browser process.

  • lnbr (Fixnum)

    Line number in calling script.

  • browser (Watir::Browser) (defaults to: nil)

    A reference to the browser window or container element to be closed.



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/awetestlib/regression/browser.rb', line 405

def kill_browser(hwnd, lnbr, browser = nil, doflag = false)
 # TODO Firefox
 logit = false
 if @browserAbbrev == 'FF'
   if is_browser?(browser) # and browser.url.length > 1
     logit = true
     here  = __LINE__
     url   = browser.url
     #capture_screen(browser, Time.new.to_f) if @screenCaptureOn
     browser.close if url.length > 0
     @status = 'killbrowser'
     fatal_to_log("Kill browser called from line #{lnbr}")
   end
 elsif hwnd
   pid = Watir::IE::Process.process_id_from_hwnd(hwnd)
   if pid and pid > 0 and pid < 538976288
     if browser.exists?
       here  = __LINE__
       logit = true
       url   = browser.url
       #capture_screen(browser, Time.new.to_f) if @screenCaptureOn
       browser.close
       sleep(2)
       if browser.exists?
         do_taskkill(FATAL, pid)
       end
       @status = 'killbrowser'
     end
   end
   if logit
      debug_to_log("#{@browserName} window hwnd #{hwnd} pid #{pid} #{url} (#{here})")
      fatal_to_log("Kill browser called from line #{lnbr}")
    end
  end
end

#login(browser, user, password) ⇒ Boolean

Simple login method

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • user (String)

    Login ID for the user.

  • password (String)

    Password for the user.

Returns:

  • (Boolean)

    True if login succeeds.



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/awetestlib/regression/browser.rb', line 237

def (browser, user, password)
  #TODO: Needs to be more flexible about finding login id and password textfields
  #TODO: Parameterize url and remove references to environment
  myURL  = @myAppEnv.url
  runenv = @myAppEnv.nodename
  message_tolog("URL: #{myURL}") if @myAppEnv
  message_tolog("Beginning login: User: #{user} Environment: #{@myAppEnv.nodename}") if @myAppEnv
  if validate(browser, @myName, __LINE__)
    browser.goto(@myAppEnv.url)
    if validate(browser, @myName)
      set_textfield_by_name(browser, 'loginId', user)
      set_textfield_by_name(browser, 'password', password)
      click_button_by_value(browser, 'Login')
      if validate(browser, @myName)
        passed_to_log("Login successful.")
        true
      end
    else
      failed_to_log("Unable to login to application: '#{$!}'")
      #screen_capture( "#{@myRoot}/screens/#{myName}_#{@runid}_#{__LINE__.to_s}_#{Time.new.to_f.to_s}.jpg")
    end
  end
rescue
  failed_to_log("Unable to login to application: '#{$!}'")
end

#logout(browser, where = @myName, lnbr = __LINE__) ⇒ Object

Closes main browser session. Misnamed. Usually used at end of script to shut down browser.



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# File 'lib/awetestlib/regression/browser.rb', line 505

def logout(browser, where = @myName, lnbr = __LINE__)
  #TODO Firewatir 1.6.5 does not implement .exists for FireWatir::Firefox class
  debug_to_log("Logging out in #{where} at line #{lnbr}.", lnbr, true)
  debug_to_log("#{__method__}: browser: #{browser.inspect} (#{__LINE__})")

  if ['FF', 'S'].include?(@browserAbbrev) || browser.exists?
    case @browserAbbrev
      when 'FF'
        if is_browser?(browser)
          url   = browser.url
          title = browser.title
          debug_to_log("#{__method__}: Firefox browser url: [#{url}]")
          debug_to_log("#{__method__}: Firefox browser title: [#{title}]")
          debug_to_log("#{__method__}: Closing browser: #{where} (#{lnbr})")
          if url and url.length > 1
            browser.close
          else
            browser = FireWatir::Firefox.attach(:title, title)
            browser.close
          end

        end
      when 'IE'
        hwnd = browser.hwnd
        pid  = Watir::IE::Process.process_id_from_hwnd(hwnd)
        debug_to_log("#{__method__}: Closing browser: hwnd #{hwnd} pid #{pid} #{where} (#{lnbr}) (#{__LINE__})")
        browser.close
        if browser.exists? and pid > 0 and pid < 538976288 # value of uninitialized memory location
          debug_to_log("Retry close browser: hwnd #{hwnd} pid #{pid} #{where} #{lnbr} (#{__LINE__})")
          browser.close
        end
        if browser.exists? and pid > 0 and pid < 538976288 # value of uninitialized memory location
          kill_browser(browser.hwnd, __LINE__, browser)
        end
      when 'S'
        if is_browser?(browser)
          url   = browser.url
          title = browser.title
          debug_to_log("Safari browser url: [#{url}]")
          debug_to_log("Safari browser title: [#{title}]")
          debug_to_log("Closing browser: #{where} (#{lnbr})")
          close_modal_s # to close any leftover modal dialogs
          browser.close
        end
      when 'C', 'GC'
        if is_browser?(browser)
          url   = browser.url
          title = browser.title
          debug_to_log("Chrome browser url: [#{url}]")
          debug_to_log("Chrome browser title: [#{title}]")
          debug_to_log("Closing browser: #{where} (#{lnbr})")
          if url and url.length > 1
            browser.close
            #else
            #browser = FireWatir::Firefox.attach(:title, title)
            #browser.close
          end

        end
      else
        raise "Unsupported browser: '#{@browserAbbrev}'"
    end
  end
  #  rescue => e
  #    if not e.is_a?(Vapir::WindowGoneException)
  #      raise e
  #    end
end

Use enabled_popup and winclicker to determine if there is an active modal popup. Useful only when no wait action has been invoked.

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • button (String) (defaults to: nil)

    The visible name of the button to be clicked to close the popup.

Returns:

  • (String)

    containing the window handle of the closed modal popup.



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# File 'lib/awetestlib/regression/browser.rb', line 450

def modal_exists?(browser, button = nil)
  rtrn = nil
  if @browserAbbrev == 'IE'
    Timeout::timeout(2) do
      begin
        if browser.enabled_popup
          hwnd = browser.enabled_popup(5)
          debug_to_log("Modal popup with handle #{hwnd} found. (#{__LINE__})")
          wc = WinClicker.new
          wc.makeWindowActive(hwnd)
          rtrn = wc.getWindowTitle(hwnd)
          if button
            wc.clickWindowsButton_hWnd(hwnd, button)
          end
          wc = nil
        end
      rescue Timeout::Error
        debug_to_log("No Modal popup found. (#{__LINE__})")
        return rtrn
      end
      return rtrn
    end
    rtrn
  else
    rtrn
  end
end

#open_browser(url = nil) ⇒ Watir::Browser

Open a browser based on the command line parameters that identify the browser and version to use for the test.

Examples:

browser = open_browser('www.google.com')

Parameters:

  • url (String, Regexp) (defaults to: nil)

    When provided, the browser will go to this url.

Returns:

  • (Watir::Browser)


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/awetestlib/regression/browser.rb', line 47

def open_browser(url = nil)
  message_to_report("Opening browser: #{@targetBrowser.name}")
  case @targetBrowser.abbrev
    when 'IE'
      @myBrowser = open_ie
      if @myBrowser.class.to_s == "Watir::IE"
        @myHwnd = @myBrowser.hwnd
      end
    when 'FF'
      @myBrowser = open_ff_for_version
    when 'S'
      aBrowser = Watir::Browser.new :safari
      @myBrowser = aBrowser
    when 'C', 'GC'
      @myBrowser = open_chrome
    else
      raise "Unsupported browser: #{@targetBrowser.name}"
  end
  if url
    go_to_url(@myBrowser, url)
  end
  @myBrowser
end

#open_chromeWatir::Browser

Open GC (Google Chrome) browser instance.

Returns:

  • (Watir::Browser)

    Browser is Google Chrome.



102
103
104
# File 'lib/awetestlib/regression/browser.rb', line 102

def open_chrome
  browser = Watir::Browser.new(:chrome)
end

#open_ffFirewatir::Browser

Open FF (Firefox) browser instance under FireWatir.

Returns:

  • (Firewatir::Browser)


95
96
97
98
# File 'lib/awetestlib/regression/browser.rb', line 95

def open_ff
  # Watir::Browser.default = 'firefox'
  browser = Watir::Browser.new :firefox
end

#open_ff_for_version(version = @targetVersion) ⇒ Watir::Browser, Firewatir::Browser

Open FF (Firefox) browser instance. Returns Firewatir::Browser if target browser is Firefox version less than 4.0

Parameters:

  • version (Fixnum) (defaults to: @targetVersion)

    A number designating the version of the browser to be opened.

Returns:

  • (Watir::Browser, Firewatir::Browser)


89
90
91
# File 'lib/awetestlib/regression/browser.rb', line 89

def open_ff_for_version(version = @targetVersion)
  browser = Watir::Browser.new :firefox
end

#open_ieWatir::Browser

Open IE (Internet Explorer) browser instance. If global variable $watir_script is set to true in the first line of the script, classic Watir will be used to drive the browser, otherwise Watir Webdriver will be used.

Returns:

  • (Watir::Browser)


76
77
78
79
80
81
82
83
# File 'lib/awetestlib/regression/browser.rb', line 76

def open_ie
  if $watir_script
    browser = Watir::IE.new
  else
    browser = Watir::Browser.new :ie
  end
  browser
end
Deprecated.

Open and attach a browser popup window where the link to open it and its title contain the same string.



1126
1127
1128
1129
1130
1131
1132
1133
# File 'lib/awetestlib/regression/browser.rb', line 1126

def open_popup_through_link_title(browser, title, pattern, name)
  click_title(browser, title)
  #TODO need some kind of wait for process here
  sleep_for 2
  attach_popup_by_url(browser, pattern, name)
rescue
  failed_to_log("Unable to open popup '#{name}': '#{$!}' (#{__LINE__})")
end

#token_auth(browser, role, token, id = 'token_pass') ⇒ Object

Provide an authorization token or passcode in a specified text field element identified by its :id attribute.

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • role (String)

    Usually a user role designation (‘Administrator’, ‘User’, etc.)

  • token (String)

    Authentification token required by logon process.

  • id (String/Regexp) (defaults to: 'token_pass')

    Value of the :id attribute of the text field that will receive the token.



310
311
312
313
314
315
316
# File 'lib/awetestlib/regression/browser.rb', line 310

def token_auth(browser, role, token, id = 'token_pass')
  set_textfield_by_id(browser, id, token)
  click_button_by_value(browser, 'Continue')
  if validate_text(browser, 'The requested page requires authentication\.\s*Please enter your Passcode below', nil, true)
    bail_out(browser, __LINE__, "Token authorization failed on '#{token}'")
  end
end

#translate_popup_title(title) ⇒ Object

Translate window title supplied in title to a title appropriate for the targeted browser and version actually being run. Used primarily for handling of modal popups and dialogs. This allows cross-browser compatibility for handling modal popups and other windows accessed by titlt.

Parameters:

  • title (String)

    The title of the window to be closed.



1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
# File 'lib/awetestlib/regression/browser.rb', line 1006

def translate_popup_title(title)
  new_title = title
  case @browserAbbrev
    when 'IE'
      if @browserVersion
        case @browserVersion
          when '8.0'
            case title
              when "Microsoft Internet Explorer"
                new_title = "Message from webpage"
              when "The page at"
                new_title = "Message from webpage"
            end
          when '7.0'
            case title
              when "Message from webpage"
                new_title = "Microsoft Internet Explorer"
              when "The page at"
                new_title = "Windows Internet Explorer"
            end
          when '6.0'
            case title
              when "Message from webpage"
                new_title = "Microsoft Internet Explorer"
              when "The page at"
                new_title = "Microsoft Internet Explorer"
            end
          else
            case title
              when "Microsoft Internet Explorer"
                new_title = "Message from webpage"
              when "The page at"
                new_title = "Message from webpage"
            end
        end
      else
        case title
          when "Microsoft Internet Explorer"
            new_title = "Message from webpage"
          when "The page at"
            new_title = "Message from webpage"
        end
      end
    when 'FF'
      case title
        when 'File Download'
          new_title = 'Opening'
        when "Microsoft Internet Explorer"
          new_title = 'The page at'
        when "Message from webpage"
          new_title = 'The page at'
      end
    when 'C'
      case title
        when 'File Download'
          new_title = 'Save As'
        when "Microsoft Internet Explorer"
          new_title = 'The page at'
        when "Message from webpage"
          new_title = 'The page at'
      end
  end
  new_title
end

#validate(browser, file_name = @myName, lnbr = "#{__LINE__}", dbg = false) ⇒ Boolean Also known as: validate_browser

Verifies health of the browser. Looks for common http and system errors that are unrecoverable and attempts to gracefully bail out of the script. Calls rescue_me() when trying to capture the text to filter out known false errors and handle container elements that don’t respond to the .text method.

Parameters:

  • browser (Watir::Browser)

    A reference to the browser window or container element to be tested.

  • file_name (String) (defaults to: @myName)

    The file name of the executing script.

  • lnbr (Fixnum) (defaults to: "#{__LINE__}")

    Contains a message or description intended to appear in the log and/or report output

  • dbg (Boolean) (defaults to: false)

    If set to true additional debug messages are written to the log.

Returns:

  • (Boolean)

    True if no error conditions have been encountered.



1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
# File 'lib/awetestlib/regression/browser.rb', line 1147

def validate(browser, file_name = @myName, lnbr = "#{__LINE__}", dbg = false)
  debug_to_log("#{__method__} begin") if dbg
  msg  = ''
  myOK = true
  if not browser
    msg  = "#{file_name}----browser is nil object. (#{lnbr})"
    myOK = false
  elsif not browser.class.to_s =~ /Watir/
    msg = "#{file_name}----not a Watir object. (#{lnbr})"
    debug_to_log(browser.inspect)
    myOK = false

  else
    if browser.respond_to?(:url)
      if not browser.url == @currentURL
        @currentURL = browser.url
        debug_to_log("Current URL: [#{@currentURL}]")
        #        mark_testlevel( "Current URL: [#{@currentURL}]", 1 )
      end
    end

    if @capture_js_errors
      if browser.respond_to?(:status)
        if browser.status.downcase =~ /errors? on page/ and
            not browser.status.downcase.include?('Waiting for')
          capture_js_error(browser)
        end
      end
    end

    begin
      browser_text = browser.text.downcase
    rescue => e
      unless rescue_me(e, __method__, "browser.text.downcase", "#{browser.class}", browser)
        debug_to_log("browser.text.downcase in #{__method__} #{browser.class}")
        debug_to_log("#{get_callers}")
        raise e
      else
        return true
      end
    end

    if browser_text
      if browser_text.match(/unrecognized error condition has occurred/i)
        msg  = "#{file_name}----Unrecognized Exception occurred. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/cannot find server or dns error/i)
        msg  = "#{file_name}----Cannot find server error or DNS error. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/the rpc server is unavailable/i)
        msg  = "#{file_name}----RPC server unavailable. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/404 not found/i) or
          browser_text.match(/the page you were looking for does\s*n[o']t exist/i)
        msg  = "#{file_name}----RFC 2068 HTTP/1.1: 404 URI Not Found. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/we're sorry, but something went wrong/i) or
          browser_text.match(/http status 500/i)
        msg  = "#{file_name}----RFC 2068 HTTP/1.1: 500 Internal Server Error. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/internet explorer cannot display the webpage/i)
        msg  = "#{file_name}----Probably RFC 2068 HTTP/1.1: 500 Internal Server Error. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/503.*service unavailable/i)
        msg  = "#{file_name}----RFC 2068 HTTP/1.1: 503 Service Unavailable. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/java.lang.NullPointerException/i)
        msg  = "#{file_name}----java.lang.NullPointerException. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/due to unscheduled maintenance/i)
        msg  = "#{file_name}----Due to unscheduled maintenance. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/network\s+error\s*(.+)$/i)
        $1.chomp!
        msg  = "#{file_name}----Network Error #{$1}. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/warning: page has expired/i)
        msg  = "#{file_name}----Page using information from form has expired. Not automatically resubmitted. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/no backend server available/i)
        msg  = "#{file_name}----Cannot Reach Server (#{lnbr})"
        myOK = false

      elsif browser_text.match(/sign on\s+.+\s+unsuccessful/i)
        msg  = "#{file_name}----Invalid Id or Password (#{lnbr})"
        myOK = false

      elsif browser_text.match(/you are not authorized/i)
        msg  = "#{file_name}----Not authorized to view this page. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/too many incorrect login attempts have been made/i)
        msg  = "#{file_name}----Invalid Id or Password. Too many tries. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/system error\.\s+an error has occurred/i)
        msg  = "#{file_name}----System Error. An error has occurred. Please try again or call the Help Line for assistance. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/Internal Server failure,\s+NSAPI plugin/i)
        msg  = "#{file_name}----Internal Server failure, NSAPI plugin. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/Error Page/i)
        msg  = "#{file_name}----Error Page. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/The website cannot display the page/i)
        msg  = "#{file_name}----HTTP 500. (#{lnbr})"
        myOK = false

        #        elsif browser_text.match(/Insufficient Data/i)
        #          msg  = "#{file_name}----Insufficient Data. (#{lnbr})"
        #          myOK = false

      elsif browser_text.match(/The timeout period elapsed/i)
        msg  = "#{file_name}----Time out period elapsed or server not responding. (#{lnbr})"
        myOK = false

      elsif browser_text.match(/Unexpected\s+errors*\s+occur+ed\.\s+(?:-+)\s+(.+)/i)
        msg = "#{file_name}----Unexpected errors occurred. #{$2.slice(0, 120)} (#{lnbr})"
        if not browser_text.match(/close the window and try again/i)
          myOK = false
        else
          debug_to_log("#{msg}")
        end

      elsif browser_text.match(/Server Error in (.+) Application\.\s+(?:-+)\s+(.+)/i)
        msg  = "#{file_name}----Server Error in #{1} Application. #{$2.slice(0, 100)} (#{lnbr})"
        myOK = false

      elsif browser_text.match(/Server Error in (.+) Application\./i)
        msg  = "#{file_name}----Server Error in #{1} Application. '#{browser_text.slice(0, 250)}...' (#{lnbr})"
        myOK = false

      elsif browser_text.match(/An error has occur+ed\. Please contact support/i)
        msg  = "#{file_name}----An error has occurred. Please contact support (#{lnbr})"
        myOK = false

      end
    else
      debug_to_log("browser.text returned nil")
    end
  end

  if not myOK
    msg << " (#{browser.url})"
    puts msg
    debug_to_log(browser.inspect)
    debug_to_log(browser.text)
    fatal_to_log(msg, lnbr)
    raise(RuntimeError, msg, caller)
  else
    debug_to_log("#{__method__} returning OK") if dbg
    return myOK
  end

rescue
  errmsg = $!
  if errmsg and errmsg.match(msg)
    errmsg = ''
  end
  bail_out(browser, lnbr, "#{msg} #{errmsg}")
end