zhimin-rwebspec 1.4.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,68 @@
1
+ require 'socket'
2
+
3
+ module RWebSpec
4
+ module ITestPlugin
5
+
6
+ def connect_to_itest(message_type, body)
7
+ begin
8
+ the_message = message_type + "|" + body
9
+ if @last_message == the_message then # ignore the message same as preivous one
10
+ return
11
+ end
12
+ itest_port = $ITEST2_TRACE_PORT || 7025
13
+ itest_socket = Socket.new(Socket::AF_INET,Socket::SOCK_STREAM,0)
14
+ itest_socket.connect(Socket.pack_sockaddr_in(itest_port, '127.0.0.1'))
15
+ itest_socket.puts(the_message)
16
+ @last_message = the_message
17
+ itest_socket.close
18
+ rescue => e
19
+ end
20
+ end
21
+ alias connect_to_itest2 connect_to_itest
22
+
23
+ def debug(message)
24
+ connect_to_itest(" DEBUG", message + "\r\n") if $RUN_IN_ITEST
25
+ end
26
+
27
+
28
+ # Support of iTest to ajust the intervals between keystroke/mouse operations
29
+ def operation_delay
30
+ begin
31
+ if $ITEST2_OPERATION_DELAY && $ITEST2_OPERATION_DELAY > 0 &&
32
+ $ITEST2_OPERATION_DELAY && $ITEST2_OPERATION_DELAY < 30000 then # max 30 seconds
33
+ sleep($ITEST2_OPERATION_DELAY / 1000)
34
+ end
35
+
36
+ while $ITEST2_PAUSE
37
+ debug("Paused, waiting ...")
38
+ sleep 1
39
+ end
40
+ rescue => e
41
+ puts "Error on delaying: #{e}"
42
+ # ignore
43
+ end
44
+ end
45
+
46
+ # find out the line (and file) the execution is on, and notify iTest via Socket
47
+ def dump_caller_stack
48
+ return unless $ITEST2_TRACE_EXECUTION
49
+ begin
50
+ caller.each_with_index do |position, idx|
51
+ next unless position =~ /\A(.*?):(\d+)/
52
+ file = $1
53
+ # TODO: send multiple trace to be parse with pages.rb
54
+ # next if file =~ /example\/example_methods\.rb$/ or file =~ /example\/example_group_methods\.rb$/ or file =~ /driver\.rb$/ or file =~ /timeout\.rb$/ # don't include rspec or ruby trace
55
+
56
+ if file.include?("_spec.rb") || file.include?("_test.rb") || file.include?("_cmd.rb")
57
+ connect_to_itest(" TRACE", position)
58
+ end
59
+
60
+ break if idx > 4 or file =~ /"_spec\.rb$/
61
+ end
62
+ rescue => e
63
+ puts "failed to capture log: #{e}"
64
+ end
65
+ end
66
+
67
+ end
68
+ end
@@ -0,0 +1,37 @@
1
+ class ContainsText
2
+
3
+ # this is what the matcher is called on.
4
+ # In this case:
5
+ # foo.should contains(:bars)
6
+ # foo would be passed to the +initialize+
7
+ def initialize(expected)
8
+ @expected = expected
9
+ end
10
+
11
+ def matches?(actual)
12
+ @actual = actual
13
+ return actual && actual.include?(@expected)
14
+ end
15
+
16
+ def actual_text
17
+ @actual.to_s.length > 1000000 ? @actual[0, 1000] : @actual
18
+ end
19
+
20
+ # error message for should
21
+ def failure_message
22
+ "expected #{actual_text} not to contains #{@expected}, but it did't"
23
+ end
24
+
25
+ # error message for should_not
26
+ def negative_failure_message
27
+ "expected #{actual_text} not to contains #{@expected}, but it did"
28
+ end
29
+
30
+ end
31
+
32
+
33
+ # This method is the one you use with should/should_not
34
+ def contains_text?(expected)
35
+ ContainsText.new(expected)
36
+ end
37
+ alias contains? contains_text?
@@ -0,0 +1,147 @@
1
+ module RWebSpec
2
+ module Popup
3
+
4
+ #= Popup
5
+ #
6
+
7
+ # Start background thread to click popup windows
8
+ # Warning:
9
+ # Make browser window active
10
+ # Don't mouse your mouse to focus other window during test execution
11
+ def check_for_popups
12
+ autoit = WIN32OLE.new('AutoItX3.Control')
13
+ #
14
+ # Do forever - assumes popups could occur anywhere/anytime in your
15
+ # application.
16
+ loop do
17
+ # Look for window with given title. Give up after 1 second.
18
+ ret = autoit.WinWait('Windows Internet Explorer', '', 1)
19
+ #
20
+ # If window found, send appropriate keystroke (e.g. {enter}, {Y}, {N}).
21
+ if (ret==1) then
22
+ autoit.Send('{enter}')
23
+ end
24
+ #
25
+ # Take a rest to avoid chewing up cycles and give another thread a go.
26
+ # Then resume the loop.
27
+ sleep(3)
28
+ end
29
+ end
30
+
31
+ ##
32
+ # Check for "Security Information" and "Security Alert" alert popup, click 'Yes'
33
+ #
34
+ # Usage: For individual test suite
35
+ #
36
+ # before(:all) do
37
+ # $popup = Thread.new { check_for_alerts }
38
+ # open_in_browser
39
+ # ...
40
+ # end
41
+ #
42
+ # after(:all) do
43
+ # close_browser
44
+ # Thread.kill($popup)
45
+ # end
46
+ #
47
+ # or for all tests,
48
+ # $popup = Thread.new { check_for_alerts }
49
+ # at_exit{ Thread.kill($popup) }
50
+ def check_for_security_alerts
51
+ autoit = WIN32OLE.new('AutoItX3.Control')
52
+ loop do
53
+ ["Security Alert", "Security Information"].each do |win_title|
54
+ ret = autoit.WinWait(win_title, '', 1)
55
+ if (ret==1) then
56
+ autoit.Send('{Y}')
57
+ end
58
+ end
59
+ sleep(3)
60
+ end
61
+ end
62
+
63
+ def verify_alert(title = "Microsoft Internet Explorer", button = "OK")
64
+ if is_windows? && !is_firefox?
65
+ WIN32OLE.new('AutoItX3.Control').ControlClick(title, '', button)
66
+ else
67
+ raise "This function only supports IE"
68
+ end
69
+ end
70
+
71
+ def click_button_in_security_information_popup(button = "&Yes")
72
+ verify_alert("Security Information", "", button)
73
+ end
74
+ alias click_security_information_popup click_button_in_security_information_popup
75
+
76
+ def click_button_in_security_alert_popup(button = "&Yes")
77
+ verify_alert("Security Alert", "", button)
78
+ end
79
+ alias click_security_alert_popup click_button_in_security_alert_popup
80
+
81
+ def click_button_in_javascript_popup(button = "OK")
82
+ verify_alert()
83
+ end
84
+ alias click_javascript_popup click_button_in_javascript_popup
85
+
86
+ ##
87
+ # This only works for IEs
88
+ # Cons:
89
+ # - Slow
90
+ # - only works in IE
91
+ # - does not work for security alert ?
92
+ def ie_popup_clicker(button_name = "OK", max_wait = 15)
93
+ require 'watir/contrib/enabled_popup'
94
+ require 'win32ole'
95
+ hwnd = ie.enabled_popup(15)
96
+ if (hwnd) #yeah! a popup
97
+ popup = WinClicker.new
98
+ popup.makeWindowActive(hwnd) #Activate the window.
99
+ popup.clickWindowsButton_hwnd(hwnd, button_name) #Click the button
100
+ #popup.clickWindowsButton(/Internet/,button_name,30)
101
+ popup = nil
102
+ end
103
+ end
104
+
105
+ def click_popup_window(button, wait_time= 9, user_input=nil )
106
+ @web_browser.start_clicker(button, wait_time, user_input)
107
+ sleep 0.5
108
+ end
109
+ # run a separate process waiting for the popup window to click
110
+ #
111
+ #
112
+ def prepare_to_click_button_in_popup(button = "OK", wait_time = 3)
113
+ # !@web_browser.is_firefox?
114
+ # TODO: firefox is OK
115
+ if RUBY_PLATFORM =~ /mswin/ then
116
+ start_checking_js_dialog(button, wait_time)
117
+ else
118
+ raise "this only support on Windows and on IE"
119
+ end
120
+ end
121
+
122
+ # Start a background process to click the button on a javascript popup window
123
+ def start_checking_js_dialog(button = "OK", wait_time = 3)
124
+ w = WinClicker.new
125
+ longName = File.expand_path(File.dirname(__FILE__)).gsub("/", "\\" )
126
+ shortName = w.getShortFileName(longName)
127
+ c = "start ruby #{shortName}\\clickJSDialog.rb #{button} #{wait_time} "
128
+ w.winsystem(c)
129
+ w = nil
130
+ end
131
+
132
+ # Click the button in javascript popup dialog
133
+ # Usage:
134
+ # click_button_in_popup_after { click_link('Cancel')}
135
+ # click_button_in_popup_after("OK") { click_link('Cancel')}
136
+ #
137
+ def click_button_in_popup_after(options = {:button => "OK", :wait_time => 3}, &block)
138
+ if is_windows? then
139
+ start_checking_js_dialog(options[:button], options[:wait_time])
140
+ yield
141
+ else
142
+ raise "this only support on Windows and on IE"
143
+ end
144
+ end
145
+
146
+ end
147
+ end
@@ -0,0 +1,96 @@
1
+ require 'uri'
2
+
3
+ # ZZ patches to RSpec 1.1.2 - 1.1.4
4
+ # - add to_s method to example_group
5
+ module Spec
6
+ module Example
7
+ class ExampleGroup
8
+ def to_s
9
+ @_defined_description
10
+ end
11
+ end
12
+ end
13
+ end
14
+
15
+ # example
16
+ # should link_by_text(text, options).size > 0
17
+
18
+ module RWebSpec
19
+ module RSpecHelper
20
+ include RWebSpec::Driver
21
+ include RWebSpec::Utils
22
+ include RWebSpec::Assert
23
+
24
+ # --
25
+ # Content
26
+ # --
27
+
28
+ def table_source(table_id)
29
+ table(:id, table_id).innerHTML
30
+ # elem = @web_browser.document.getElementById(table_id)
31
+ # raise "The element '#{table_id}' is not a table or there are multple elements with same id" unless elem.name.uppercase == "TABLE"
32
+ # elem.innerHTML
33
+ end
34
+ alias table_source_by_id table_source
35
+
36
+ def element_text(elem_id)
37
+ @web_browser.element_value(elem_id)
38
+ end
39
+ alias element_text_by_id element_text
40
+
41
+ #TODO: is it working?
42
+ def element_source(elem_id)
43
+ @web_browser.get_html_in_element(elem_id)
44
+ end
45
+
46
+
47
+ def button_by_id(button_id)
48
+ button(:id, button_id)
49
+ end
50
+
51
+ def buttons_by_caption(text)
52
+ button(:text, text)
53
+ end
54
+ alias buttons_by_text buttons_by_caption
55
+
56
+ def link_by_id(link_id)
57
+ link(:id, link_id)
58
+ end
59
+
60
+ # default options: exact => true
61
+ def links_by_text(link_text, options = {})
62
+ options.merge!({:exact=> true})
63
+ matching_links = []
64
+ links.each { |link|
65
+ matching_links << link if (options[:exact] ? link.text == link_text : link.text.include?(link_text))
66
+ }
67
+ return matching_links
68
+ end
69
+ alias links_with_text links_by_text
70
+
71
+ def save_page(file_name = nil)
72
+ @web_browser.save_page(file_name)
73
+ end
74
+
75
+ def save_content_to_file(content, file_name = nil)
76
+ file_name ||= Time.now.strftime("%Y%m%d%H%M%S") + ".html"
77
+ puts "about to save page: #{File.expand_path(file_name)}"
78
+ File.open(file_name, "w").puts content
79
+ end
80
+
81
+ # When running
82
+ def debugging?
83
+ $ITEST2_DEBUGGING && $ITEST2_RUNNING_AS == "test_case"
84
+ end
85
+
86
+ # RSpec Matchers
87
+ #
88
+ # Example,
89
+ # a_number.should be_odd_number
90
+ def be_odd_number
91
+ simple_matcher("must be odd number") { |actual| actual && actual.to_id % 2 == 1}
92
+ end
93
+
94
+ end
95
+
96
+ end
@@ -0,0 +1,8 @@
1
+ module RWebSpec
2
+ module TestScript
3
+ include RWebSpec::Driver
4
+ include RWebSpec::Utils
5
+ include RWebSpec::Assert
6
+
7
+ end
8
+ end
@@ -0,0 +1,171 @@
1
+ #***********************************************************
2
+ #* Copyright (c) 2006, Zhimin Zhan.
3
+ #* Distributed open-source, see full license in MIT-LICENSE
4
+ #***********************************************************
5
+
6
+ # useful hekoer methods for testing
7
+ #
8
+ module RWebSpec
9
+ module Utils
10
+
11
+ # default date format returned is 29/12/2007.
12
+ # if supplied parameter is not '%m/%d/%Y' -> 12/29/2007
13
+ # Otherwise, "2007-12-29", which is most approiate date format
14
+ #
15
+ # %a - The abbreviated weekday name (``Sun'')
16
+ # %A - The full weekday name (``Sunday'')
17
+ # %b - The abbreviated month name (``Jan'')
18
+ # %B - The full month name (``January'')
19
+ # %c - The preferred local date and time representation
20
+ # %d - Day of the month (01..31)
21
+ # %H - Hour of the day, 24-hour clock (00..23)
22
+ # %I - Hour of the day, 12-hour clock (01..12)
23
+ # %j - Day of the year (001..366)
24
+ # %m - Month of the year (01..12)
25
+ # %M - Minute of the hour (00..59)
26
+ # %p - Meridian indicator (``AM'' or ``PM'')
27
+ # %S - Second of the minute (00..60)
28
+ # %U - Week number of the current year,
29
+ # starting with the first Sunday as the first
30
+ # day of the first week (00..53)
31
+ # %W - Week number of the current year,
32
+ # starting with the first Monday as the first
33
+ # day of the first week (00..53)
34
+ # %w - Day of the week (Sunday is 0, 0..6)
35
+ # %x - Preferred representation for the date alone, no time
36
+ # %X - Preferred representation for the time alone, no date
37
+ # %y - Year without a century (00..99)
38
+ # %Y - Year with century
39
+ # %Z - Time zone name
40
+ # %% - Literal ``%'' character
41
+
42
+ def today(format = '%d/%m/%Y')
43
+ format_date(Time.now, format)
44
+ end
45
+ alias getToday_AU today
46
+ alias getToday_US today
47
+ alias getToday today
48
+
49
+
50
+ def days_before(days, format = '%d/%m/%Y')
51
+ nil if !(days.instance_of?(Fixnum))
52
+ format_date(Time.now - days * 24 * 3600, format)
53
+ end
54
+
55
+ def yesterday
56
+ days_before(1)
57
+ end
58
+
59
+ def days_from_now(days, format = '%d/%m/%Y')
60
+ nil if !(days.instance_of?(Fixnum))
61
+ format_date(Time.now + days * 24 * 3600, format)
62
+ end
63
+ alias days_after days_from_now
64
+
65
+ def tomorrow
66
+ days_from_now(1)
67
+ end
68
+
69
+ # return a random number >= min, but <= max
70
+ def random_number(min, max)
71
+ rand(max-min+1)+min
72
+ end
73
+
74
+ def random_boolean
75
+ return random_number(0, 1) == 1
76
+ end
77
+
78
+ def random_char(lowercase = true)
79
+ sprintf("%c", random_number(97, 122)) if lowercase
80
+ sprintf("%c", random_number(65, 90)) unless lowercase
81
+ end
82
+
83
+ def random_digit()
84
+ sprintf("%c", random_number(48, 57))
85
+ end
86
+
87
+ def random_str(length, lowercase = true)
88
+ randomStr = ""
89
+ length.times {
90
+ randomStr += random_char(lowercase)
91
+ }
92
+ randomStr
93
+ end
94
+
95
+ # Return a random string in a rangeof pre-defined strings
96
+ def random_string_in(arr)
97
+ return nil if arr.empty?
98
+ index = random_number(0, arr.length-1)
99
+ arr[index]
100
+ end
101
+ alias random_string_in_collection random_string_in
102
+
103
+
104
+ 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)
105
+
106
+ # Pick a random value out of a given range.
107
+ def value_in_range(range)
108
+ case range.first
109
+ when Integer then number_in_range(range)
110
+ when Time then time_in_range(range)
111
+ when Date then date_in_range(range)
112
+ else range.to_a.rand
113
+ end
114
+ end
115
+
116
+ # Generate a given number of words. If a range is passed, it will generate
117
+ # a random number of words within that range.
118
+ def words(total)
119
+ (1..interpret_value(total)).map { WORDS.rand }.join(' ')
120
+ end
121
+
122
+ # Generate a given number of sentences. If a range is passed, it will generate
123
+ # a random number of sentences within that range.
124
+ def sentences(total)
125
+ (1..interpret_value(total)).map do
126
+ words(5..20).capitalize
127
+ end.join('. ')
128
+ end
129
+
130
+ # Generate a given number of paragraphs. If a range is passed, it will generate
131
+ # a random number of paragraphs within that range.
132
+ def paragraphs(total)
133
+ (1..interpret_value(total)).map do
134
+ sentences(3..8).capitalize
135
+ end.join("\n\n")
136
+ end
137
+
138
+ # If an array or range is passed, a random value will be selected to match.
139
+ # All other values are simply returned.
140
+ def interpret_value(value)
141
+ case value
142
+ when Array then value.rand
143
+ when Range then value_in_range(value)
144
+ else value
145
+ end
146
+ end
147
+
148
+ private
149
+
150
+ def time_in_range(range)
151
+ Time.at number_in_range(Range.new(range.first.to_i, range.last.to_i, range.exclude_end?))
152
+ end
153
+
154
+ def date_in_range(range)
155
+ Date.jd number_in_range(Range.new(range.first.jd, range.last.jd, range.exclude_end?))
156
+ end
157
+
158
+ def number_in_range(range)
159
+ if range.exclude_end?
160
+ rand(range.last - range.first) + range.first
161
+ else
162
+ rand((range.last+1) - range.first) + range.first
163
+ end
164
+ end
165
+
166
+ def format_date(date, date_format = '%d/%m/%Y')
167
+ date.strftime(date_format)
168
+ end
169
+
170
+ end
171
+ end