Class: SelWeT::Unit

Inherits:
Test::Unit::TestCase
  • Object
show all
Includes:
SelWeT
Defined in:
lib/selwet.rb

Overview

end

Defined Under Namespace

Classes: ArgumentValueError, ConnectionRefusedError, ElementIsMissingError, ElementIsNotDisplayedError, Error, PageLoadError

Class Method Summary collapse

Class Method Details

.alert_cancelObject

See Also:



77
78
79
# File 'lib/selwet.rb', line 77

def alert_cancel
  @@driver.switch_to.alert.dismiss
end

.alert_okObject

See Also:



94
95
96
# File 'lib/selwet.rb', line 94

def alert_ok
  @@driver.switch_to.alert.accept
end

.check_element(selector, num = nil) ⇒ Object

Raises:



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/selwet.rb', line 135

def check_element selector, num = nil
  raise(ArgumentValueError, "Invalid value \"#{selector}\" of argument 'selector'") unless selector.class == String
  raise(ArgumentValueError, "Invalid value \"#{num}\" of argument 'num'") unless [FalseClass, TrueClass, NilClass].include?(num.class)
  wait = Selenium::WebDriver::Wait.new(:timeout => @@timewait)
  begin
    wait.until { @@driver.find_element(:css => selector) }
  rescue Selenium::WebDriver::Error::TimeOutError
    return false
  end
  if num
    return true, @@driver.find_elements(:css => selector).size
  else
    return true
  end
end

.checked?(selector) ⇒ Boolean

Returns:

  • (Boolean)

Raises:



112
113
114
115
116
117
118
119
120
121
122
# File 'lib/selwet.rb', line 112

def checked? selector
  raise(ArgumentValueError, "Invalid value of argument 'selector'") unless selector.class == String
  if check_element(selector) 
    element = @@driver.find_element(:css => selector)
    raise "Element #{selector} is not a checkbox/radio" unless ['radio', 'checkbox'].include?(element.tag_name)
    raise "Element #{selector} not displayed" unless element.displayed?
    return element.selected?.inspect
  else
    raise(ElementIsMissingError, "Element #{selector} is missing")
  end
end

.clear_cacheObject

Очистить кэш браузера



151
152
153
# File 'lib/selwet.rb', line 151

def clear_cache
  @@driver.manage.delete_all_cookies
end

.click(selector, desc = nil) ⇒ Object

Raises:



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/selwet.rb', line 167

def click selector, desc = nil
  raise(ArgumentValueError, "Invalid value \"#{selector}\" of argument 'selector'") unless selector.class == String
  raise(ArgumentValueError, "Invalid value \"#{desc}\" of  argument 'desc'") unless [String, NilClass].include?(desc.class)
  i = 0
      if (check_element(selector))
          begin    
              element = @@driver.find_element(:css => selector)
              raise(ElementIsNotDisplayedError, "Element \"#{selector}\" is not displayed") unless displayed?(selector)
              element.click
              if (@@browser == :chrome)
                  sleep 1
              end
              wait = Selenium::WebDriver::Wait.new
              wait.until { @@driver.execute_script("return window.onunload = function(){return window.onload}; ") }
          rescue ElementIsNotDisplayedError
              i = i + 1
              if i <= 2 
                  sleep @@timewait
                  retry
              else
                  raise(ElementIsNotDisplayedError, "Element \"#{selector}\" is not displayed") unless displayed?(selector)
          end
      end
   end
end

.close_window(num) ⇒ Object

Закрыть окно с номером num. Окна нумируются в порядке их открытия. Нумирация начинается с 0. Если необходимо закрыть текущее окно, то перед закрытием необходимо переключиться на другое окно. После закрытия окна происходить их переупорядочивание. Так, например, если было закрыто первое окно (num = 0), то второе окно станет первым (было num = 1, стало num = 0) и т.д.

Examples:

context "Example" do

  should 'TODO something' do
    Unit.close_window 2
    ... 

Parameters:

  • num (Fixnum)

    номер окна

Raises:

  • (ArgumentError)

See Also:



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/selwet.rb', line 203

def close_window num
  raise ArgumentError.new("Invalid value \"#{num}\" of argument 'num'") unless num.class == Fixnum
  update_window_handles
  raise 'Invalid window number' unless @@handles.keys.include?(num.to_s)
  current = @@handles.key(@@driver.window_handle)
  raise 'Can not close active window' if num.to_s == current
  @@driver.switch_to.window @@handles[num.to_s]
  @@driver.close
  @@handles.delete_if { |key, value| key == num.to_s }
  @@driver.switch_to.window @@handles[current]
  new_handles = {}
  num = 0
  @@handles.keys.sort.each do |key|
    new_handles[num.to_s] = @@handles[key]
    num += 1
  end
  @@handles = new_handles
end

.displayed?(selector) ⇒ Boolean

Returns:

  • (Boolean)

Raises:



232
233
234
235
236
237
238
239
# File 'lib/selwet.rb', line 232

def displayed? selector
  raise(ArgumentValueError, "Invalid value \"#{selector}\" of argument 'selector'") unless selector.class == String
  if check_element(selector)
    return @@driver.find_element(:css => selector).displayed?
  else
    raise(ElementIsMissingError, "Element #{selector} is missing")
  end
end

.fill_in(selector, value) ⇒ Object

Raises:



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/selwet.rb', line 252

def fill_in selector, value
  raise(ArgumentValueError, "Invalid value \"#{selector}\" of argument 'selector'") unless selector.class == String
  raise(ArgumentValueError, "Invalid value \"#{value}\" of argument 'value'") unless value.class == String
  i = 0
  if check_element(selector)
      begin
          element = @@driver.find_element(:css => selector)
          raise(ElementIsNotDisplayedError, "Element \"#{selector}\" is not displayed") unless displayed?(selector)
          begin
              @@driver.action.move_to(element).perform
              element.clear
          rescue
      #skip this
          end
          element.send_keys(value)
      rescue ElementIsNotDisplayedError
          i = i + 1
          if i <= 2
              sleep @@timewait
              retry
          else
              raise(ElementIsNotDisplayedError, "Element \"#{selector}\" is not displayed") unless displayed?(selector)
          end
      end
  
  else
      raise(ElementIsMissingError, "Element #{selector} is missing")
  end      
end

.get_attr(selector, attr, all = nil) ⇒ Object

Raises:



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/selwet.rb', line 313

def get_attr selector, attr, all = nil
  raise(ArgumentValueError, "Invalid value \"#{selector}\" of argument 'selector'") unless selector.class == String
  raise(ArgumentValueError, "Invalid value \"#{attr}\" of argument 'attr'") unless attr.class == String
  if check_element(selector)
    unless all
      return @@driver.find_element(:css => selector).attribute(attr)
    else
      elems = @@driver.find_elements(:css => selector)
      array = []
      elems.each do |elem|
        array.push elem.attribute(attr)
      end
      return array
    end
  else
    raise(ElementIsMissingError, "Element #{selector} is missing")
  end
end

.get_locationObject



339
340
341
# File 'lib/selwet.rb', line 339

def get_location
  @@driver.current_url
end

.get_tag(selector, all = nil) ⇒ Object

Raises:



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/selwet.rb', line 354

def get_tag selector, all = nil
  raise(ArgumentValueError, "Invalid value \"#{selector}\" of argument 'selector'") unless selector.class == String
  if check_element(selector)
    unless all
      return @@driver.find_element(:css => selector).tag_name
    else
      elems = @@driver.find_elements(:css => selector)
      array = []
      elems.each do |elem|
        array.push elem.tag_name
      end
      return array    
    end
  else
    raise(ElementIsMissingError, "Element #{selector} is missing")
  end
end

.get_text(selector, all = nil) ⇒ Object

Raises:



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/selwet.rb', line 382

def get_text selector, all = nil
  raise(ArgumentValueError, "Invalid value \"#{selector}\" of argument 'selector'") unless selector.class == String
  raise(ArgumentValueError, "Invalid value \"#{all}\" of argument 'all'") unless [NilClass, FalseClass, TrueClass].include?(all.class)
  if check_element(selector)
    unless all
      return @@driver.find_element(:css => selector).text
    else
      elems = @@driver.find_elements(:css => selector)
      array = []
      elems.each do |elem|
        array.push elem.text
      end
      return array
    end
  else
    raise(ElementIsMissingError, "Element #{selector} is missing")
  end
end

.go_to(url) ⇒ Object

Raises:

See Also:



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'lib/selwet.rb', line 410

def go_to url
    raise(ArgumentValueError, "Invalid value of argument 'selector'") unless url.class == String
    wait = Selenium::WebDriver::Wait.new
    i = 0
    begin            
        @@driver.navigate.to url
        if (@@browser == :chrome)
            sleep 1
        end
        wait.until { @@driver.execute_script("return window.onload = function(){}; ") }
        i = i + 1 
    rescue Exception => e 
        if i <= 2 
            @@driver.navigate.refresh
            retry
        else 
            raise(PageLoadError, "Page #{url} didn't load within PageLoadTimeOut time")
        end
    end
end

.hover_over_element(selector) ⇒ Object

Raises:



290
291
292
293
294
295
296
297
298
# File 'lib/selwet.rb', line 290

def hover_over_element selector
  raise(ArgumentValueError, "Invalid value \"#{selector}\" of argument 'selector'") unless selector.class == String
  if check_element(selector)
    element = @@driver.find_element(:css => selector)
    @@driver.action.move_to(element).perform
  else
    raise(ElementIsMissingError, "Element #{selector} is missing")
  end
end

.opened?(num) ⇒ Boolean

assert_equal false, Unit.opened?(2), ‘Window not closed!’

Returns:

  • (Boolean)

Raises:



439
440
441
442
443
# File 'lib/selwet.rb', line 439

def opened? num
  raise(ArgumentValueError, "Invalid value of argument 'num'") unless num.class == Fixnum
  update_window_handles
  return @@handles.keys.include?(num.to_s)
end

.press_key(key, state = nil) ⇒ Object

Parameters:

  • state (Symbol) (defaults to: nil)

    состояние. Допустимые значения: :down(нажать), :up(отпустить). Если параметр не будет указан, то будет сделано обычное нажатие.

Raises:



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/selwet.rb', line 451

def press_key key, state = nil
  unless [
          :null,:cancel,:help,:backspace,:tab,:clear,:return,:enter,:shift,:left_shift,:control,:left_control,
          :alt,:left_alt,:pause,:escape,:space,:page_up,:page_down,:end,:home,:left,:arrow_left,:up,:arrow_up,
          :right,:arrow_right,:down,:arrow_down,:insert,:delete,:semicolon,:equals,:numpad0,:numpad1,:numpad2,
          :numpad3,:numpad4,:numpad5,:numpad6,:numpad7,:numpad8,:numpad9,:multiply,:add,:separator,:subtract,
          :decimal,:divide,:f1,:f2,:f3,:f4,:f5,:f6,:f7,:f8,:f9,:f10,:f11,:f12,:meta,:command
         ].include? key
    raise(ArgumentValueError, "Invalid value \"#{key}\" of argument 'key'") unless /^[A-Za-z0-9]$/ === key.to_s
  end
  raise(ArgumentValueError, "Invalid value \"#{state}\" of argument 'state'") unless [:up, :down, nil].include?(state)
  case state
  when :up
    @@driver.action.key_up(key).perform
  when :down
    @@driver.action.key_down(key).perform
  when nil
    @@driver.action.send_keys(key).perform
  end
end

.refreshObject

Обновить текущее окно



472
473
474
# File 'lib/selwet.rb', line 472

def refresh
  @@driver.navigate.refresh
end

.screenshot(filename) ⇒ Object

Parameters:

  • filename (String)

    имя файла

Raises:



477
478
479
480
# File 'lib/selwet.rb', line 477

def screenshot filename
  raise(ArgumentValueError, "Invalid value \"#{filename}\" of argument 'filename'") unless filename.class == String
  @@driver.save_screenshot("./"+filename+".png") 
end

.set_browser(browser) ⇒ Object

Raises:



487
488
489
490
# File 'lib/selwet.rb', line 487

def set_browser browser
  raise(ArgumentValueError, "Invalid value \"#{browser}\" of argument 'browser'") unless [:firefox, :chrome, :ie, :safari, :phantomjs].include? browser
  @@browser = browser
end

.set_pageload_timewait(sec) ⇒ Object

Raises:

See Also:



557
558
559
560
# File 'lib/selwet.rb', line 557

def set_pageload_timewait sec
  raise(ArgumentValueError, "Invalid value \"#{sec}\" of argument 'sec'") unless sec.class == Fixnum
  @@pageload_timewait = sec
end

.set_select_items(selector, items) ⇒ Object

Raises:



501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# File 'lib/selwet.rb', line 501

def set_select_items selector, items
  raise(ArgumentValueError, "Invalid value \"#{selector}\" of argument 'selector'") unless selector.class == String
  raise(ArgumentValueError, "Invalid value \"#{items}\" of argument 'items'") unless [Array, Fixnum].include?(items.class)
  if check_element(selector)
    select = Selenium::WebDriver::Support::Select.new(@@driver.find_element(:css => selector))
    raise(ArgumentValueError, "Invalid value \"#{items}\" of argument 'items' for not multiple select") if items.class == Array and !select.multiple?
    if select.multiple?
      select.deselect_all
      if items.class == Array
        items.each do |item|
          raise(ArgumentValueError, "Invalid value \"#{items}\" of argument 'items'") unless item.class == Fixnum
          select.select_by(:index, item)
        end
      else
        select.select_by(:index, items)
      end
    else
      select.select_by(:index, items)
    end
  else
    raise(ElementIsMissingError, "Element #{selector} is missing")
  end 
end

.set_server_url(url) ⇒ Object

Raises:



532
533
534
535
# File 'lib/selwet.rb', line 532

def set_server_url url
  raise(ArgumentValueError, "Invalid value \"#{url}\" of argument 'url'") unless url.class == String
  @@server_url = url
end

.set_timewait(sec) ⇒ Object



544
545
546
547
# File 'lib/selwet.rb', line 544

def set_timewait sec
  raise(ArgumentValueError, "Invalid value \"#{sec}\" of argument 'sec'") unless sec.class == Fixnum
  @@timewait = sec
end

.shutdownObject

Закрывает браузер после выполнения всех тестов. Внутренний метод. Выполняется автоматически.



564
565
566
567
568
569
# File 'lib/selwet.rb', line 564

def shutdown
  if @@driver
    @@driver.close
    @@driver.quit
  end
end

.startupObject

Выполняется автоматически непосредственно перед запуском тестов.



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# File 'lib/selwet.rb', line 572

def startup
  begin
      @@driver = nil
      url = nil
      unless @@server_url
          puts 'URL not specified! Local browser will be used.'
      else
          url = @@server_url
      end
      if @@browser.nil?
          raise ArgumentError.new('Browser not specified!')
      end
      if url
          if @@browser == :phantomjs
              @@driver = Selenium::WebDriver.for(:remote, :url => url)
          else
              @@driver = Selenium::WebDriver.for(:remote, :desired_capabilities => @@browser, :url => url)
          end
      else
          @@driver = Selenium::WebDriver.for @@browser
      end

      if (@@driver == nil)
          raise("Can't create driver for #{@@browser.to_s}")
      end

  rescue Errno::ECONNREFUSED
      raise(ConnectionRefusedError, "Connection refused on #{@@server_url}\n\n") 
  end

  @@driver.manage.timeouts.implicit_wait = @@timewait
  @@driver.manage.timeouts.script_timeout = @@timewait
  @@driver.manage.timeouts.page_load = @@pageload_timewait
  @@driver.manage.window.maximize
  @@handles["0"] = @@driver.window_handle
end

.switch_to_window(num) ⇒ Object

Raises:

See Also:



619
620
621
622
623
624
# File 'lib/selwet.rb', line 619

def switch_to_window num
  raise(ArgumentValueError, "Invalid value \"#{selector}\" of argument 'num'") unless num.class == Fixnum
  update_window_handles
  raise "Invalid window number" unless @@handles.keys.include?(num.to_s)
  @@driver.switch_to.window @@handles[num.to_s]
end

.to_frame(selector) ⇒ Object

Raises:

See Also:



635
636
637
638
639
640
641
642
643
644
# File 'lib/selwet.rb', line 635

def to_frame selector
  raise(ArgumentValueError, "Invalid value \"#{selector}\" of argument 'selector'") unless selector.class == String
  if check_element(selector)
    element = @@driver.find_element(:css => selector)
    @@driver.action.move_to(element).perform
    @@driver.switch_to.frame element
  else
    raise(ElementIsMissingError, "Element #{selector} is missing")
  end
end

.to_pageObject

See Also:



655
656
657
# File 'lib/selwet.rb', line 655

def to_page
  @@driver.switch_to.default_content 
end

.update_window_handlesObject

Обновить список handle. Внутренняя функция.



659
660
661
662
663
664
665
666
667
668
669
670
# File 'lib/selwet.rb', line 659

def update_window_handles
  new_handles = @@driver.window_handles - @@handles.values
  old_handles = @@handles.values - @@driver.window_handles
  @@handles.delete_if{ |key, value| old_handles.include? value }
  unless new_handles.empty?
    num = @@handles.keys.max.to_i+1
    new_handles.each do |handle|
      @@handles[num.to_s] = handle
      num += 1
    end
  end
end

.window_titleString

Returns заголовок.

Returns:

  • (String)

    заголовок



673
674
675
# File 'lib/selwet.rb', line 673

def window_title
  @@driver.title
end