Class: Sahi::Browser

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Browser

Takes browser_type as specified in sahi/userdata/config/browser_types.xml (name of browserType) - RECOMMENDED

OR

Takes browser_path, browser_options and browser_executable - NOT RECOMMENDED Various browser options needed to initialize the Browser object are:

Internet Explorer 6&7: browser_path = “C:\Program Files\Internet Explorer\iexplore.exe” browser_options = “”

browser_executable = "iexplore.exe"

Internet Explorer 8: browser_path = “C:\Program Files\Internet Explorer\iexplore.exe” browser_options = “-nomerge”

browser_executable = "iexplore.exe"

Firefox:

browser_path = "C:\\Program Files\\Mozilla Firefox\\firefox.exe"
browser_options = "-profile $userDir/browser/ff/profiles/sahi0 -no-remote"
browser_executable = "firefox.exe"

Chrome: userdata_dir = “D:/sahi/sf/sahi_993/userdata” # path to Sahi’s userdata directory.

browser_path = "C:\\Documents and Settings\\YOU_THE_USER\\Local Settings\\Application Data\\Google\\Chrome\\Application\\chrome.exe"
browser_options = "--user-data-dir=# {userdata_dir}\browser\chrome\profiles\sahi$threadNo"
browser_executable = "chrome.exe"

Safari: browser_path = “C:\Program Files\SafariSafari.exe” browser_options = “”

browser_executable = "safari.exe"

Opera: browser_path = “C:\Program Files\Opera\opera.exe” browser_options = “”

browser_executable = "opera.exe"


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/sahi.rb', line 65

def initialize(*args)
  @proxy_host = "localhost"
  @proxy_port = 9999
  if args.size == 3
    @browser_path = args[0]
    @browser_options = ars[1]
    @browser_executable = args[2]
  elsif args.size == 1
    @browser_type = args[0]
  end
  @popup_name = nil
  @domain_name = nil
  @sahisid = nil
  @print_steps = false
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



211
212
213
# File 'lib/sahi.rb', line 211

def method_missing(m, *args, &block)  
  return ElementStub.new(self, m.to_s, args)
end

Instance Attribute Details

#domain_nameObject

Returns the value of attribute domain_name.



25
26
27
# File 'lib/sahi.rb', line 25

def domain_name
  @domain_name
end

Returns the value of attribute popup_name.



25
26
27
# File 'lib/sahi.rb', line 25

def popup_name
  @popup_name
end

Returns the value of attribute print_steps.



25
26
27
# File 'lib/sahi.rb', line 25

def print_steps
  @print_steps
end

#proxy_hostObject

Returns the value of attribute proxy_host.



25
26
27
# File 'lib/sahi.rb', line 25

def proxy_host
  @proxy_host
end

#proxy_portObject

Returns the value of attribute proxy_port.



25
26
27
# File 'lib/sahi.rb', line 25

def proxy_port
  @proxy_port
end

#sahisidObject

Returns the value of attribute sahisid.



25
26
27
# File 'lib/sahi.rb', line 25

def sahisid
  @sahisid
end

Instance Method Details

#add_url_mock(url_pattern, clazz = nil) ⇒ Object

make specific url patterns return dummy responses. Look at _addMock documentation.



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

def add_url_mock(url_pattern, clazz=nil) 
  clazz = "MockResponder_simple" if !clazz
  execute_step("_sahi._addMock(#{Utils.quoted(url_pattern)}, #{Utils.quoted(clazz)})")
end

#browser_js=(js) ⇒ Object



237
238
239
# File 'lib/sahi.rb', line 237

def browser_js=(js)
  exec_command("setBrowserJS", {"browserJS"=>js})
end

#check_nil(s) ⇒ Object



241
242
243
# File 'lib/sahi.rb', line 241

def check_nil(s)
  return (s == "null")  ? nil : s
end

#check_proxyObject



81
82
83
84
85
86
87
# File 'lib/sahi.rb', line 81

def check_proxy()
  begin
    response("http://#{@proxy_host}:#{@proxy_port}/_s_/spr/blank.htm")
  rescue
    raise "Sahi proxy is not available. Please start the Sahi proxy."
  end
end

#chrome?Boolean

returns true if browser is Google Chrome

Returns:

  • (Boolean)


435
436
437
# File 'lib/sahi.rb', line 435

def chrome?()
  return fetch_boolean("_sahi._isChrome()")
end

#clear_last_alertObject

resets the last alerted message



314
315
316
# File 'lib/sahi.rb', line 314

def clear_last_alert()
  execute_step("_sahi._clearLastAlert()")
end

#clear_last_confirmObject

resets the last confirm message



324
325
326
# File 'lib/sahi.rb', line 324

def clear_last_confirm()
  execute_step("_sahi._clearLastConfirm()")
end

#clear_last_downloaded_filenameObject

clear last downloaded file’s name



389
390
391
# File 'lib/sahi.rb', line 389

def clear_last_downloaded_filename()
  execute_step("_sahi._clearLastDownloadedFileName()")
end

#clear_last_promptObject

clears the last prompted message



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

def clear_last_prompt()
  execute_step("_sahi._clearLastPrompt()")
end

#closeObject

closes the browser



246
247
248
249
250
251
252
253
# File 'lib/sahi.rb', line 246

def close()
  if popup?()
    execute_step("_sahi._closeWindow()");
  else
    exec_command("kill");
    #Process.kill(9, @pid) if @pid
  end
end

#collect(els, attr = nil) ⇒ Object

returns element attributes of all elements of type attr matching the identifier within relations



228
229
230
231
232
233
234
# File 'lib/sahi.rb', line 228

def collect(els, attr=nil)
	  if(attr == nil)
	return els.collect_similar()
  else
		return fetch("_sahi.collectAttributes(#{Utils.quoted(attr)}, #{Utils.quoted(els.to_type())}, #{els.to_identifiers()})").split(",___sahi___")
  end
end

#domain(name) ⇒ Object

represents a domain section of window.



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/sahi.rb', line 284

def domain(name)
  if (@browser_type != null)
    win = Browser.new(@browser_type)
  else
    win = Browser.new(@browser_path, @browser_options, @browser_executable)
  end

  win.proxy_host = @proxy_host
  win.proxy_port = @proxy_port
  win.sahisid = @sahisid
  win.print_steps = @print_steps
  win.popup_name = @popup_name
  win.domain_name = name
  return win
end

#domain?Boolean

Returns:

  • (Boolean)


304
305
306
# File 'lib/sahi.rb', line 304

def domain?()
  return @domain_name != nil
end

#exec_command(cmd, qs = {}) ⇒ Object



112
113
114
115
# File 'lib/sahi.rb', line 112

def exec_command(cmd, qs={})
  res = response("http://#{@proxy_host}:#{@proxy_port}/_s_/dyn/Driver_" + cmd, {"sahisid"=>@sahisid}.update(qs))
  return res.force_encoding("UTF-8")
end

#execute_sahi(step) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/sahi.rb', line 187

def execute_sahi(step)
  if popup?() 
    step = "_sahi._popup(#{Utils.quoted(@popup_name)})." + step
  end
  if domain?() 
    step = "_sahi._domain(#{Utils.quoted(@domain_name)})." + step
  end
  #puts step
  exec_command("setStep", {"step" => step, 'addSahi' => true})
  i = 0
  while (i < 500)
    sleep(0.1)
    i+=1
    check_done = exec_command("doneStep")
    done = "true".eql?(check_done)
    
    error = check_done.index("error:") == 0
    return if done
		if (error)
      raise check_done
		end        
  end      
end

#execute_step(step) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/sahi.rb', line 126

def execute_step(step)
  if popup?() 
    step = "_sahi._popup(#{Utils.quoted(@popup_name)})." + step
  end
  if domain?() 
    step = "_sahi._domain(#{Utils.quoted(@domain_name)})." + step
  end
  #puts step
  exec_command("setStep", {"step" => step})
  i = 0
  while (i < 500)
    sleep(0.1)
    i+=1
    check_done = exec_command("doneStep")
    done = "true".eql?(check_done)
    
    error = check_done.index("error:") == 0
    return if done
		if (error)
      raise check_done
		end        
  end      
end

#expect_confirm(message, input) ⇒ Object

set an expectation to press OK (true) or Cancel (false) for specific confirm message



329
330
331
# File 'lib/sahi.rb', line 329

def expect_confirm(message, input)
  execute_step("_sahi._expectConfirm(#{Utils.quoted(message) }, #{input})")
end

#expect_prompt(message, input) ⇒ Object

set an expectation to set given value for specific prompt message



379
380
381
# File 'lib/sahi.rb', line 379

def expect_prompt(message, input)
  execute_step("_sahi._expectPrompt(#{Utils.quoted(message)}, #{Utils.quoted(input) })")
end

#fetch(expression) ⇒ Object

evaluates a javascript expression on the browser and fetches its value



216
217
218
219
220
# File 'lib/sahi.rb', line 216

def fetch(expression) 
     key = "___lastValue___" + Time.now.getutc.to_s;
     execute_step("_sahi.setServerVarPlain('"+key+"', " + expression + ")")
     return check_nil(exec_command("getVariable", {"key" => key}))
end

#fetch_boolean(expression) ⇒ Object

evaluates a javascript expression on the browser and returns true if value is true or “true”



223
224
225
# File 'lib/sahi.rb', line 223

def fetch_boolean(expression)
  return fetch(expression) == "true"
end

#firefox?Boolean

returns true if browser is Firefox

Returns:

  • (Boolean)


430
431
432
# File 'lib/sahi.rb', line 430

def firefox?()
  return fetch_boolean("_sahi._isFF()")
end

#get_windows(activePeriod = nil) ⇒ Object



173
174
175
176
177
178
179
180
181
# File 'lib/sahi.rb', line 173

def get_windows(activePeriod=nil)
	if(activePeriod == nil)
   		str = exec_command("getWindowsAsJSON", {"activePeriod" => -1});
    	else
    		activePeriod = activePeriod * 1000
		str = exec_command("getWindowsAsJSON", {"activePeriod" => activePeriod});
    	end
	return JSON.parse(str)
end

#ie?Boolean

returns true if browser is Internet Explorer

Returns:

  • (Boolean)


425
426
427
# File 'lib/sahi.rb', line 425

def ie?()
  return fetch_boolean("_sahi._isIE()")
end

#is_ready?Boolean

Returns:

  • (Boolean)


108
109
110
# File 'lib/sahi.rb', line 108

def is_ready?
  return  "true".eql?(exec_command("isReady"))
end

#last_alertObject

returns the message last alerted on the browser



309
310
311
# File 'lib/sahi.rb', line 309

def last_alert()
  return fetch("_sahi._lastAlert()")
end

#last_confirmObject

returns the last confirm message



319
320
321
# File 'lib/sahi.rb', line 319

def last_confirm()
  return fetch("_sahi._lastConfirm()")
end

#last_downloaded_filenameObject

get last downloaded file’s name



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

def last_downloaded_filename()
  return fetch("_sahi._lastDownloadedFileName()")
end

#last_promptObject

returns the last prompted message



334
335
336
# File 'lib/sahi.rb', line 334

def last_prompt()
  return fetch("_sahi._lastPrompt()")
end

navigates to the given url



122
123
124
# File 'lib/sahi.rb', line 122

def navigate_to(url, force_reload=false)
  execute_step("_sahi._navigateTo(\"" + url + "\", "+ (force_reload.to_s()) +")");
end

#openObject

opens the browser



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/sahi.rb', line 90

def open()
  check_proxy()
  @sahisid = Time.now.to_f
  start_url = "http://sahi.example.com/_s_/dyn/Driver_initialized"
  if (@browser_type != null)
    exec_command("launchPreconfiguredBrowser", {"browserType" => @browser_type, "startUrl" => start_url})
  else
    exec_command("launchAndPlayback", {"browser" => @browser, "browserOptions" => @browser_options, "browserExecutable" => @browser_executable, "startUrl" => start_url})
  end
  
  i = 0
  while (i < 500)
    i+=1
    break if is_ready?
    sleep(0.1)
  end
end

#opera?Boolean

returns true if browser is Opera

Returns:

  • (Boolean)


445
446
447
# File 'lib/sahi.rb', line 445

def opera?()
  return fetch_boolean("_sahi._isOpera()")
end

represents a popup window. The name is either the window name or its title.



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/sahi.rb', line 267

def popup(name)
  if (@browser_type != null)
    win = Browser.new(@browser_type)
  else
    win = Browser.new(@browser_path, @browser_options, @browser_executable)
  end

  win.proxy_host = @proxy_host
  win.proxy_port = @proxy_port
  win.sahisid = @sahisid
  win.print_steps = @print_steps
  win.popup_name = name
  win.domain_name = @domain_name
  return win
end

#popup?Boolean

Returns:

  • (Boolean)


300
301
302
# File 'lib/sahi.rb', line 300

def popup?()
  return @popup_name != nil
end

#prepare_window_action(oldTitle) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
# File 'lib/sahi.rb', line 150

def prepare_window_action(oldTitle)
		len = oldTitle.length
		if (len > 30) 
len = 30
		end
		titleToUse = fetch("_sahi.trim(#{Utils.quoted(oldTitle[0..30].strip)})")
		newTitle = titleToUse.gsub(/[^0-9a-zA-Z ]/, '') + ' _' + Time.now.getutc.to_s
		execute_step("window.document.title =" + Utils.quoted(newTitle))
		wait(2);
		return newTitle
end

#remove_url_mock(url_pattern) ⇒ Object

reverse effect of add_url_mock



405
406
407
# File 'lib/sahi.rb', line 405

def remove_url_mock(url_pattern) 
     execute_step("_sahi._removeMock(#{Utils.quoted(url_pattern)})")
end

#response(url, qs = {}) ⇒ Object



117
118
119
# File 'lib/sahi.rb', line 117

def response(url, qs={})
  return Net::HTTP.post_form(URI.parse(url), qs).body
end

#safari?Boolean

returns true if browser is Safari

Returns:

  • (Boolean)


440
441
442
# File 'lib/sahi.rb', line 440

def safari?()
  return fetch_boolean("_sahi._isSafari()")
end

#save_downloaded(file_path) ⇒ Object

Save the last downloaded file to specified path



394
395
396
# File 'lib/sahi.rb', line 394

def save_downloaded(file_path)
  execute_step("_sahi._saveDownloadedAs(#{Utils.quoted(file_path)})")
end

#selection_text(win = nil) ⇒ Object

return selection text



416
417
418
419
420
421
422
# File 'lib/sahi.rb', line 416

def selection_text(win = nil)
  if(win != nil)
    return fetch("_sahi._getSelectionText(#{win.to_s()})")
  else
    return fetch("_sahi._getSelectionText()")
  end	
end

#speed=(ms) ⇒ Object

sets the speed of execution. The speed is specified in milli seconds



256
257
258
# File 'lib/sahi.rb', line 256

def speed=(ms)
  exec_command("setSpeed", {"speed"=>ms})
end

#strict_visibility_check=(check) ⇒ Object

sets strict visibility check. If true, Sahi APIs ignores elements which are not visible



261
262
263
# File 'lib/sahi.rb', line 261

def strict_visibility_check=(check)
  execute_step("_sahi._setStrictVisibilityCheck(#{check})")
end

#swipe(moveX, moveY, isRelative = true) ⇒ Object

simulates the swipe event



374
375
376
# File 'lib/sahi.rb', line 374

def swipe(moveX, moveY, isRelative=true)
  execute_step("_sahi._touchMove(#{self.to_s()}, moveX, moveY, isRelative)")
end

#tapObject

simulates the tap event



349
350
351
# File 'lib/sahi.rb', line 349

def tap()
  execute_step("_sahi._tap(#{self.to_s()})")
end

#titleObject

return window title



410
411
412
# File 'lib/sahi.rb', line 410

def title()
  return fetch("_sahi._title()")
end

#touchObject

simulates the touch event



344
345
346
# File 'lib/sahi.rb', line 344

def touch()
  execute_step("_sahi._touch(#{self.to_s()})")
end

#touchCancelObject

simulates the touchCancel event



364
365
366
# File 'lib/sahi.rb', line 364

def touchCancel()
  execute_step("_sahi._touchCancel(#{self.to_s()})")
end

#touchEndObject

simulates the touchEnd event



359
360
361
# File 'lib/sahi.rb', line 359

def touchEnd()
  execute_step("_sahi._touchEnd(#{self.to_s()})")
end

#touchMove(moveX, moveY, isRelative = true) ⇒ Object

simulates the touchMove event



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

def touchMove(moveX, moveY, isRelative=true)
  execute_step("_sahi._touchMove(#{self.to_s()}, moveX, moveY, isRelative)")
end

#touchStartObject

simulates the touchStart event



354
355
356
# File 'lib/sahi.rb', line 354

def touchStart()
  execute_step("_sahi._touchStart(#{self.to_s()})")
end

#type_key_code_native(key) ⇒ Object



169
170
171
# File 'lib/sahi.rb', line 169

def type_key_code_native(key)
	exec_command("typeKeyCodeNative", {"key" => key})
end

#type_native(str) ⇒ Object



183
184
185
# File 'lib/sahi.rb', line 183

def type_native(str)
	exec_command("typeNative", {"str" => str})
end

#wait(timeout) ⇒ Object

waits for specified time (in seconds). if a block is passed, it will wait till the block evaluates to true or till the specified timeout, which ever is earlier.



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

def wait(timeout) 
  total = 0;
  interval = 0.2;
  
  if !block_given?
    sleep(timeout)
    return
  end
  
  while (total < timeout)
    sleep(interval);
    total += interval;
    begin 
      return if yield
    rescue Exception=>e 
      puts e
    end
  end          
end

#window_action(action) ⇒ Object



162
163
164
165
166
167
# File 'lib/sahi.rb', line 162

def window_action(action)
	title = fetch("window.top.document.title")
	title = prepare_window_action(title)
	puts ">" + title + "<"
	exec_command("windowAction", {"action" => action, "title" => title})
end