Module: RWebSpec::Mechanize::Utils

Included in:
LoadTestHelper
Defined in:
lib/rwebspec-mechanize/test_utils.rb

Constant Summary collapse

WORDS =
%w(alias consequatur aut perferendis sit voluptatem accusantium doloremque aperiam eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo aspernatur aut odit aut fugit sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt neque dolorem ipsum quia dolor sit amet consectetur adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem ut enim ad minima veniam quis nostrum exercitationem ullam corporis nemo enim ipsam voluptatem quia voluptas sit suscipit laboriosam nisi ut aliquid ex ea commodi consequatur quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae et iusto odio dignissimos ducimus qui blanditiis praesentium laudantium totam rem voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident sed ut perspiciatis unde omnis iste natus error similique sunt in culpa qui officia deserunt mollitia animi id est laborum et dolorum fuga et harum quidem rerum facilis est et expedita distinctio nam libero tempore cum soluta nobis est eligendi optio cumque nihil impedit quo porro quisquam est qui minus id quod maxime placeat facere possimus omnis voluptas assumenda est omnis dolor repellendus temporibus autem quibusdam et aut consequatur vel illum qui dolorem eum fugiat quo voluptas nulla pariatur at vero eos et accusamus officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae itaque earum rerum hic tenetur a sapiente delectus ut aut reiciendis voluptatibus maiores doloribus asperiores repellat)

Instance Method Summary collapse

Instance Method Details

#allow(&block) ⇒ Object Also known as: shall_allow, allowing

Does not provide real function, other than make enhancing test syntax

Example:

allow { click_button('Register') }


164
165
166
# File 'lib/rwebspec-mechanize/test_utils.rb', line 164

def allow(& block)
  yield
end

#days_before(days, format = nil) ⇒ Object



223
224
225
226
# File 'lib/rwebspec-mechanize/test_utils.rb', line 223

def days_before(days, format = nil)        
  return nil if !(days.instance_of?(Fixnum))
  format_date(Time.now - days * 24 * 3600, date_format(format))
end

#days_from_now(days, format = nil) ⇒ Object Also known as: days_after



232
233
234
235
# File 'lib/rwebspec-mechanize/test_utils.rb', line 232

def days_from_now(days, format = nil)
  return nil if !(days.instance_of?(Fixnum))
  format_date(Time.now + days * 24 * 3600, date_format(format))
end

#failsafe(&block) ⇒ Object Also known as: fail_safe

try operation, ignore if errors occur

Example:

failsafe { click_link("Logout") }  # try logout, but it still OK if not being able to (already logout))


175
176
177
178
179
180
# File 'lib/rwebspec-mechanize/test_utils.rb', line 175

def failsafe(& block)
  begin
    yield
  rescue =>e
  end
end

#interpret_value(value) ⇒ Object

If an array or range is passed, a random value will be selected to match. All other values are simply returned.



321
322
323
324
325
326
327
# File 'lib/rwebspec-mechanize/test_utils.rb', line 321

def interpret_value(value)
  case value
  when Array then value.rand
  when Range then value_in_range(value)
  else value
  end
end

#on(page) {|page| ... } ⇒ Object

Example:

on @page do |i|
  i.enter_text('btn1')
  i.click_button('btn1')
end

Yields:

  • (page)


140
141
142
# File 'lib/rwebspec-mechanize/test_utils.rb', line 140

def on(page, & block)
  yield page
end

#paragraphs(total) ⇒ Object

Generate a given number of paragraphs. If a range is passed, it will generate a random number of paragraphs within that range.



313
314
315
316
317
# File 'lib/rwebspec-mechanize/test_utils.rb', line 313

def paragraphs(total)
  (1..interpret_value(total)).map do
    sentences(3..8).capitalize
  end.join("\n\n")
end

#random_booleanObject



248
249
250
# File 'lib/rwebspec-mechanize/test_utils.rb', line 248

def random_boolean
  return random_number(0, 1) == 1
end

#random_char(lowercase = true) ⇒ Object



252
253
254
255
256
257
258
# File 'lib/rwebspec-mechanize/test_utils.rb', line 252

def random_char(lowercase = true)
  if lowercase
    sprintf("%c", random_number(97, 122))
  else
    sprintf("%c", random_number(65, 90))
  end
end

#random_digitObject



260
261
262
# File 'lib/rwebspec-mechanize/test_utils.rb', line 260

def random_digit()
  sprintf("%c", random_number(48, 57))
end

#random_number(min, max) ⇒ Object

return a random number >= min, but <= max



244
245
246
# File 'lib/rwebspec-mechanize/test_utils.rb', line 244

def random_number(min, max)
  rand(max-min+1)+min
end

#random_str(length, lowercase = true) ⇒ Object



264
265
266
267
268
269
270
# File 'lib/rwebspec-mechanize/test_utils.rb', line 264

def random_str(length, lowercase = true)
  randomStr = ""
  length.times {
    randomStr += random_char(lowercase)
  }
  randomStr
end

#random_string_in(arr) ⇒ Object Also known as: random_string_in_collection

Return a random string in a rangeof pre-defined strings



273
274
275
276
277
# File 'lib/rwebspec-mechanize/test_utils.rb', line 273

def random_string_in(arr)
  return nil if arr.empty?
  index = random_number(0, arr.length-1)
  arr[index]
end

#repeat_try(num_tries = $testwise_polling_timeout || 30, interval = $testwise_polling_interval || 1, &block) ⇒ Object

Try the operation up to specified times, and sleep given interval (in seconds) Error will be ignored until timeout Example

repeat_try(3, 2) { click_button('Search' } # 3 times, 6 seconds in total
repeat_try { click_button('Search' } # using default 5 tries, 2 second interval


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/rwebspec-mechanize/test_utils.rb', line 55

def repeat_try(num_tries = $testwise_polling_timeout || 30, interval = $testwise_polling_interval || 1, & block)
  num_tries ||= 1
  (num_tries - 1).times do |num|
    begin
      yield
      return
    rescue => e
      # puts "debug: #{num} failed: #{e}"
      sleep interval
    end
  end

  # last try, throw error if still fails
  begin
    yield
  rescue => e
    raise e.to_s + " after trying #{num_tries} times every #{interval} seconds"
  end
  yield
end

#sentences(total) ⇒ Object

Generate a given number of sentences. If a range is passed, it will generate a random number of sentences within that range.



305
306
307
308
309
# File 'lib/rwebspec-mechanize/test_utils.rb', line 305

def sentences(total)
  (1..interpret_value(total)).map do
    words(5..20).capitalize
  end.join('. ')
end

#shall_not_allow(&block) ⇒ Object Also known as: do_not_allow

fail the test if user can perform the operation

Example:

shall_not_allow { 1/0 }


148
149
150
151
152
153
154
155
156
# File 'lib/rwebspec-mechanize/test_utils.rb', line 148

def shall_not_allow(& block)
  operation_performed_ok = false
  begin
    yield
    operation_performed_ok = true
  rescue
  end
  raise "Operation shall not be allowed" if operation_performed_ok
end

#symbol_to_sequence(symb) ⇒ Object

Convert :first to 1, :second to 2, and so on…



79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/rwebspec-mechanize/test_utils.rb', line 79

def symbol_to_sequence(symb)
  value = {:zero => 0,
           :first => 1,
           :second => 2,
           :third => 3,
           :fourth => 4,
           :fifth => 5,
           :sixth => 6,
           :seventh => 7,
           :eighth => 8,
           :ninth => 9,
           :tenth => 10}[symb]
  return value || symb.to_i
end

#take_screenshot(opts = {}) ⇒ Object

use win32screenshot library to save curernt active window, which shall be IE

opts => the direcotry to save image under



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/rwebspec-mechanize/test_utils.rb', line 99

def take_screenshot(opts = {})
  # puts "calling new take screenshot: #{$screenshot_supported}"
  unless $screenshot_supported
    puts " [WARN] Screenhost not supported, check whether win32screenshot gem is installed" 
    return
  end
  
    begin
      screenshot_image_filename =  "screenshot_" + Time.now.strftime("%m%d%H%M%S") + ".jpg"
      the_dump_dir = opts[:to_dir] || default_dump_dir
      FileUtils.mkdir_p(the_dump_dir) unless File.exists?(the_dump_dir)
      screenshot_image_filepath = File.join(the_dump_dir, screenshot_image_filename)
      screenshot_image_filepath.gsub!("/", "\\") if is_windows?

      FileUtils.rm_f(screenshot_image_filepath) if File.exist?(screenshot_image_filepath)

      if is_firefox? then
        Win32::Screenshot::Take.of(:window, :title => /mozilla\sfirefox/i).write(screenshot_image_filepath)					
elsif ie
        Win32::Screenshot::Take.of(:window, :title => /internet\sexplorer/i).write(screenshot_image_filepath)					
      else
        Win32::Screenshot::Take.of(:foreground).write(screenshot_image_filepath)
      end
      notify_screenshot_location(screenshot_image_filepath)
    rescue => e
      puts "error on taking screenshot: #{e}"
    end
  
end

#today(format = nil) ⇒ Object Also known as: getToday_AU, getToday_US, getToday

default date format returned is 29/12/2007. if supplied parameter is not ‘%m/%d/%Y’ -> 12/29/2007 Otherwise, “2007-12-29”, which is most approiate date format

%a - The abbreviated weekday name (``Sun'')
%A - The  full  weekday  name (``Sunday'')
%b - The abbreviated month name (``Jan'')
%B - The  full  month  name (``January'')
%c - The preferred local date and time representation
%d - Day of the month (01..31)
%H - Hour of the day, 24-hour clock (00..23)
%I - Hour of the day, 12-hour clock (01..12)
%j - Day of the year (001..366)
%m - Month of the year (01..12)
%M - Minute of the hour (00..59)
%p - Meridian indicator (``AM''  or  ``PM'')
%S - Second of the minute (00..60)
%U - Week  number  of the current year,
        starting with the first Sunday as the first
        day of the first week (00..53)
%W - Week  number  of the current year,
        starting with the first Monday as the first
        day of the first week (00..53)
%w - Day of the week (Sunday is 0, 0..6)
%x - Preferred representation for the date alone, no time
%X - Preferred representation for the time alone, no date
%y - Year without a century (00..99)
%Y - Year with century
%Z - Time zone name
%% - Literal ``%'' character


215
216
217
# File 'lib/rwebspec-mechanize/test_utils.rb', line 215

def today(format = nil)                
  format_date(Time.now, date_format(format))
end

#tomorrow(format = nil) ⇒ Object



238
239
240
# File 'lib/rwebspec-mechanize/test_utils.rb', line 238

def tomorrow(format = nil)
  days_from_now(1, date_format(format))
end

#try(timeout = $testwise_polling_timeout, polling_interval = $testwise_polling_interval || 1, &block) ⇒ Object



42
43
44
45
46
47
# File 'lib/rwebspec-mechanize/test_utils.rb', line 42

def try(timeout = $testwise_polling_timeout, polling_interval = $testwise_polling_interval || 1, &block)
  puts "Warning: method 'try' is deprecated (won't support in RWebSpec 3), use try_until instead."
  try_until(timeout, polling_interval) {
    yield
  }
end

#try_until(timeout = $testwise_polling_timeout, polling_interval = $testwise_polling_interval || 1, &block) ⇒ Object Also known as: try_upto

Try the operation up to specified timeout (in seconds), and sleep given interval (in seconds). Error will be ignored until timeout Example

try_until { click_link('waiting')}
try_until(10, 2) { click_button('Search' } # try to click the 'Search' button upto 10 seconds, try every 2 seconds
try_until { click_button('Search' }


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rwebspec-mechanize/test_utils.rb', line 21

def try_until(timeout = $testwise_polling_timeout, polling_interval = $testwise_polling_interval || 1, &block)
  start_time = Time.now

  last_error = nil
  until (duration = Time.now - start_time) > timeout
    begin
      yield
      last_error = nil
	return true 
    rescue => e
      last_error = e
    end
    sleep polling_interval
  end

  raise "Timeout after #{duration.to_i} seconds with error: #{last_error}." if last_error
  raise "Timeout after #{duration.to_i} seconds."
end

#value_in_range(range) ⇒ Object

Pick a random value out of a given range.



284
285
286
287
288
289
290
291
# File 'lib/rwebspec-mechanize/test_utils.rb', line 284

def value_in_range(range)
  case range.first
  when Integer then number_in_range(range)
  when Time then time_in_range(range)
  when Date then date_in_range(range)
  else range.to_a.rand
  end
end

#words(total) ⇒ Object

Generate a given number of words. If a range is passed, it will generate a random number of words within that range.



295
296
297
298
299
300
301
# File 'lib/rwebspec-mechanize/test_utils.rb', line 295

def words(total)
  if total.class == Range
    (1..interpret_value(total)).map { WORDS[random_number(total.min, total.max)] }.join(' ')
  else
    (1..interpret_value(total)).map { WORDS[random_number(0, total)] }.join(' ')
  end
end

#yesterday(format = nil) ⇒ Object



228
229
230
# File 'lib/rwebspec-mechanize/test_utils.rb', line 228

def yesterday(format = nil)
  days_before(1, date_format(format))
end