Class: Soda::Soda

Inherits:
Object
  • Object
show all
Defined in:
lib/Soda.rb

Overview

Soda – Class

This class that converts Soda Meta Data into Ruby Watir Commands and

executes them.

Params:

browser: For setting the default browser. IE/FireFox/...
sugarflavor: This is the type of sugar flavor we are testing: ent,pro...
savehtml: Setting this saves off failed html pages o disk.
hijacks: This is a hash of keys to overwrite csv file values.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Soda

Returns a new instance of Soda.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
128
129
130
131
132
133
134
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/Soda.rb', line 81

def initialize(params)
   $curSoda = self;
   @params = nil
   @debug = params['debug']
   @browser = nil
   @saveHtml = params['savehtml']
   @blocked_files = []
   @fileStack = [] # used for keeping track of which file we are in # 
   @curEl = nil # current element being used #    
   $link_not_assert = false 
   $skip_css_errors = false
   @newCSV = [] 
   $SodaHome = Dir.getwd()
   @current_os = SodaUtils.GetOsType()
   @sugarFlavor = {}
   @resultsDir = {} 
   @globalVars = {}
   @SIGNAL_STOP = false
   @hiJacks = nil
   @breakExit = false
   @currentTestFile = "" 
   @exceptionExit = false
   @ieHwnd = 0
   @nonzippytext = false
   $global_time = Time.now()
   $mutex = Mutex.new()
   @whiteList = []
   @white_list_file = ""
   @restart_test = nil
   @restart_count = 0
   @non_lib_test_count = 0
   @last_test = ""
   @SugarWait = false
   @testDelay = false
   @restart_test_running = false
   @FAILEDTESTS = []
   @GotWatchDog = false
   @vars = Hash.new
   blocked_file_list = "tests/modules/blockScriptList.xml"
   whitelist_file = "tests/modules/whitelist.xml"
   result = nil
   sigs = [
      "INT",
      "ABRT",
      "KILL"
   ]
   err = 0
 
   @testDelay = params['testdelay'] if (params.key?('testdelay'))
   @sugarFlavor = params['flavor'] if (params.key?('flavor'))
   @resultsDir = params['resultsdir'] if (params.key?('resultsdir'))
   @globalVars = params['gvars'] if (params.key?('gvars'))
   @nonzippytext = params['nonzippytext'] if (params.key?('nonzippytext'))

   if (@globalVars.key?('scriptsdir'))
      blocked_file_list = "#{@globalVars['scriptsdir']}/modules/" +
         "blockScriptList.xml"
      whitelist_file = "#{@globalVars['scriptsdir']}/modules/whitelist.xml" 
   end

   if (File.exist?(blocked_file_list))
      @blocked_files = SodaUtils.ParseBlockFile(blocked_file_list)
   end

   if (File.exist?(whitelist_file))
      @whiteList = SodaUtils.ParseWhiteFile(whitelist_file)
   end

   @sugarFlavor = @sugarFlavor.downcase()

   if (params.key?('restart_count'))
      @restart_count = params['restart_count'].to_i()
      if (params.key?('restart_test'))
         @restart_test = params['restart_test']
      end
   end

   if (params['hijacks'] != nil)
      @hiJacks = params['hijacks']
   end

   if (params.key?('sugarwait'))
      @SugarWait = params['sugarwait']
   end


   # stack of elements allowing for parent child hierchy
   # <form id='myform'><textfield name='myfield'/></form> 
   @parentEl = [] 

   sigs.each do |s|
      Signal.trap(s, proc { @SIGNAL_STOP = true } )
   end

   if (@current_os =~ /windows/i)
      $win_only = true
   end

   @autoClick = { 
      "button" => true, 
      "link" => true, 
      "radio" => true
   }
  
   @params = params
   err = NewBrowser()
   if (err != 0)
      exit(-1)
   end

   # this is setup to allow other skips, but there should never really
   # be any other type of error to skip.  The only reason why I added
   # this skip is because a manager requested it.  In genernal skipping
   # reporting errors is not a good thing and should never ever be done!
   @params['errorskip'].each do |error|
      case error
         when /css/i
            $skip_css_errors = true
      end
   end

   @vars['stamp'] = getStamp()
   @vars['currentdate'] = getDate()
end

Instance Attribute Details

#browserObject

Returns the value of attribute browser.



79
80
81
# File 'lib/Soda.rb', line 79

def browser
  @browser
end

#repObject

Returns the value of attribute rep.



79
80
81
# File 'lib/Soda.rb', line 79

def rep
  @rep
end

Instance Method Details

#assertPageObject

assertPage – Method

This method checks to see of the browser contains any text for known
errors.  It also looks to make sure anything in the whitelist isn't
reported as a error.

Input:

None.

Output:

None.


1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
# File 'lib/Soda.rb', line 1095

def assertPage()
   data = []
   found_error = false
   page_strs_to_replace = [
      'Expiration Notice:', 'Notice: Your license expires',
      'Warning: Please upgrade', 
      '(Fatal|Error): Your license expired|',
      'isError', 'errors' ,'ErrorLink'
      ]
   page_strs_to_replace2 = [
      'Warning: Your email settings are not configured to send email',
      'Warning: Missing username and password',
      'Warning: You are modifying your automatic',
      'Warning: Auto import must be enabled when automatically'+
          ' creating cases'
      ]

   crazyEvilIETabHack()
   @browser.wait()

   begin
      text = @browser.text
   rescue Exception => e
      @rep.ReportException(e)
      text = ""
   ensure

   end
  
   text = text.gsub(/^\n/, "")

   page_strs_to_replace.each do |reg|
      text = text.gsub(/#{reg}/i, '')
   end
   
   page_strs_to_replace2.each do |reg|
      text = text.gsub(/#{reg}/, '')
   end

   @whiteList.each do |hash|
      text = text.gsub(/#{hash['data']}/, '')
   end

   data = text.split(/\n/)
   data.each do |line|
      case (line)
         when /(Notice:.*line.*)/i
            @rep.ReportFailure("Found error in page HTML: '#{$1}'\n")
            found_error = true
         when /(Warning:)/i
            @rep.ReportFailure("Found error in page HTML: '#{$1}'\n")
            found_error = true
         when /(.*Error:.*line.*)/i
            @rep.ReportFailure("Found error in page HTML: '#{$1}'\n")
            found_error = true
         when/(Error retrieving)/i
            @rep.ReportFailure("Found error in page HTML: '#{$1}'\n") 
            found_error = true
         when /(SQL Error)/i
            @rep.ReportFailure("Found error in page HTML: '#{$1}'\n") 
            found_error = true
      end
   end

   if (found_error)
      @FAILEDTESTS.push(@currentTestFile)
   end

end

#CheckJavaScriptErrorsObject

CheckJavaScriptErrors – Method

This function checks the current page for all javascript errors.

Params:

None.

Results:

Always returns 0.


1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
# File 'lib/Soda.rb', line 1824

def CheckJavaScriptErrors()
   result = nil
   data = nil
   error_hash = {}

   if (Watir::Browser.default == "firefox")
      result = @browser.execute_script(
         "#{SodaUtils::FIREFOX_JS_ERROR_CHECK_SRC}")
      data = result.split(/######/)
      data.each do |line|
         line = line.chomp()

         if ( (line != "") && 
            (line !~ /chrome:\/\/browser\/content\/tabbrowser\.xm/) &&
            (line !~ /SShStarter.js/i ))
            if (error_hash.key?(line))
               error_hash[line] += 1
            else
               error_hash[line] = 1
           end 
         end
      end
   end

   error_hash.each do |error, count|
      if (count > 1)
         msg = "Javascript Error (repeated #{count} times):#{error}\n"
      else
         msg = "Javascript Error:#{error}\n"
      end

      @rep.ReportJavaScriptError(msg, $skip_css_errors)
   end

   return 0
end

#checkSelectList(list, str) ⇒ Object

checkSelectList – Method

This method checks to see if a string exisits in a list of some kind.

Params:

list: ???
str: A string to check for in the list.

Results:

returns true of the string is found or false if it is not.


1290
1291
1292
1293
1294
1295
1296
1297
1298
# File 'lib/Soda.rb', line 1290

def checkSelectList(list, str)
   list.each do |i|
      if (i == str)
         return true
      end
   end

   return false          
end

#cloneEvent(event) ⇒ Object

cloneEvent – Method

This method does a deep clone of events Arrays in Ruby are objects and
 we ocassionally need to preserve the state of the arrays.

Params:

event: ???

Results:

returns the event data after it as been marshaled into a byte stream.


1312
1313
1314
# File 'lib/Soda.rb', line 1312

def cloneEvent(event)
   return Marshal.load(Marshal.dump(event))
end

#CloseBrowserObject

CloseBrowser – Method

This method closes browsers.

Params:

None.

Results:

None.


1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
# File 'lib/Soda.rb', line 1362

def CloseBrowser()
   result = 0

   if (Watir::Browser.default =~ /firefox/i)
      result = SodaFireFox.CloseBrowser(@browser)
   else
      @browser.close()
      result = 1
   end

   if (result < 1)
      @rep.ReportFailure("Failed trying to close browser: '#{result}'!\n")
   end

   @browser = nil
end

#crazyEvilIETabHackObject

crazyEvilIETabHack – Method

This method make ie's tab pages act like firefox's in the since that,
when a new tab is opened in ie and that new tab has focus watir doesn't 
notice and keeps working on the browser tab that isn't in focus anymore.
Yes this is totally lame, but here is the hack to make it work.

Note:

Because the window handle is the same for the tabbed window I really
didn't need to go through all of the trouble, I could have just 
reattached to the same hwnd and this would have all worked, but then
this code would not be able to support when we are going to no be using
tab's.  Really we should not be using tabs anymore anyway!

Params:

None.

Results:

Always returns 0.


2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
# File 'lib/Soda.rb', line 2388

def crazyEvilIETabHack()
   if(Watir::Browser.default !~ /ie/i)
      return 0
   end

   if (@ieHwnd != 0)
      ie_count = 0
      
      Watir::IE.each do |tab|
         ie_count += 1
      end

      if ((ie_count == 1) && (@ieHwnd != 0))
         @browser = Watir::Browser.attach(:hwnd, @ieHwnd)
         PrintDebug("IE hack: switching back to parent window handle:" +
            " \"#{@ieHwnd}\".\n")
         @ieHwnd = 0
     end
   end
  
   Watir::IE.each do |tab|
      url = tab.url
      if ( (url =~ /popup/i) && (@ieHwnd == 0))
         @ieHwnd = @browser.hwnd()
         @browser = Watir::Browser.attach(:hwnd, tab.hwnd)
         tmp_hwnd = @browser.hwnd()
         PrintDebug("IE hack: found popup window switching from parent"+
            " handle: \"#{@ieHwnd}\" to popup handle: \"#{tab.hwnd}\".\n")
         break
      end
   end

  return 0
end

#cssInfoEvent(event) ⇒ Object

cssInfoEvent – method

This method checks that css values for a given soda element.

Input:

event: A soda event.

Output:

returns 0 on success or -1 on error.


2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
# File 'lib/Soda.rb', line 2325

def cssInfoEvent(event)
   jssh_var = ""
   jssh_data = nil
   css_data = nil

   if (!event.key?('cssprop'))
      @rep.ReportFailure("Missing attribte: 'cssprop' on line: "+
      "#{event[line_number]}!\n")
      return -1  
   elsif (!event.key?('cssvalue'))
      @rep.ReportFailure("Missing attribte: 'cssvalue' on line: "+
         "#{event['line_number']}!\n")  
      return -1
   end
  
   event['cssprop'] = replaceVars(event['cssprop'])
   event['cssvalue'] = replaceVars(event['cssvalue'])

   if (@params['browser'] =~ /firefox/i)
      css_data = SodaUtils.GetFireFoxStyle(@curEl, event['cssprop'], 
            @rep, @browser)
   elsif (@params['browser'] =~ /ie/i)
      css_data = SodaUtils.GetIEStyle(@curEl, event['cssprop'], @rep)
   end
   
   return -1 if (css_data == nil)

   if (event['cssvalue'] == "#{css_data}")
      msg = "CSS property '#{event['cssprop']}' => "+
         "'#{css_data}'"
     @rep.Assert(true, msg) 
   else
      msg = "CSS propery '#{event['cssprop']}' => "+
         "'#{css_data}' was expecting value: "+
         "'#{event['cssvalue']}'!"
      @rep.Assert(false, msg, @currentTestFile,
         "#{event['line_number']}")
   end

   return 0
end

#eventAttach(event) ⇒ Object

eventAttach - Method

This method attaches to a new browser window and then preforms the
all child in the new window.

Params:

event: This is the soda <attach> event.

Results:

None.


1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
# File 'lib/Soda.rb', line 1510

def eventAttach(event)
   title = nil
   url = nil
   new_browser = nil
   old_browser = @browser

   PrintDebug("eventAttach: Starting.\n")
  
   begin
      if (event.key?('title'))
         title = replaceVars(event['title'])
         title = stringToRegex(title) 
         new_browser = @browser.attach(:title, title)
      elsif (event.key?('url'))
         url = replaceVars(event['url'])
         url = stringToRegex(url)
         new_browser = @browser.attach(:url, url)
      end
   rescue Exception=>e
      @rep.ReportException(e, @currentTestFile);

      e_dump = SodaUtils.DumpEvent(event)
      @rep.log("Event Dump From Exception: #{e_dump}!\n", 
         SodaUtils::EVENT)

      new_browser = nil
   end
   
   if (new_browser != nil)
      @browser = new_browser
      if (event.key?('children'))
         handleEvents(cloneEvent(event['children']))
      end

      @browser = old_browser
   end

   PrintDebug("eventAttach: Finished.\n")
end

#eventBrowser(event) ⇒ Object

eventBrowser – Method

This method handles all Soda browser events.

Params:

event: This is the event to handle.

Results:

returns a hash with keys: browser_close & error.


1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
# File 'lib/Soda.rb', line 1390

def eventBrowser(event)
   result = {
      'browser_closed' => false,
      'error' => 0 
   }

   event = SodaUtils.ConvertOldBrowserClose(event, @rep, @currentTestFile)

   if (event.key?('action'))
      action = replaceVars(event['action'])
      @rep.log("Firing browser action: \"#{action}\"\n")

      case action
         when "back"
            @browser.back
         when "forward"
            @browser.forward
         when "close"
            if (@browser != nil)
               CloseBrowser()
               result['browser_closed'] = true
            else
               PrintDebug("For some reason I got a nill @browser object!",
                  SodaUtils::WARN)
               @rep.IncTestWarningCount()
               result['browser_closed'] = true
            end
         when "refresh"
            @browser.refresh
         else
            @rep.ReportFailure("Unknown browser action:"+
               " \"#{action}\".\n")
            result['error'] = -1
      end
   end

   if (event.key?('url'))
      event['url']  = replaceVars(event['url'])
      @browser.goto(event['url'])
      @browser.wait()
      if (event['assertPage'] == nil || event['assertPage'] != "false")
          assertPage()
      end
   end

   if (event.key?('assert'))
      PrintDebug("Asserting Browser Contains: #{event['assert']}\n");
      result['error'] = kindsOfBrowserAssert(event)
   end

   if (event.key?('assertnot'))
      @rep.log("Asserting browser does not Contain: " +
         " #{event['assertnot']}\n");
      event['assert'] = event['assertnot'] # hack #
      result['error'] = kindsOfBrowserAssert(event, false)
      event.delete('assert') # clean up hack #
   end

   if event.key?('send_keys')
      if ($win_only == true)
         case event['send_keys']
            when 'Ctrl+W'
               send_keys("^{w}")
            when 'BACKSPACE'
               send_keys("{BACKSPACE}")
            when 'ENTER'
               send_keys("{ENTER}")
            else
               send_keys(event['send_keys'])
               #@rep.log("eventBrowser: Unknown send_key: " +
               #   "\"#{event['send_keys']}.\n", SodaUtils::WARN)
         end
      else
         msg = "Failed: This method Windows support only!\n"
         @rep.ReportFailure(msg)
         result['error'] = -1
      end
   end

   return result
end

#eventCondition(event) ⇒ Object



1578
1579
1580
# File 'lib/Soda.rb', line 1578

def eventCondition(event)
   
end

#eventCSV(event) ⇒ Object

eventCSV – Method

This method handles the csv file events.

Params:

event: This is the event to handle.

Results:

None.


1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
# File 'lib/Soda.rb', line 1483

def eventCSV(event)

   event['file'] = replaceVars(event['file'])
   getRightCSV(event) 
   csv = SodaCSV.new(event['file'])

   while (record = csv.nextRecord())
      setScriptVar(event['var'], record)
      
      if (event.key?('children'))
         handleEvents(cloneEvent(event['children']))
      end
   end
end

#eventDialog(event) ⇒ Object



1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
# File 'lib/Soda.rb', line 1661

def eventDialog(event)
   win_handle = nil

   if (@current_os !~ /windows/i)
      @rep.ReportFailure("Using SODA dialog command on unsupported os:"+
         " '#{@current_os}'!\n")
      return -1
   end

   if (!event.key?('title'))
      @rep.ReportFailure("SODA: dialog command is missing the 'title' "+
         "attribute!\n")
      return -1
   end

   PrintDebug("Trying to connect to dialog: title => '#{event['title']}'.\n")
   for i in 0..10 do
      win_handle = @autoit.WinGetHandle(event['title'])
      if (win_handle.empty? || win_handle.length < 1)
         win_handle = nil
         sleep(1)
      else
         PrintDebug("Found dialog window handle: '#{win_handle}'.\n")
         break   
      end
   end

   if (win_handle == nil)
      @rep.ReportFailure("Failed to find dialog by title => "+
         "'#{event['title']}'!\n")
      return -1
   end

   if (!event.key?('children'))
      return 0
   end

   event['children'].each do |child|
      case (child['do'])
         when "sendkey"
            @autoit.WinActivate(event['title'], nil)
            sleep(1)
            @autoit.Send(child['key'])
         when "assert"
            sleep(1)
            @autoit.WinActivate(event['title'], nil)
            sleep(1)
            @autoit.Send("^a")
            sleep(1)
            @autoit.Send("^c")
            sleep(1)
            tmp = @autoit.ClipGet()
            if (tmp.empty? || tmp.length < 1)
               @rep.ReportFailure("Failed to get text from dialog!\n")
               next
            end

            if (SodaUtils.isRegex(child['value']))
               child['value'] = stringToRegex(child['value'])
               match = child['value'].match(tmp)
               if (match == nil)
                  @rep.ReportFailure("Falied to match regex: "+
                     "'#{child['value']}' to dialog text '#{tmp}'"+
                     "!\n")
                  next
               else
                  @rep.Assert(true, "Matched Regex: '#{child['value']}'"+
                     " to dialog text.\n") 
               end
            else
               @rep.Assert(child['value'] == tmp, "Checking that dialog"+
                  " matches value: '#{child['value']}'.\n")
            end
      end
   end
end

#eventFieldAction(event, fieldType) ⇒ Object

eventFieldAction – Method

returns true of jsevent was fired.



2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
# File 'lib/Soda.rb', line 2076

def eventFieldAction(event, fieldType)
   js = nil
   js_fired = false
   result = nil
   foundaction = nil
   foundvalue = nil
   fieldactions = [
      'clear',
      'focus',
      'click',
      'set',
      'assert',
      'assertnot',
      'include',
      'noninclude',
      'var',
      'vartext',
      'children',
      'button',
      'exists',
      'link',
      'append',
      'disabled',
      'jscriptevent',
      'cssprop',
      'cssvalue'
      ]

   if (@SIGNAL_STOP != false)
      exit(-1)
   end

   fieldactions.each do |action|
      if (event.key?(action))
         foundaction = action
         break
      end
   end

   if (foundaction == nil)
      foundaction = event['do']
   end

   if (event.key?("alert"))
    if (event['alert'] =~ /true/i)
       @rep.log("Enabling Alert Hack\n")
       fieldType.alertHack(true, true) 
    else
       fieldType.alertHack(false, false)
       @rep.log("Disabeling alert!\n")
       PrintDebug("eventFieldAction: Finished.\n")
       return
    end
   end

   if (event.key?("jscriptevent"))
      js = replaceVars(event['jscriptevent'])
   end

   case (foundaction)
      when /cssprop|cssvalue/i
         cssInfoEvent(event)
      when "jscriptevent"
         fieldType.jsevent(@curEl, js, true)
         js_fired = true
      when "append"
         result = fieldType.append(@curEl, replaceVars(event['append']))
         if (result != 0)
            event['current_test_file'] = @currentTestFile
            e_dump = SodaUtils.DumpEvent(event)
            @rep.log("Event Dump: #{e_dump}\n", SodaUtils::EVENT)     
         end
      when "button"
         fieldType.click(@curEl, @SugarWait)
         @browser.wait()
         if (event['assertPage'] == nil || event['assertPage'] != "false")
            assertPage()
         end
      when "link"
         if ( (js != nil) && (js =~ /onmouseover/i) )
            jswait = true
            if (event.key?('jswait'))
               jswait = false if (event['jswait'] =~ /false/i)
            end
            fieldType.jsevent(@curEl, js, jswait)
         end
         fieldType.click(@curEl, @SugarWait)
         @browser.wait()
         if (event['assertPage'] == nil || event['assertPage'] != "false")
            assertPage()
         end
      when "clear"
         if(event['clear'])
            event['clear'] = replaceVars(event['clear'])
            case event['clear']
               when /true/i
                  PrintDebug("Clearing field\n")
                  fieldType.clear(@curEl)
               when /false/i
                  PrintDebug("Skipping field clearing event as its value" +
                     " was: \"#{event['clear']}\".\n")
               else
                  @rep.log("Found unsupported value for <textfield clear" +
                     "=\"true/false\" />!\n", SodaUtils::WARN)
                  @rep.IncTestWarningCount()
                  @rep.log("Unsupported clear value =>" +
                     " \"#{event['clear']}\".\n", SodaUtils::WARN)
                  @rep.IncTestWarningCount()
            end
         end
      when "focus"
         if (event['focus'])
            PrintDebug("Setting focus\n")
            fieldType.focus(@curEl)
         end
      when "radio"
         if (!fieldType.getStringTrue(event['set']) && 
               @autoClick[event['do']])
            fieldType.click(@curEl, @SugarWait)
            @browser.wait()
         end
      when "click"
         if ( (fieldType.getStringTrue(event['click'])) ||
               (!event.key?('click') && @autoClick[event['do']]) )

            PrintDebug("Performing click\n")
            fieldType.click(@curEl, @SugarWait)
            @browser.wait()
            if (event['assertPage'] == nil || event['assertPage'] != "false")
               assertPage()
            end
         end
      when "set"
         if (@curEl.class.to_s =~ /textfield/i)
            result = fieldType.set(@curEl, event['set'], @nonzippytext)
         else
            result = fieldType.set(@curEl, event['set'])
         end

         if (result != 0)
            event['current_test_file'] = @currentTestFile
            e_dump = SodaUtils.DumpEvent(event)
            @rep.log("Event Dump: #{e_dump}\n", SodaUtils::EVENT)
         end
      when "assert"
         fieldEventAssert(event, fieldType)
      when "assertnot"
         fieldEventAssert(event, fieldType)
      when "include"
         event['include'] = stringToRegex(event['include'])
         event['include'] = replaceVars(event['include'])
         @rep.log("Asserting Exist Option: #{event['include']}\n")
         @contents = SodaSelectField.getAllContents(@curEl)
         @rep.Assert(checkSelectList(@contents, event['include']),
            @currentTestFile)
      when "noninclude"
         event['noninclude'] = stringToRegex(event['noninclude'])
         event['noninclude'] = replaceVars(event['noninclude'])
         @rep.log("Asserting Not Exist Option: " +
            "#{event['noninclude']}", SodaUtils::ERROR)
         @contents = SodaSelectField.getAllContents(@curEl)
         @rep.Assert(!(checkSelectList(@contents, event['noninclude'])),
            @currentTestFile)
      when "var"
         setScriptVar(event['var'], fieldType.getValue(@curEl))
      when "vartext"
         setScriptVar(event['vartext'], fieldType.getText(@curEl))
      when "children"
         @parentEl.push(@curEl)
         handleEvents(event['children'])
         @parentEl.pop()
      when "disabled"
         event['disabled'] = getStringBool(event['disabled'])
         FieldUtils.CheckDisabled(@curEl, event['disabled'], @rep)
      else
         msg = "Failed to find supported field action.\n"
         @rep.log(msg, SodaUtils::WARN)
         @rep.IncTestWarningCount()
         e_dump = SodaUtils.DumpEvent(event)
         @rep.log("Event Dump: #{e_dump}\n", SodaUtils::EVENT)
   end

   return js_fired
end

#eventFileField(event) ⇒ Object

eventFileField – Method:

This method handles the FileField event.

Params:

event: THis is the soda event to handle.

Results:

None.


1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
# File 'lib/Soda.rb', line 1979

def eventFileField(event)
   os = nil
   abs = nil
   upload_file = nil
   path = nil
   what = nil

   event['do'] = 'file_field'
   if (event.key?('set'))
      upload_file = event['set']
   else
      @rep.Assert(false, "eventFileField: 'set' is empty!\n",
         @currentTestFile)
      return -1
   end

   path = Pathname.new(upload_file)

   if (!path.absolute?)
      upload_file = "#{$SodaHome}/#{upload_file}"
   end

   os = SodaUtils.GetOsType
   if (os =~ /windows/i)
      upload_file = upload_file.gsub("/", "\\")
   end

   PrintDebug("Uploading file: \"#{upload_file}\"\n")

   if (event.key?("id"))
      what = replaceVars(event['id'])
      @browser.file_field(:id, "#{what}").set(upload_file)
   elsif (event.key?("value"))
      what = replaceVars(event['value'])
      @browser.file_field(:value, "#{what}").set(upload_file)
   elsif (event.key?("name"))
      what = replaceVars(event['name'])
      @browser.file_field(:name, "#{what}").set(upload_file)
   else
      @rep.log("Unable to find control accessor for FileField!\n",
         SodaUtils::ERROR)
   end
end

#eventJavascript(event) ⇒ Object

eventJavascript – Method

This method handles all script events.

Params:

event: This is the event to handle.

Results:

None.


1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
# File 'lib/Soda.rb', line 1872

def eventJavascript(event)
   result = nil

   if (event['content'].length > 0)
       addUtils = event.key?('addUtils') && (getStringBool(event['addUtils']))
       result = SodaUtils.execute_script(event['content'], addUtils, @browser, @rep)
   else
      @rep.log("No javascript source content found!", SodaUtils::ERROR)
      return -1
   end
   
   CheckJavaScriptErrors()
   return result;
end

eventLink – Method

This method handles the Link event.

Params:

event: This is the soda event to handle.

Results:

None.


1898
1899
1900
1901
1902
1903
# File 'lib/Soda.rb', line 1898

def eventLink(event)
   field = nil

   field = getField(event) 
   return field
end

#eventMouseClick(event) ⇒ Object

eventMouseClick – Method

This method handles soda mouseclick events.  Currently this is only
supported on windows.

Params:

event: This is the soda event to handle.

Results:

None.


2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
# File 'lib/Soda.rb', line 2056

def eventMouseClick(event)
   PrintDebug("eventMouseClick: Starting.\n")
   if ($win_only == true)
      if (event.key?('xpos') && event.key?('ypos'))
         MouseClick(event['xpos'],event['ypos']);
      end                                          
    else 
      msg = "eventMouseClick Failed: This method Windows support only!\n"
      @rep.ReportFailure(msg)
    end

   PrintDebug("eventMouseClick: Finished.\n")
end

#eventPuts(event) ⇒ Object

eventPuts – Method

This method handles the puts event.

Params:

event: The soda puts event.

Results:

None.


2034
2035
2036
2037
2038
2039
2040
2041
2042
# File 'lib/Soda.rb', line 2034

def eventPuts(event)
   if (event.key?('text'))
      temp = replaceVars(event['text'])
      @rep.log("#{temp}\n" )
   elsif (event.key?('var'))
      var = replaceVars(event['var']) 
      @rep.log("#{var}\n")        
   end
end

#eventRequires(event) ⇒ Object

eventRequires – Method

This method handles the requires events.

Params:

event: This is the event to handle.

Results:

None.


1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
# File 'lib/Soda.rb', line 1561

def eventRequires(event)
   flav = nil

   flav = replaceVars(event['sugarflavor'])
   PrintDebug("Flavor: #{flav}\n")
 
   if (FlavorMatch(flav) == true)
      if (event.key?('children')) 
         handleEvents(cloneEvent(event['children']))
      else
         @rep.log("Found requires event without any children!\n", 
            SodaUtils::WARN)
         @rep.IncTestWarningCount()
      end 
   end
end

#eventRuby(event) ⇒ Object



1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
# File 'lib/Soda.rb', line 1741

def eventRuby(event)
   result = 0

   if (event['content'].empty?)
      return 0
   end
   
   eresult = eval(event['content'])
   eresult = "#{eresult}"

   if (eresult != event['assert'])
      result = false
   else
      result = true
   end

   @rep.Assert(result, "Evaling ruby code results: Expecting:"+
      " \"#{event['assert']}\" found: \"#{eresult}\".\n", 
      @currentTestFile, "#{event['line_number']}")

end

#eventScript(event) ⇒ Object

eventScript – Method

This method handles all script events.

Params:

event: This is the event to handle.

Results:

None.


1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
# File 'lib/Soda.rb', line 1774

def eventScript(event)
   results = 0

   if (event.key?('file'))
      # specified a new csv to file
      if (event.key?('csv'))
         event['csv'] = replaceVars(event['csv'])
         @newCSV.push({"#{event['file']}"=>"#{event['csv']}"})
      end
                                              
      event['file'] = replaceVars(event['file'])
      @fileStack.push(event['file'])
      script = getScript(event['file'])
      if (script != nil)
         parent_script = @currentTestFile
         @currentTestFile = event['file']
         results = handleEvents(script)
         if (@currentTestFile !~ /lib/i && results != 0)
            @rep.IncFailedTest()
         else
            @rep.IncTestPassedCount() if (@currentTestFile !~ /lib/i)
         end
         @currentTestFile = parent_script
      else
         msg = "Failed opening script file: \"#{event['file']}\"!\n"
         @rep.ReportFailure(msg)
      end

      @fileStack.pop()
   end

   if (event.key?('fileset'))
      event['fileset'] = replaceVars(event['fileset'])
      @rep.log("Starting New Soda Fileset: #{event['fileset']}\n")
      getDirScript(event['fileset'])
      @rep.log("Fileset: #{event['fileset']} finished.\n")
   end  
end

#eventVar(event) ⇒ Object

eventVar – Method

This method handles the var event.

Params:

event: This is the event to handle.


1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
# File 'lib/Soda.rb', line 1954

def eventVar(event)

   if (event['set'] == '#stamp#')
      event['set'] = Soda.getStamp()
   end

   if (event['set'] == '#rand#')
      event['set'] = rand(999999)
   end

   setScriptVar(event['var'], event['set']);

end

#eventWait(event) ⇒ Object

eventWait – Method

Results:

return true if a next should be called, else false.


1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
# File 'lib/Soda.rb', line 1914

def eventWait(event)
   result = false

   RestartGlobalTime()

   if ( event.key?('condition') && 
        getStringBool(event['condition']) && 
        event.key?('children') )
                                            
      event['children'].each do |sub_event|
         @rep.log("Waiting Page Load: \n") 
         waitByMultipleCondition(sub_event, event['timeout'])
      end
      
      result = true
   elsif (event.key?('timeout'))
      @rep.log("Waiting Page Load: #{event['timeout']}s\n")
      sleep(Integer(event['timeout']))
      @rep.log("Page Load Finished.\n")
      result = true
   else
      @rep.log("Waiting Page Load: 10s\n")
      sleep(10)
      PrintDebug("Page Load Finished.\n")
      result = true
   end

   RestartGlobalTime()

   return result
end

#eventWhiteList(event) ⇒ Object

eventWhiteList – Method

This method handles the whitelist soda event, by adding or deleting a
item to the whitelist at runtime.

Input:

event: A soda whitelist event.

Output:

None.


1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
# File 'lib/Soda.rb', line 1594

def eventWhiteList(event)
   err = 0

   if (!event.key?('name'))
      @rep.ReportFailure("Missing 'name' attribute for whitelist tag!"+
         "  Line number: #{event['line_number']}!\n")
      err = -1
   elsif (!event.key?('action'))
      @rep.ReportFailure("Missing 'action' attribute for whitelist tag!"+
         "  Line number: #{event['line_number']}!\n")
      err = -1
   elsif (!event.key?('content') && event['action'] =~ /add/i)
       @rep.ReportFailure("Missing 'content' for whitelist tag!"+
         "  Line number: #{event['line_number']}!\n")
       err = -1
   end

   return if (err != 0)

   case (event['action'])
      when /add/i
         found_key = false

         @whiteList.each do |hash|
            next if (!hash.key?(event['name']))
            if (hash.key?(event['name']))
               found_key = true
               break
            end
         end      
         
         if (found_key)
            @rep.ReportFailure("Trying to add whitelist that already"+
               " exists: '#{event['name']}'!\n")
         else
            new_white = {
               'name' => event['name'],
               'data' => event['content']
            }

            @whiteList.push(new_white)
            @rep.log("Adding data to whitelist: '#{new_white['name']}'.\n")
         end
      when /delete/i
         index = -1
         found_key = false

         @whiteList.each do |hash|
            index += 1
            next if (!hash.key?('name'))
            if (hash['name'] == event['name'])
               found_key = true
               break
            end
         end

         if (found_key)
            @whiteList.delete_at(index)
         else
            @rep.ReportFailure("Failed to find whitelist name: "+
               "'#{event['name']}'!\n")
         end
   end
end

#fieldEventAssert(event, fieldType) ⇒ Object

fieldEventAssert – Method

This method handles the field action 'assert'.

Params:

event: The soda event with the field action 'assert'.

Results:

None.


2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
# File 'lib/Soda.rb', line 2272

def fieldEventAssert(event, fieldType)
   msg = ""
   assert_type = ""
   result = 0

   if (event.key?('assertnot'))
      assert_type = 'assertnot'
   else
      assert_type = event['assert']
   end

   case assert_type
      when /assertnot/i
         contains = replaceVars(event['assertnot'] )
         msg = "Asserting that value doesn't exist: \"#{contains}\""
         @rep.log("#{msg}\n")
         result = @rep.Assert(!(fieldType.assert(@curEl, contains)), msg,
            @currentTestFile, "#{event['line_number']}")
      when /enabled/i
         msg = "Asserting that Element is enabled."
         @rep.log("#{msg}\n")
         result = @rep.Assert(fieldType.enabled(@curEl), msg, 
               @currentTestFile, "#{event['line_number']}")
      when /disabled/i
         msg = "Asserting that Element is disabled."
         @rep.log("#{msg}\n")
         result = @rep.Assert(fieldType.disabled(@curEl), msg, 
               @currentTestFile, "#{event['line_number']}")
      else
         contains = replaceVars(event['assert'])
         @rep.log("Asserting value: #{contains}\n")
         msg = "Asserting that value: \"#{contains}\" exists."
         result = @rep.Assert(fieldType.assert(@curEl, contains), msg,
            @currentTestFile, "#{event['line_number']}")
   end

   if (result != 0)
      @FAILEDTESTS.push(@currentTestFile)
   end

end

#FlavorMatch(flavor) ⇒ Object

FlavorMatch – Method

This method checks that all the test requirements meet the current
testing env.

Params:

events: The soda events array.

Results:

returns true if this test can be ran, else false.  Will also return true
if the test has no requires info at all, but a warning message will be
logged.


1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
# File 'lib/Soda.rb', line 1330

def FlavorMatch(flavor)
   match = false
   flavor = flavor.downcase()

   if (flavor =~ /,/)
      flavors = flavor.split(",")
      flavors.each do |sugflav|
         if (sugflav == @sugarFlavor)
            match = true
            break
         end
      end
   else
      if (flavor == @sugarFlavor)
         match = true
      end
   end

   return match
end

#generateWatirObjectStr(event) ⇒ Object

generateWatirObjectStr – Method

This function generates ruby watir code on the fly based on the event.

Params:

event: A soda event.

Results:

returns a string of ruby/watir code.


601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
# File 'lib/Soda.rb', line 601

def generateWatirObjectStr(event)
   str = ""

   # the 'do' is the field to access at this point
   fun = event['do'];

   # if there is a parent Element we are going to use that #
   if (@parentEl.length > 0)
      str = '@parentEl[@parentEl.length - 1]'
   else 
   # otherwise the browser is the parent
      str = '@browser'
   end
   
   str += ".send(:#{fun} "

   # sodalookups contains how each field may be accessed
   $sodalookups[fun].each do |how, avail|
      if (!avail)
         next
      end
      
      if (event.key?(how))
         # replace any variables in how we are going to use it 
         # (useful for dynamic links)
         event[how] = replaceVars(event[how])
         regex = stringToRegex(event[how])
         quote = true
         
         if (regex != event[how])
            quote = false
         end
         
         curhow = event[how]
         if (quote)
            curhow = "'#{event[how]}'"
         end
         
         # despite documentation forms don't support multiple attributes
         if (fun == 'form')
            str += ",:#{how}, #{curhow}"
            break
         end
            
         # support for accessing elements by multiple attributes
         str += ",:#{how}=>#{curhow}"
      end
         # if we have an index which specifies which one to return if there 
         # are more than one
         # if event.key?('index') 
         #  str += ",:index=>#{event['index']}" 
         # end
   end # end each #

   str += ")"

   return str
end

#GetBrowserObject

GetCurrentBrowser – Method

This method get the current Watir browser object.

Input:

None.

Output:

Returns the current watir browser object.


3039
3040
3041
# File 'lib/Soda.rb', line 3039

def GetBrowser()
   return @browser
end

#getDateObject

getDate – Method

This method returns a new formated date string from the current time.

Params:

None.

Results:

returns a string with the current date.


399
400
401
# File 'lib/Soda.rb', line 399

def getDate()
   return Time.now().strftime("%m/%d/%Y")
end

#getDirScript(file) ⇒ Object

getDirScript – Method

This method goes into directory and load xml scripts.

Params:

file: This is the file to open.

Results:

None.

Notes:

Using recursion...  This should be revisited for a better way.


863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
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
# File 'lib/Soda.rb', line 863

def getDirScript(file)
   test_count = 0
   results = 0

   file = File.expand_path(file)

   if (File.directory?(file))
      files = []
      fd = Dir.open(file)
      fd.each do |f|
         files.push("#{file}/#{f}") if (f =~ /\.xml$/i)
      end
      fd.close()

      if (files.empty?)
         @rep.log("No tests found in directory: '#{file}'!\n",
            SodaUtils::WARN)
         @rep.IncTestWarningCount()
         return nil
      end   

      test_count = files.length()
      @rep.log("Fileset: '#{file}' contains #{test_count} files.\n")

      files.each do |f|
         getDirScript(f)
      end
   elsif (File.file?(file))
      if (!(remBlockScript(file)) && 
         ((file !~ /^setup/) || (file !~ /^cleanup/) ) )
         @rep.log("Starting new soda test file: \"#{file}\".\n")

         script = getScript(file)
         if (script != nil)
            parent_test_file = @currentTestFile
            @currentTestFile = file
            results = handleEvents(script)
            if (results != 0)
               @FAILEDTESTS.push(@currentTestFile)
               @rep.IncFailedTest()
            else
               @rep.IncTestPassedCount() if (file !~ /lib/i)
            end
            @currentTestFile = parent_test_file
         else
            msg = "Failed opening script file: \"#{file}\"!\n"
            @rep.ReportFailure(msg)
         end
      end
   end
end

#getEvents(event) ⇒ Object

getEvents – Method

This methos returns a list of events.   Certain events may need to be 
expanded into multiple events.

Params:

event: This event to get...

Results:

returns  a hash of events.


978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
# File 'lib/Soda.rb', line 978

def getEvents(event)
   events  = []
   seed = nil

   # expand lists into multiple events #
   if (event.key?('list'))
      seed = Hash.new()

      event.each do |k,v|
         if (k == 'list' || k == 'by')
            next
         end
         seed[k] = v
      end

      event['list'].each do |k,v|
         cur = seed.dup
         cur[event['by']] = k
         cur['set'] = v
         events.push(cur)
      end
   else
      events.push(event)
   end

   return events
end

#GetFailedTestsObject

GetFailedTests – Method

This method returns a list of failed tests.

Input:

None.

Output:

returns a list of failed tests.  The list can be empty of no tests 
failed.


291
292
293
294
295
# File 'lib/Soda.rb', line 291

def GetFailedTests()
   @FAILEDTESTS.uniq!()

   return @FAILEDTESTS
end

#getField(event, flag = true) ⇒ Object

getField – Method

This method gets the field based on the event from the page.

Params:

event: This is the event to use to get the field.
flag: If true will cause this function to wait for the event.

Results:



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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/Soda.rb', line 523

def getField(event, flag = true)
   str = nil
   field = nil

   # this is to handle how the IE dom accesses links #
   if ( (Watir::Browser.default =~ /ie/i) && (event.key?('href')) )
      tmp_href = event['href']
      event = SodaUtils.IEConvertHref(event, @browser.url())
      @rep.log("Converted Soda test href: '#{tmp_href}' to IE href:"+
         " '#{event['href']}'.\n")
      end
   str = generateWatirObjectStr(event)

   # if the timeout is set use the specified timeout for accessing the 
   # field otherwise allow 15 seconds
   timeout = (event.key?('timeout'))? Integer(event['timeout']): 15
   required = (event.key?('required'))? SodaField.getStringTrue(event['required']): true

   event['required'] = required

   if (event.key?('exist'))
      event['exists'] = event['exist']
   end

   if (event.key?('exists'))
      exists = getStringBool(event['exists'])

      if (exists == true)
         field = waitFor(eval(str), event['do'], timeout, true)
      
         if (field != nil)
            @rep.Assert(true, "#{event['do']} element exists.", 
               @currentTestFile)
         else
            @rep.Assert(false, "Failed to find #{event['do']} element!", 
               @currentTestFile, "#{event['line_number']}")
            @FAILEDTESTS.push(@currentTestFile)
         end
      else
         field = waitFor(eval(str), event['do'], timeout, false)      
         if (field == nil)
            @rep.Assert(true, "#{event['do']} element does not exist as "+
               "expected.", @currentTestFile)
         else
            @rep.Assert(false, "#{event['do']} exists when it is not "+
               "expected to!", @currentTestFile, "#{event['line_number']}")
            @FAILEDTESTS.push(@currentTestFile)
         end
      end
   else
      # use for wait tag
      if (flag == false)
         field = waitFor(eval(str), event['do'], timeout, required, false)
      else
         # get the field
         field = waitFor(eval(str), event['do'], timeout, required)
      end
   end

   if ( (required != true) && (field == nil) )
      @rep.log("Element not found, but was tagged as: required ="+
         " \"#{required}\".\n")
   end

   return field
end

#getRightCSV(event) ⇒ Object

getRightCSV – Method

This method replaces the default csv with specified event.

Params:

event: This is the event to replace the csv with.

Results:

None.


955
956
957
958
959
960
961
962
963
964
# File 'lib/Soda.rb', line 955

def getRightCSV(event)   
   for csv in @newCSV
      csv.each do |runfile, runcsv|
         if (@fileStack[@fileStack.length - 1] == runfile)
            event['file'] = runcsv
            @newCSV.delete(runfile)  
         end
      end
   end
end

#getScript(file, is_restart = false) ⇒ Object

getScript – Method

This method loads and soda XML script and parses it and returns the 
Soda Meta Data.

Params:

file: A soda xml test file.
is_restart: true/false, tells us that this is a restart test.

Results:

on success returns a XML DOM Document, or nil on error.


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
# File 'lib/Soda.rb', line 775

def getScript(file, is_restart = false)
   script = nil
   valid_xml = true
   script_check = false
   err = 0

   if (!File.extname(file) == '.xml')
       msg = "Failed trying to parse file: \"#{file}\": Not a valid " +
         " XML file!\n"
      @rep.ReportFailure(msg)
      script = nil
      valid_xml = false
   end

   if (valid_xml)
      $run_script = file
      PrintDebug("Parsing Soda test file: \"#{file}\".\n")
      begin
         checker = SodaTestCheck.new(file, @rep)
         script_check = checker.Check()
         if (!script_check)
            script = nil
            @rep.IncSkippedTest()
         else
            script = SodaXML.new.parse(file)
         end
      rescue Exception => e
         @rep.ReportException(e, file)
         script = nil
      ensure
      end
   end

   return script
end

#getScriptVar(name, default = '') ⇒ Object

getScriptVar – Method

This method retrieves variables used during script execution if the 
variable is not set then the default value is returned variables are 
specified in a script as {@myvar} to set this variable use var='myvar'
for CSV variables it would be {@record.csvvar}
The following attribues may have variables used within them 
*assert
*accessor attributes (href, id, value ...)
*contains

Params:

name: The name of the var to get the value from.
default: If the value isn't already set then it is set to this value.

Results:

returns the value for the given name.

Notes:

This method will also overwrite any csv value of the key for that value
is in the @hiJacks hash for this class.


461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
# File 'lib/Soda.rb', line 461

def getScriptVar(name, default='')
   val = default
   names = nil
   is_csv = false
   org_name = name
   tmp_name = org_name.gsub(/^\./, "")

   # if it contains a '.' it must be a CSV variable so it is stored as a 
   # hash
   if ( (name.index('.')) && (name !~ /^global/) )
      names = name.split('.')
      name = names[0]
      is_csv = true
   end

   # make sure we have a variable set
   if (@vars.key?(name))
      # if we have an array for names it means it was a CSV variable
      if (names)
         val =  @vars[name][names[1]]
      else
         val =  @vars[name]
      end
   else
      begin
         val = "Soda unknown script key: \"#{tmp_name}\"!"
         msg = "Failed to find script variable by name: \"#{tmp_name}\"!\n"
         @rep.ReportFailure(msg)
         raise(msg)
      rescue Exception => e
         @rep.ReportException(e)
      ensure

      end
   end
 
   if (@hiJacks.key?(org_name))
      PrintDebug("High Jacking CSV variable: \"#{org_name}\" from value:" +
         " \"#{val}\" to \"#{@hiJacks["#{org_name}"]}\"\n")
      val = @hiJacks["#{org_name}"]
   else
      tmp_val = "#{val}"
      tmp_val = tmp_val.gsub("\n", '\n')
      PrintDebug("Value for \"#{tmp_name}\" => \"#{tmp_val}\".\n")
   end

   val = "" if (val == nil) # default it to be an empty string. #

   return val
end

#getStampObject

getStamp – Method

This method creates a new formated datetime string from the current time.

Params:

None.

Results:

reutrns a formated string with the current datetime.


384
385
386
# File 'lib/Soda.rb', line 384

def getStamp()
   return Time.now().strftime("%y%m%d_%H%M%S")
end

#getStringBool(value) ⇒ Object

getStringBool – Method

This method checks to see of the value passed to it proves to be positive
in most any way.

Params:

value: This is a string that will prove something true or false.

Results:

returns true if the value is a form of being 'positive', or false.
If the value isn't a string then the value is just returned....

Notes:

This is a total hack, we should be throw an exception if the value is
something other then a string...  Will come back to this later...


1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
# File 'lib/Soda.rb', line 1264

def getStringBool(value)
   if (value.is_a?(String))
      value.downcase!

      if (value == 'true' or value == 'yes' or value == '1')
         return true
      else
         return false
      end 
   end

   return value
end

#handleEvents(events) ⇒ Object

handleEvents – Method

This is the heart of event handling used as a switch statement instand
of classes  to keep it simple for QA to modify.

Params:

events: The result of the getScript method, really all the xml events.

Results:

A big flip'n sloppy mess!

Notes:

Total hack!  This needs to be redone from the ground up it is a total
sloppy mess!


2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
# File 'lib/Soda.rb', line 2439

def handleEvents(events)
   browser_closed = false
   result = 0
   jswait = true
   result = 0
   js_fired = false
   exception_event = nil 

   for next_event in events
      if (@exceptionExit != false)
         @rep.log("Exception occured, now exiting...\n")
         @exceptionExit = false
         return -1
      end

      events = getEvents(next_event)

      for event in events
      begin
         @rep.AddEventCount()
         @curEl = nil
         fieldType = nil
 
         event = SodaUtils.ConvertOldAssert(event, @rep, @currentTestFile)
         RestartGlobalTime()
         crazyEvilIETabHack() 

         if (event.key?('set') && event['set'].is_a?(String) && 
            event['set'].index('{@') != nil)

            default = event.key?('default')?event['default']: ''
            var_temp = replaceVars(event['set'], default)

            # if set nil to object, nothing to do just skip
            if (var_temp == nil)
               break
            end

            event['set'] = var_temp
         end

         if (event.key?('assert')) 
            event['assert'] = replaceVars(event['assert'])
            event['assert'] = stringToRegex(event['assert'])
         elsif (event.key?('assertnot'))
            event['assertnot'] = replaceVars(event['assertnot'])
            event['assertnot'] = stringToRegex(event['assertnot'])
         end 
        
         case event['do']
            when "exception"
               PrintDebug("Found Exception Handler.\n")
               exception_event = event
               next
            when "breakexit"
               @breakExit = true
               next
            when "dialog"
               eventDialog(event)
               next
            when "whitelist"
               eventWhiteList(event)
               next
            when "sugarwait"
               SodaUtils.WaitSugarAjaxDone(@browser, @rep)
               next
            when "condition"
               eventCondition(event)
               next
            when "ruby"
               eventRuby(event)
               next
            when "wait"
               if (eventWait(event) == true) 
                  next
               end
            when "browser" 
               err = eventBrowser(event)
               if (err['error'] != 0)
                  result = -1
               end

               next 
            when "requires"
               eventRequires(event)
               next 
            when "attach"
               eventAttach(event)
               next
            when "csv"
               eventCSV(event) 
               next
            when "comment"
               next
            when "timestamp"
               @vars['stamp'] = Time.now().strftime("%y%m%d_%H%M%S")
               next
            when "script"
               eventScript(event)
               next
            when "var"
               eventVar(event)
               next
            when "javascript"
               eventJavascript(event)
               next
            when "puts"
               eventPuts(event)
               next 
            when "mouseclick" 
               eventMouseClick(event)
               next
            when "filefield"
               fieldType = SodaFileField
               eventFileField(event)
               next 
            when "textfield"
               fieldType = SodaField
               event['do'] = 'text_field'
               @curEl = getField(event)
            when "textarea" 
               fieldType = SodaField
               event['do'] = 'text_field'
               @curEl = getField(event)
            when "checkbox"
               fieldType = SodaCheckBoxField
               event['do'] = 'checkbox'
               @curEl = getField(event)
            when "select"
               fieldType = SodaSelectField
               event['do'] = 'select_list'
               @curEl = getField(event)
           when "radio"
               fieldType = SodaRadioField
               event['do'] = 'radio'
               @curEl = getField(event)
            when "link"
               fieldType = SodaField 
               @curEl = eventLink(event)
            when "td"
               fieldType = SodaField
               event['do'] = 'cell'
               @curEl = getField(event)
            when "tr"
               fieldType = SodaField
               event['do'] = 'row'
               @curEl = getField(event)
            when "div"
               fieldType = SodaField
               @curEl = getField(event)
            when "hidden"
               fieldType = SodaField
               @curEl = getField(event)
            when "li"
               fieldType = SodaLiField
               @curEl = getField(event)
            else
               if (@SIGNAL_STOP != false)
                  exit(-1)
               end
              
               # if its none of the above assume it is a field
               fieldType = SodaField
               @curEl = getField(event)
         end # end case #

         if ( (@curEl == nil) && (event['required'] == false) )
            next
         end

         if (@curEl == nil)
            if (event.key?("exists"))
               exists = getStringBool(event['exists'])
              
               if (exists != false)
                  e_dump = SodaUtils.DumpEvent(event)
                  @rep.log("No Element found for event!\n", 
                     SodaUtils::ERROR)
                  @rep.log("Event Dump for unfound element: #{e_dump}!\n",
                     SodaUtils::EVENT)
               end
            else
               e_dump = SodaUtils.DumpEvent(event)
               @rep.ReportFailure("No Element found for event!\n")
               @rep.log("Event Dump for unfound element: #{e_dump}!\n", 
                  SodaUtils::EVENT)
            end

            next
         end

         # If we have a field here is the default actions 
         # that can be done on it 
         if (@curEl)
            js_fired = eventFieldAction(event, fieldType)
         end

         jswait = true
         if (event.key?("jscriptevent") && (js_fired != true) && 
            (replaceVars(event['jscriptevent']) == "onkeyup"))
            if (event.key?('jswait'))
               jswait = false if (event['jswait'] =~ /false/i)
            end

            js = replaceVars(event['jscriptevent'])
            fieldType.jsevent(@curEl, js, jswait)
         elsif (event.key?("jscriptevent") && (js_fired != true))
            if (event.key?('jswait'))
               jswait = false if (event['jswait'] =~ /false/i)
            end
            js = replaceVars(event['jscriptevent'])
            fieldType.jsevent(@curEl, js, jswait)
         end

         if (browser_closed != true && jswait != false)
            CheckJavaScriptErrors()
         end

         rescue Exception=>e
            @FAILEDTESTS.push(@currentTestFile)
            @exceptionExit = true
            @rep.log("Exception in test: \"#{@currentTestFile}\", Line: " +
               "#{event['line_number']}!\n", SodaUtils::ERROR)
            @rep.ReportException(e, @fileStack[@fileStack.length - 1]);
            e_dump = SodaUtils.DumpEvent(event)
            @rep.log("Event Dump From Exception: #{e_dump}!\n", 
               SodaUtils::EVENT)

            if (exception_event != nil)
               @rep.log("Running Exception Handler.\n", SodaUtils::WARN)
               @rep.IncTestWarningCount()
               @exceptionExit = false
               handleEvents(exception_event['children'])
               @rep.log("Finished Exception Handler.\n", SodaUtils::WARN)
               @rep.IncTestWarningCount()
               @exceptionExit = true
            end

            result = -1
         ensure
            if (@exceptionExit)
               @exceptionExit = false
               return -1
            end
         end # end rescue & ensure #
      end # end event's for loop #
   end # end top most for loop #


   if (exception_event != nil)
      if (exception_event.key?('alwaysrun'))
         run = getStringBool(exception_event['alwaysrun'])
         if (run)
            PrintDebug("Exception Handler: alwaysrun = '#{run}'.\n")
            PrintDebug("Running Exception Handler.\n")
            result  = handleEvents(exception_event['children'])
            PrintDebug("Exception Handler: Finished.\n")
         end
      end
   end

   return result
end

#kindsOfBrowserAssert(event, flag = true) ⇒ Object

kindsOfBrowserAssert – Method

This method does an assert on the text contained in the web browser.
The assert can be either a regexp or a string.

Input:

event: This is a soda event.
flag: true or false, for an assert or an assertnot

Output:

returns -1 on error else 0 on success.


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
# File 'lib/Soda.rb', line 1178

def kindsOfBrowserAssert(event, flag = true)
    msg = "Unknown Browser Assert!"
    match = nil
    ass = nil
    contains = ""
    is_regex = false
    result = 0

    if (event['assert'].kind_of? Regexp)
       is_regex = true
       contains = event['assert'].to_s()

       if (event['assert'] != nil)
          match = event['assert'].match(@browser.text)
          if (match != nil)
             ass = true
          else
             ass = false
          end
       else
          @rep.ReportFailure("Failed to create regex!\n")
          e_dump = SodaUtils.DumpEvent(event)
          @rep.log("Event Dump: #{e_dump}!\n", SodaUtils::EVENT)
          ass = false
          result = -1
       end
    else
       contains = replaceVars(event['assert'] )
       # assert the text in specified area
       if (@parentEl.length > 0)
          ass = @parentEl[@parentEl.length-1].text.include?(contains)
       else
          ass = @browser.text.include?(contains)
       end
    end

    if (flag)
       if (!is_regex)
          msg = "Checking that the Browser does contain the text: "+
             "\"#{contains}\""
       else
           msg = "Checking that the Browser does match regex: "+
             "\"#{contains}\""     
       end

       result = @rep.Assert(ass, msg, @currentTestFile, 
             "#{event['line_number']}")
       if (result != 0)
          @FAILEDTESTS.push(@currentTestFile)
       end
    else
       if (!is_regex)
          msg = "Checking that browser does not contain text:"+
             " \"#{contains}\" in page."
       else
          msg = "Checking that browser regex doesn not match: "+
             " \"#{contains}\" in page."
       end

       result = @rep.Assert(!ass, msg, @currentTestFile, 
             "#{event['line_number']}")
       if (result != 0)
          @FAILEDTESTS.push(@currentTestFile)
       end
    end

    return result
end

#MouseClick(x_pos, y_pos) ⇒ Object

MouseClick – Method

This method stimulates a mouse click operation.

Params:

x: The x cord position.
y: The y cord position.

Results:

None.


369
370
371
# File 'lib/Soda.rb', line 369

def MouseClick(x_pos,y_pos)
   @autoit.MouseClick("left", x, y)
end

#NewBrowserObject



225
226
227
228
229
230
231
232
233
234
235
236
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/Soda.rb', line 225

def NewBrowser()
   err = 0

   RestartGlobalTime()

   if ( @current_os =~ /WINDOWS/i && 
      @params['browser'] =~ /ie|firefox/i ) 
      require 'win32ole'
      @autoit = WIN32OLE.new("AutoItX3.Control")
   end

   if (@params['browser']) 
      Watir::Browser.default = @params['browser']
   end

   # sleeping here because watir has issues if a new browsers comes up
   # after a firefox process is killed.
   sleep(10)

   if (@params['browser'] =~ /firefox/i)
      for i in 0..10 do
         if (@params['profile'] != nil)
            result = SodaFireFox.CreateFireFoxBrowser(
               {:profile => "#{@params['profile']}"})
         else
            result = SodaFireFox.CreateFireFoxBrowser()
         end
         
         if (result['browser'] != nil)
            @browser = result['browser']
            break
         end

         sleep(2)
      end

      if (@browser == nil)
         SodaUtils.PrintSoda("Failed to create new firefox browser!\n",
            SodaUtils::ERROR)
         SodaUtils.PrintSoda("Exception Message: " +
            "#{result['exception'].message}\n", SodaUtils::ERROR)
         SodaUtils.PrintSoda("BackTrace: #{result['exception'].backtrace}"+
            "\n", SodaUtils::ERROR)
         err = -1
      end

      @browser.execute_script(SodaUtils::FIREFOX_JS_ERROR_CLEAR)
   else
      @browser = Watir::Browser.new()
   end

   return err
end

#PrintDebug(str, level = SodaUtils::LOG) ⇒ Object

PrintDebug – Method

This method only logs a message to the soda log if the debug flag is set.

Params:

str: The message to debug.
level: The debug level to report.

Results:

Always returns 0.


329
330
331
332
333
334
335
# File 'lib/Soda.rb', line 329

def PrintDebug(str, level = SodaUtils::LOG)
   if (@debug != false)
      @rep.log(str, level)
   end

   return 0
end

#remBlockScript(test_file) ⇒ Object

remBlockScript – Method

This method checks to see of the test file is in the 
blockScriptsList.txt to decide if the test can be ran.

Params:

file: This is the soda test file that were are checking to see of we can
   run or not.

Results:

returns true if the file is to be blocked, else false.


928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
# File 'lib/Soda.rb', line 928

def remBlockScript(test_file)
   result = false 

   @blocked_files.each do |bhash|
      tmp_file = File.basename(test_file)
      if (tmp_file =~ /#{bhash['testfile']}/)
         @rep.log("Blocklist: blocking file: \"#{test_file}\".\n")
         @rep.IncBlockedTest()
         result = true
         break
      end
   end

   return result
end

#replaceVars(str, default = '') ⇒ Object

replaceVars – Method

This method replaces a {@varname} with the appropriate variable.

Params:

str: The string to replace words in.
default: The default to replace with.

Results:

returns an empty string if the var is the csv file is nothing, else a 
new string with the vars replaced.


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
# File 'lib/Soda.rb', line 1019

def replaceVars(str, default='')
   org_str = str
   vars_hash = Hash.new()
   result = "#{str}".scan(/\{@[\w\.]+\}/i)

   result.each do |var|
      next if ( (var == nil) or (var.empty?) ) 
      var = var.gsub(/^\{@/, "")
      var = var.gsub(/\}$/, "")
      tmp = getScriptVar(var, default)
      
      if (tmp == nil)
         tmp = "Unknown Var: '#{var}'"
         @rep.ReportFailure("Error trying to access an unknown script var:"+
            " '#{var}'!\n")
      end

      vars_hash[var] = tmp
   end

   vars_hash.each do |k, v|
      str = str.gsub(/\{@#{k}\}/, v)
   end

   if (org_str != str)
      tmp_org_str = "#{org_str}"
      tmp_org_str = tmp_org_str.gsub("\n", '\n')
      tmp_str = "#{str}"
      tmp_str = tmp_str.gsub("\n", '\n')
      PrintDebug("Replacing string '#{tmp_org_str}' with '#{tmp_str}'\n")
   end

   return str  
end

#RestartBrowserTest(suitename) ⇒ Object

RestartBrowserTest – Method

This method checks to see if the browser needs to be restarted.

Input:

None.

Output:

None.


822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
# File 'lib/Soda.rb', line 822

def RestartBrowserTest(suitename)

   RestartGlobalTime()

   if (@params['browser'] =~ /firefox/i)
      SodaFireFox.KillProcesses()
   end
   
   err = NewBrowser()
   if (err != 0)
      print "(!)Failed to restart browser!\n"
   end

   if (!@restart_test.empty?)
      resultdir = "#{@resultsDir}/#{suitename}"
      @rep = SodaReporter.new(@restart_test, @saveHtml, resultdir,
         0, nil, false);
      @rep.log("Restarting browser.\n")
      restart_script = getScript(@restart_test)
      handleEvents(restart_script)
      @rep.log("Finished: Browser restart.\n")
      @rep.EndTestReport()
   end

   RestartGlobalTime()
end

#RestartGlobalTimeObject

RestartGlobalTime – Method

This method reset the global time, for the watchdog timer.

Input:

None.

Output:

None.


217
218
219
220
221
# File 'lib/Soda.rb', line 217

def RestartGlobalTime()
   $mutex.synchronize {
      $global_time = Time.now()
   }
end

#run(file, rerun = false, genhtml = true, suitename = nil) ⇒ Object

run – Method

This method executes a test file.

Params:

file: The Soda test file.
rerun: true/false, this tells soda that this tests is a rerun of a
   failed test.
suitename: The name of the suite to group the results into.

Results:

returns a SodaReport object.


2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
# File 'lib/Soda.rb', line 2733

def run(file, rerun = false, genhtml = true, suitename = nil)
   result = 0
   master_result = 0
   thread_soda = nil
   thread_timeout = (60 * 6) # 6 minutes #
   time_check = nil
   resultsdir = nil
   blocked = false

   if (suitename != nil)
      resultsdir = "#{@resultsDir}/#{suitename}"
   else
      resultsdir = @resultsDir
   end

   @currentTestFile = file
   @exceptionExit = false      
   @fileStack.push(file)

   if (@browser == nil)
      NewBrowser()
   end

   @rep = SodaReporter.new(file, @saveHtml, resultsdir, 0, nil, rerun);
   SetGlobalVars()
   blocked = remBlockScript(file)
 
   if (!blocked)
      checker = SodaTestCheck.new(file, @rep)
      script_check = checker.Check()
      if (!script_check)
         script = nil
      else
         script = getScript(file)
      end
   else 
      script = nil
   end

   if (script != nil) 
      @currentTestFile = file
      thread_soda = Thread.new {
         result = handleEvents(script)
      }

      while (thread_soda.alive?)
         $mutex.synchronize {
            time_check = Time.now()
            time_diff = time_check - $global_time
            time_diff = Integer(time_diff)

            if (time_diff >= thread_timeout)
               msg = "Soda watchdog timed out after #{time_diff} seconds!\n"
               @GotWatchDog = true
               @rep.ReportFailure(msg)
               PrintDebug("Global Time was: #{$global_time}\n")
               PrintDebug("Timeout Time was: #{time_check}\n")
               @rep.IncTestWatchDogCount()
               begin
                  result_dir = @rep.GetResultDir()
                  shooter = SodaScreenShot.new(result_dir)
                  image_file = shooter.GetOutputFile()
                  @rep.log("ScreenShot taken: #{image_file}\n")
               rescue  Exception => e
                  @rep.ReportException(e)
               ensure
               end

               result = -1
               thread_soda.exit()
               break
            end
         }
         sleep(10)
      end

      if (result != -1)
         thread_soda.join()
      end

      if (result != 0)
         master_result = -1
      else
         @rep.IncTestPassedCount()
      end
   else
      if (!blocked)
         msg = "Failed trying to run soda test: \"#{@currentTestFile}\"!\n"
         @rep.IncFailedTest()
         @rep.ReportFailure(msg)
      end
   end

   @rep.SodaPrintCurrentReport()
   @rep.EndTestReport()
   @rep.ReportHTML() if (genhtml)

   return master_result
end

#RunAllSuites(suites) ⇒ Object

RunAllSuites – Method

This function run a list of suite files as suites, not as tests.

Input:

suites: An array of Soda suite files to be ran.

Output:

returns a hash with the results from the ran suites.


2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
# File 'lib/Soda.rb', line 2844

def RunAllSuites(suites)
   results = {}
   err = 0
   global_err = 0
   indent = " " * 2
   indent2 = "#{indent}" * 2
   indent3 = "#{indent}" * 4
   hostname = `hostname`
   hostname = hostname.chomp()

   suites.each do |s|
      print "SUITE: #{s}\n"
      base_suite_name = File.basename(s)
      if (results.key?(base_suite_name))
         suite_dup_id = 1
         while (results.key?("#{base_suite_name}-#{suite_dup_id}"))
            suite_dup_id += 1
         end
         base_suite_name = "#{base_suite_name}-#{suite_dup_id}"
      end

      RestartGlobalTime()
      results[base_suite_name] = RunSuite(s)
      RestartGlobalTime()
   end

   if (results.empty?)
      return results
   end

   time = Time.now()
   time = "#{time.to_i}-#{time.usec}"
   suite_report = "#{@resultsDir}/#{hostname}-#{time}-suite.xml"
   fd = File.new(suite_report, "w+")
   fd.write("<data>\n")

   RestartGlobalTime()

   results.each do |k,v|
      fd.write("\t<suite>\n")
      fd.write("\t#{indent}<suitefile>#{k}</suitefile>\n")

      if (v.key?("Suite Failure"))
         v.each do |sek, sev|
            name = sek
            name = name.gsub(" ", "_")
            fd.write("\t#{indent2}<#{name}>#{sev}</#{name}>\n")
         end 
      else
         v.each do |testname, testhash|
            fd.write("\t#{indent2}<test>\n")
            fd.write("\t#{indent3}<testfile>#{testname}</testfile>\n")
            testhash.each do |tname, tvalue|
               if (tname == "result")
                  err = -1 if (tvalue.to_i != 0)
               end
               new_name = "#{tname}"
               new_name = new_name.gsub(" ", "_")
               fd.write("\t#{indent3}<#{new_name}>#{tvalue}</#{new_name}>\n")
            end
            fd.write("\t#{indent2}</test>\n")
         end
      end
      fd.write("\t</suite>\n")
   end

   fd.write("</data>\n")
   fd.close()

   RestartGlobalTime()

   return err
end

#RunSuite(suitefile) ⇒ Object



2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
# File 'lib/Soda.rb', line 2921

def RunSuite(suitefile)
   parser = nil
   doc = nil
   test_order = 0
   test_since_restart = 0
   result = {}
   tests = []
   suite_name = File.basename(suitefile, ".xml")

   print "Running Suite: #{suitefile}\n"

   begin
      fd = File.new(suitefile)
      doc = REXML::Document.new(fd)
      doc = doc.root

      doc.elements.each do |node|
         next if (node.name =~ /text/i)
         next if (node.name =~ /comment/i)
         
         if (node.name !~ /script/i)
            raise "Using unsupported Soda suite element: '#{node.name}'"+
               " in suite file: '#{suitefile}'!"
         end

         attrs = {}
         node.attributes.each do |k,v|
            attrs[k] = "#{v}"
         end

         if (attrs.key?('file'))
            tests.push(attrs['file'])
         elsif (attrs.key?('fileset'))
            files = File.join(attrs['fileset'], "*.xml")
            files = Dir.glob(files).sort_by{|f| File.stat(f).mtime}
            files.each do |f|
               tests.push(f)
            end
         end
      end

      fd.close()
   rescue Exception => e
      SodaUtils.PrintSoda(e.message, SodaUtils::ERROR)
      err_hash = {
         'result' => -1,
         'Suite Failure' => true,
         'Suite Error' => "#{e.message}"
      }
      return err_hash
   ensure
   end   

   tests.each do |test|
      if ((@restart_count > 0) && (test_since_restart >= @restart_count))
         RestartBrowserTest(suite_name)
         test_since_restart = 0
         SodaUtils.PrintSoda("(*)Browser restart finished.\n")
      end

      test_order += 1
      tmp_result = {}
      tmp_result['result'] = run(test, false, true, suite_name)
      tmp_result['Test_Order'] = test_order
      tmp_result.merge!(@rep.GetRawResults)
      
      if (tmp_result['Test Failure Count'].to_i != 0)
         tmp_result['result'] = -1
      elsif (tmp_result['Test JavaScript Error Count'].to_i != 0)
         tmp_result['result'] = -1
      elsif (tmp_result['Test Assert Failures'].to_i != 0)
         tmp_result['result'] = -1
      elsif (tmp_result['Test Exceptions'].to_i != 0)
         tmp_result['result'] = -1
      end

      tmp_result['Real_Test_Name'] = test
      test_basename = File.basename(test, ".xml")
      logfile = tmp_result['Test Log File']

      if (logfile =~ /#{test_basename}-\d+/)
         logfile =~ /#{test_basename}(-\d+)/
         ran_test_name = "#{test_basename}#{$1}"
         ran_test_name << ".xml"
      else
         ran_test_name = test
      end

      result[ran_test_name] = tmp_result
      @rep.ZeroTestResults()

      test_dir = File.dirname(test)
      if (test_dir !~ /lib/i)
         test_since_restart += 1
      end

      if (@testDelay)
         SodaUtils.PrintSoda("Starting Test Delay...\n")
         sleep(10)
         SodaUtils.PrintSoda("Finished Test Delay.\n")
      end

   end

   return result
end

#send_keys(key_string) ⇒ Object

send_keys –

This function sends keyboard keys to firefox(IE has support this method)

Params:

key_string: A string of keys to send.

Results:



347
348
349
350
351
352
353
354
355
# File 'lib/Soda.rb', line 347

def send_keys(key_string)      
   case Watir::Browser.default
      when /ie|firefox/i
         @autoit.WinActivate(@browser.title())
         @autoit.Send(key_string)
      else
         PrintDebug("Send_keys: Unknown Browser!", SodaUtils::ERROR)
   end          
end

#SetGlobalVarsObject

SetGlobalVars - Method

This method reads all the vars passed to the constructor and sets them
up for use for all soda tests.

Params:

None.

Results:

None.


310
311
312
313
314
315
# File 'lib/Soda.rb', line 310

def SetGlobalVars()
   @globalVars.each do |k,v|
      name = "global.#{k}"
      setScriptVar(name, v)
   end
end

#SetReporter(reporter) ⇒ Object

SetReporter – method

This method sets the reporter object for soda.  Really only used for
sodamachine.

Input:

reporter: This is the reporter object for soda to use.

Results:

None.


2715
2716
2717
# File 'lib/Soda.rb', line 2715

def SetReporter(reporter)
   @rep = reporter
end

#setScriptVar(name, value) ⇒ Object

setScriptVar – Method

This method sets variables used during script execution by the scripts
themselves.

Params:

name: The key in the @vars to set.
value: The new value to the for the given key.

Results:

None.


416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/Soda.rb', line 416

def setScriptVar(name, value)
   @vars[name] = value
   msg = "Setting key: \"#{name}\" =>"

   if (value.instance_of?(Hash))
      msg << " Hash:{"
      value.each do |k ,v|
         tmp_k = k.gsub("\n", '\n')
         tmp_v = v.gsub("\n", '\n')
         msg << "'#{tmp_k}'=>'#{tmp_v}',"
      end
      msg = msg.chop()
      msg << "}\n" 
   else
      tmp_value = "#{value}"
      tmp_value = tmp_value.gsub("\n", '\n')
      msg << " \"#{tmp_value}\"\n"
   end

   PrintDebug(msg)
end

#stringToRegex(str) ⇒ Object

stringToRegex – Method

This method creates a Regexp object from a string.

Params:

str: The string to convert to a regex.

Results:

returns the passed string if it is not a regex str, else a new regex
object is returned.


1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
# File 'lib/Soda.rb', line 1066

def stringToRegex(str)
   result = nil

   if (SodaUtils.isRegex(str))
      result = SodaUtils.CreateRegexFromStr(str)
      if (result == nil)
         @rep.ReportFailure("Failed trying to convert string to regex:"+
            " String: '#{str}'!\n") 
      end
   else
      result = str
   end

   return result
end

#waitByMultipleCondition(event, timeout = 10) ⇒ Object

waitByMultipleCondition – Method

This method waits until the multiple condition is matchedv.

Params:

event: The event to check.
timeout: The number of seconds to wait.

Results:

None.

Notes:

This method looks like a total hack, need to revist this later.


737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
# File 'lib/Soda.rb', line 737

def waitByMultipleCondition(event, timeout = 10)            
   case event['do']
      when "textfield"
         event['do'] = 'text_field'
      when "textarea"
         event['do'] = 'text_field'
      when "select"
         event['do'] = 'select_list'
      when "filefield"
         event['do'] = 'file_field'
   end            
   
   event['timeout'] = timeout 
   @curEl = getField(event, false)           
   
   if (event.key?('children'))
      @parentEl.push(@curEl)  
      event['children'].each do |sub_event|
         waitByMultipleCondition(sub_event, event['timeout'])
      end
   end

   @parentEl.pop()
end

#waitFor(field, name, timeout = 15, required = true, flag = true) ⇒ Object

waitFor – Method

Waits for a field to be present this ensures that a field is on the page
when we expect it to *field is the field we want *name is a human 
readable name for the field *timeout is the number of seconds we are 
willing to wait for the field if timeout is set to 0 or -1 then we 
won't raise an exception if we can't find the field and we consider the 
field optional.

Params:

field: This is the name of the field on the page.
name: The human readable field name.
timeout: Number of seconds to wait for the field.
required: 
flag:

Results:

returns nil on error, or field on success.


680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
# File 'lib/Soda.rb', line 680

def waitFor(field, name, timeout = 15, required = true, flag = true)
   start_time = Time.now
   result = nil
   found_field = false
   
   until (found_field = field.exists?) do
      sleep(0.5)
      # if the timeout is > 0 then we really wanted the field to be there 
      # so raise an exception otherwise the field is considered optional
      # used for "wait" tag

      if ( (Time.now - start_time > timeout) && (found_field != true))
         if (flag == false)
            msg = "waitFor: Element not found: \"#{name}\"!\n"
            @rep.log(msg)
            break
         end

         if ($link_not_assert)         
            @rep.log("Assertion Passed\n");
            $link_not_assert = false
            break
         elsif (required && (found_field != true))
            @rep.log("waitFor: Element not found: \"#{name}\""+
               " Timedout after #{timeout} seconds!\n")
            @FAILEDTESTS.push(@currentTestFile)
            break
         else
            break
         end
      end
   end
   
   if (flag == false)
      @rep.log("waitFor found Element: \"#{name}\".\n");
   end

   result = field if (found_field)

   return result
end