Script Execution Control APIs
abstract
These APIs control the way a script executes
Set Mode tells the script to start executing further steps on a different mode (application type).
Look at Sahi Pro multiple modes for available modes.
Parameters
$applicationType | string optional | Mode or Application Type to set. If not specified, application type BROWSER is assumed. |
Return Value
Modes Supported :
Raw Script
_setMode("BROWSER"); // Further steps in script will be sent to browser.
_setMode("WINDOWS"); // Further steps in script will be sent to Windows applications.
Sahi Pro Classic API :_setMode
Forces script to wait for given time or given condition to be true, which ever comes first
Parameters
$timeout | integer | time in milliseconds to wait for |
$condition | Sahi expression optional | condition to wait for. If specified, _wait will return if either the condition is met or if the time elapsed has exceeded timeout, whichever comes first. |
Return Value
Modes Supported :
Raw Script
_wait(1000); // Will stop execution for a second
// Wait till div by id "ajaxConfirm" is populated for max 5 seconds.
_wait(5000, _getText(_div("ajaxConfirm"))!="");
// Wait till button becomes visible
_wait(5000, _isVisible(_button("Confirm")));
// Wait till "Loading ..." message disappears
_wait(1000); // may take a second before that message appears.
_wait(5000, !_isVisible(_div("Loading ..."))); // wait max 5 seconds for it to disappear.
Sahi Pro Classic API :_wait
Sets what readyStates of an XMLHttpRequest (XHR) Sahi should wait for.
Sahi normally monitors all AJAX requests and proceeds only if the XHR readyState is 4.
In some applications which use long polling or comet requests, there may be XHRs in readyState 1.
Sahi would wait for a long time and then timeout in such cases.
Parameters
$readyStates | string | Comma separated ready states e.g "1,2,3" |
$forURL | string optional | URL for which given ready states should be set. URL pattern can also be specified here using regular expression. |
Return Value
Modes Supported :
Raw Script
//Setting _setXHRReadyStatesToWaitFor to "2,3" will allow Sahi to proceed if the readyStates are either 1 or 4.
_setXHRReadyStatesToWaitFor("2,3");
//Setting _setXHRReadyStatesToWaitFor to "1,2,3" for the window URL that matches regular expression /formTest/.
_setXHRReadyStatesToWaitFor("1,2,3","/formTest/");
Sahi Pro Classic API :_setXHRReadyStatesToWaitFor
When set to true, it will not use the Sahi wait mechanism.
To stop bypassing the wait mechanism, set it to false again.
Parameters
$b | boolean | true or false |
Return Value
Modes Supported :
Raw Script
//start bypassing wait mechanism
_byPassWaitMechanism(true);
_setValue(_textbox("user"), "test");
_setValue(_password("pass"), "secret");
_click(_button("Login"));
//stop bypassing wait mechanism
_byPassWaitMechanism(false);
Sahi Pro Classic API :_byPassWaitMechanism
Modify the Windows, AJAX and Flex wait times. Sahi will wait for the specified time after start of every step, following which it will move on to execute the next step,
even if the activity(page/ajax/flex) is under execution. Pass the value as null to keep the last defined wait time.
Parameters
$windowLoadTime | integer | time in milliseconds. Default is 60000ms. |
$ajaxLoadTime | integer | time in milliseconds. Default is 60000ms. |
$flexLoadTime | integer | time in milliseconds. Default is 0ms. |
Return Value
Modes Supported :
Raw Script
_setWaitTimes(5000, 0, 0);
_navigateTo("http://sahi.co.in/demo/training/");//Sahi will wait for 5000ms following this step to load the page.
//If the page is not loaded within 5000ms, the execution will go to next step.
_click(_submit("Login"));
_setWaitTimes(null, 7000, 0);//Sahi will not wait for flex loads if any. It will wait for 7000ms for any AJAX activity and 5000ms for page load
//following this step before moving to next step.
Sahi Pro Classic API :_setWaitTimes
Use
Set Strict Visibility Check
with parameter $doCheck
as true to strictly look for only visible elements and ignore elements which are not visible.
Parameters
$doCheck | boolean | set to true to enable strict visibility check. |
$checkZIndex | boolean optional | If true, checks whether the element is on top or not(Checks whether some other element with a higher Z index is not hiding it). If false, omits this check. Default is false. This argument is not available for Windows mode. |
$doScroll | boolean optional | If true, checks whether element is the top element by scrolling to the element. If false, checks only for the current viewport. Default is false. Used only when checkZIndex is true. This argument is not available for Windows mode. |
Return Value
Modes Supported :
Raw Script
// make Sahi ignore elements which are not visible.
// do operations on visible elements ...
_setStrictVisibilityCheck(true); //doesn't check z-index
_setStrictVisibilityCheck(true, true); //checks z-index
_assertExists(_textbox("textbox_id"));
_setStrictVisibilityCheck(true, true,true); //checks z-index after scrolling
_assertExists(_textbox("textbox_id"));
// make sahi revert to original behavior of considering all elements in the DOM.
_setStrictVisibilityCheck(false);
Sahi Pro Classic API :_setStrictVisibilityCheck
When an action(like click, type, etc.) is performed on a HTML element, the focus gets removed from the previously focused element. Similarly, when a action (like _click, _setValue, etc.) is performed on a HTML element, Sahi Pro by default triggers a blur event on the previously focused element to remove focus from it.
However, this behaviour may not be desired for some HTML elements. In such cases, disable this automatic blur using Set Automatic Blur API.
Parameters
$enable | boolean | set to true to enable calling blur event. |
Return Value
Modes Supported :
Raw Script
// make Sahi to stop automatic blur.
_setAutomaticBlur(false);
_setValue(_textbox("category"), "Automation"); // for this automatic blur is not desired.
// make Sahi revert to original behavior of automatic blur.
_setAutomaticBlur(true);
Sahi Pro Classic API :_setAutomaticBlur
Sets the speed of execution of steps.
Parameters
$speed | integer | speed in milliseconds |
Return Value
Modes Supported :
Raw Script
_setSpeed(2000);
//Each step will execute with a gap of 2000 milliseconds (2 seconds).
//Default execution speed is 100ms;
Sahi Pro Classic API :_setSpeed
Sahi Pro continuously pings the proxy server to await commands. In some very rare cases, it may be required to
silence all ping activity after execution of a step (For example, if you are monitoring CPU or browser usage statistics after a step).
In such case, calling Set Ping Delay After Step will disable pinging for the given delay time.
Parameters
$delay | integer | delay in milliseconds |
Return Value
Modes Supported :
Raw Script
_setPingDelayAfterStep(5000);
_click(_link("Link Test")); // pinging will stop for 5000 ms after this step
_click(_link("Back")); // pinging will stop for 5000 ms after this step
_setPingDelayAfterStep(0);
_click(_link("Abc")); // Normal pinging will resume.
Sahi Pro Classic API :_setPingDelayAfterStep
Forces script to fail and abort on any error. Further steps will not be executed.
This is the default behaviour of Sahi.
Parameters
None |
Return Value
Modes Supported :
Raw Script
_stopOnError();
Sahi Pro Classic API :_stopOnError
Forces script to continue inspite of error. Further steps will be executed.
Parameters
None |
Return Value
Modes Supported :
Raw Script
_continueOnError();
Sahi Pro Classic API :_continueOnError
Causes a script to stop as a failure and log the given message. Can be used in the middle of a script.
info
- When called from inside a testcase, only that testcase will fail and other testcases will not be impacted.
- When called from inside try block, execution will proceed to catch block.
- onScriptFailure and onScriptError callback functions will NOT be called.
Parameters
$message | string optional | Message to be logged in playback logs |
Return Value
Modes Supported :
Raw Script
Sahi Pro Classic API :_fail
Causes a script to stop execution.
info
- When called from inside a _testcase, the whole script execution will be stopped. Execution will not proceed to next testcase
- When called from inside try block, execution will terminate without entering the catch block.
- onScriptFailure and onScriptError callback functions will NOT be called.
Parameters
None |
Return Value
Modes Supported :
Raw Script
Sahi Pro Classic API :_stop
Script Synchronization
Scripts can be forced to synchronize with each other by acquiring locks.
Acquires a lock with given name. If another script calls Lock with the same name, that script will wait till
this lock is unlocked or till timeout happens.
If timeout is not specified, the default timeout defined by
If you wish to lock a portion of code that deals with browser windows, example: focusing a window and taking a screenshot or focusing a window and doing file uploads, use LockWindow instead of Lock. For example usage, refer to the LockWindow example below. Use Lock and _unlock for functionality other than dealing with windows.
sahi.lock.timeout
property in sahi.properties
is used.
(Default is 60 seconds. Can be overridden in userdata.properties)
If you wish to lock a portion of code that deals with browser windows, example: focusing a window and taking a screenshot or focusing a window and doing file uploads, use LockWindow instead of Lock. For example usage, refer to the LockWindow example below. Use Lock and _unlock for functionality other than dealing with windows.
Parameters
$name | string | Lock name |
$timeout | integer optional | timeout |
Return Value
string | Key that can be used in the _unlock API |
Modes Supported :
Raw Script
Sahi Pro Classic API :_lock
Unlocks or releases the lock (acquired through the _lock API) that matches the given key.
danger
key is NOT the name of the lock but the value returned from the _lock method.
Parameters
$key | string | Lock key returned from _lock |
Return Value
Modes Supported :
Raw Script
Sahi Pro Classic API :_unlock
This is a more specific version of the _lock API.
Acquires a lock with a name internal to Sahi. The same lock is used by Sahi when launching new browser windows.
If another script calls Lock Window, that script will wait till this Lock Window is unlocked or till timeout happens. If timeout is not specified, the default timeout defined by
Acquires a lock with a name internal to Sahi. The same lock is used by Sahi when launching new browser windows.
If another script calls Lock Window, that script will wait till this Lock Window is unlocked or till timeout happens. If timeout is not specified, the default timeout defined by
sahi.lock.timeout
property in sahi.properties
is used.
(Default is 60 seconds. Can be overridden in userdata.properties)
info
In 5.1.0, _lock API was introduced.
As part of taking screenshots, one would first need to call _focusWindow. The user could use _lock to lock a portion of code that called _focusWindow and then a Screenshot API. This is to ensure that while one script takes the screenshot of its browser, other scripts will wait before taking screenshots.
However, Sahi itself launches browser windows to run scripts of a suite. Since this is not controlled through _lock, a Sahi browser window may get opened while a script is attempting to take a screenshot. This would end up affecting the screenshot.
To avoid this problem, we have introduced the Lock Window API. Whenever Sahi internally opens/manages browser windows, it calls Lock Window to lock the window related code.
Users should always use Lock Window when managing any code related to windows, example: focusing the window and taking screenshots, focusing the window and do a native file upload, etc.
As part of taking screenshots, one would first need to call _focusWindow. The user could use _lock to lock a portion of code that called _focusWindow and then a Screenshot API. This is to ensure that while one script takes the screenshot of its browser, other scripts will wait before taking screenshots.
However, Sahi itself launches browser windows to run scripts of a suite. Since this is not controlled through _lock, a Sahi browser window may get opened while a script is attempting to take a screenshot. This would end up affecting the screenshot.
To avoid this problem, we have introduced the Lock Window API. Whenever Sahi internally opens/manages browser windows, it calls Lock Window to lock the window related code.
Users should always use Lock Window when managing any code related to windows, example: focusing the window and taking screenshots, focusing the window and do a native file upload, etc.
Parameters
$timeout | long optional | timeout |
Return Value
Modes Supported :
Raw Script
Sahi Pro Classic API :_lockWindow
Unlocks or releases the lock acquired by calling _lockWindow.
Used in conjunction with _lockWindow.
Used in conjunction with _lockWindow.
Parameters
None |
Return Value
Modes Supported :
Raw Script
Sahi Pro Classic API :_unlockWindow
Suppose we have 2 scripts: one for taking a screenshot and another for fileupload via native events.
// Script 1
_focusWindow();
_takeScreenShot();
// Script 2
_focusWindow();
// file upload via native events
Both these scripts need their browsers to be in focus. How ever when run in a suite, the sequence may become like this:
_focusWindow(); // script 1
_focusWindow(); // script 2: brings second window in focus
_takeScreenShot(); // script 1: will take screenshot of window 2 which is WRONG
To synchronize these, whenever focus is being sought, we may acquire a lock and then release the lock only when our operation is complete.
Since we are dealing with windows, call _lockWindow instead of _lock so that windows opened by Sahi internally are also managed correctly.
//Script 1
_lockWindow();
_focusWindow();
_takeScreenShot();
_unlockWindow();
//Script 2
_lockWindow();
_focusWindow();
// do file upload stuff
_unlockWindow();
Now the sequence would be:
_lockWindow(); // script 1
_focusWindow(); // script 1
_lockWindow(); // script 2: will block here.
_takeScreenShot(); // script 1
_unlockWindow(); // script 1
_focusWindow(); // script 2
// do file upload stuff // script 2
_unlockWindow(); // script 2
Callback functions
Sahi provides a few hooks or callback functions which are automatically executed at various points of the script life cycle. These functions need to be defined at the start of the script.The various functions are: Example:
onScriptFailure = function($e){
// Handle whatever you want to do, first.
// Use either of the following. Prefer the former.
_logExceptionAsFailure($e); // Explicitly log the exception as failure.
_log("In onScriptError", "FAILURE"); // Log with a Failure tag.
}
warning
If you have handled onScriptError in the script, Sahi will not treat it as a failure unless you specifically indicate it.
To indicate that the script has failed, you can use one of the following approaches.
Example:
To indicate that the script has failed, you can use one of the following approaches.
onScriptError = function($e){
// Handle whatever you want to do, first.
// Use either of the following. Prefer the former.
_logExceptionAsFailure($e); // Explicitly log the exception as failure.
_log("In onScriptError", "FAILURE"); // Log with a Failure tag.
return false;
}
onScriptEnd = function(){
// Step performed after end of script.
_log("After End");
}
Callback example
onBeforeStep = function($step, $debugInfo){
_log("onBeforeStep executed for step : " +$step);
}
onAfterStep = function($step, $debugInfo, $status){
_log("step executed successfully with status : "+$status);
}
onScriptEnd = function(){
_click(_button("Logout"));
}
onScriptError = function($e){
_alert(">> In onScriptError");
}
onScriptFailure = function($e){
_alert(">> In onScriptFailure");
}
_navigateTo("http://sahi.co.in/demo/training/");
_setValue(_textbox("user"), "test");
_setValue(_password("password"), "secret");
_click(_submit("Login"));
_assertExists(_submit("Login")); // cause SCRIPT ASSERTION FAILURE - triggers onScriptFailure
_setValue(_textbox("q11"), "2"); // causes SCRIPT ERROR - triggers onScriptError
// Script aborts here, but executes onScriptEnd() to logout
_setValue(_textbox("q[1]"), "1");
_setValue(_textbox("q[2]"), "1");
_click(_button("Add"));
_assertEqual("1150", _textbox("total").value); // cause SCRIPT FAILURE
// If not aborted earlier, automatically calls onScriptEnd() to logout.
infoNote: Sahi already has implemented some Callback functions in
Thus when implementing your Callback function, you must override the default implementation of that Callback function as shown in the examples above.
userdata/scripts/global_include.sah
which will be called by default.
Thus when implementing your Callback function, you must override the default implementation of that Callback function as shown in the examples above.
Taking screenshots on error/failure
onScriptError = function($e){
_focusWindow();
_takeScreenShot();
}
onScriptFailure = onScriptError;
_navigateTo("http://sahi.co.in/demo/training/");
_setValue(_textbox("user"), "test");
_setValue(_password("password"), "secret");
_click(_submit("Login"));
Force Sahi to continue on error after screenshots and logging.
onScriptError = function($e){
_logExceptionAsFailure($e);
_focusWindow();
_takeScreenShot();
return true; // Forces Sahi to continue execution and not stop at error. Since Sahi Pro V4.3
}
_navigateTo("http://sahi.co.in/demo/training/");
_setValue(_textbox("user"), "test");
_setValue(_password("password"), "secret");
_click(_submit("Login"));
Example:
onBeforeStep = function($step, $debugInfo){
// Step performes before every steps.
_log("onBeforeStep executed for step : " +$step);
}
Example:
onAfterStep = function($step, $debugInfo, $status){
// Step performes after every steps.
_log("step executed successfully with status : "+$status);
}