Sahi Pro - Action APIs
Sahi's Action APIs simulate user actions on the browser.
Normally Sahi tries to perform actions via Javascript events. This allows play back without the browser being in focus.In rare cases where Javascript events do not work properly, we switch to native events.
Mouse Events
Mouse events simulate the user's mouse based actions.Mouse events are normally triggered at 0,0 coordinates of that element (top left)
Events can be forced to perform at other coordinates by using the _xy API.
_xy
_xy($element, $x, $y)
Arguments
$element | HTML DOM element | Element within which we want to perform the mouse action |
$x | integer | x co-ordinate in pixels |
$y | integer | y co-ordinate in pixels |
Details
Specifies the coordinates on element where the event should be fired.
Eg.
Negative values can be given to specify offset from right and bottom.
Eg.
Specifies the coordinates on element where the event should be fired.
Eg.
_click(_xy(_button("id"), 10, 20))
clicks inside the button, 10px from the left and 20 pixels from the top.Negative values can be given to specify offset from right and bottom.
Eg.
_click(_xy(_button("id"), -5, -10))
clicks inside the button, 5px from the right and 10px from the bottom.Combo keys are available with some mouse events to simulate SHIFT click, CTRL click etc.
These are used for multi-selecting on some UIs.
_click
_click($element[, $combo])
Arguments
$element | HTML DOM element | element to click on |
$combo | string optional | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" |
Details
_click simulates a user's click on the given element.
_click simulates a user's click on the given element.
_click(_button("Click Me"));
_click(_button("Click Me"), "CTRL"); // clicks with CTRL key pressed
_click(_button("Click Me"), "CTRL|SHIFT"); // clicks with CTRL and SHIFT keys pressed
// With _xy
_click(_xy(_button("Click Me"),4,5)); // Click at coordinates 4,5 pixels inside the button
_doubleClick
_doubleClick($element[, $combo])
Arguments
$element | HTML DOM element | element to double click on |
$combo | string optional | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" |
Details
_doubleClick simulates a user's click on the given element.
_doubleClick simulates a user's click on the given element.
_doubleClick(_button("DblClick Me"));
_doubleClick(_button("DblClick Me"), "CTRL"); // double clicks with CTRL key pressed
_doubleClick(_button("DblClick Me"), "CTRL|SHIFT"); // double clicks with CTRL and SHIFT keys pressed
// With _xy
_doubleClick(_xy(_button("DblClick Me"),4,5)); // double click at coordinates 4,5 pixels inside the button
_rightClick
_rightClick($element[, $combo])
Arguments
$element | HTML DOM element | element to right click on |
$combo | string optional | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" |
Details
_rightClick simulates a user's click on the given element.
_rightClick simulates a user's click on the given element.
_rightClick(_button("Right Click Me"));
_rightClick(_button("Right Click Me"), "CTRL"); // right clicks with CTRL key pressed
_rightClick(_button("Right Click Me"), "CTRL|SHIFT"); // right clicks with CTRL and SHIFT keys pressed
// With _xy
_rightClick(_xy(_button("Right Click Me"),4,5)); // right click at coordinates 4,5 pixels inside the button
warning
_rightClick will not bring up the browser's context menu.
_mouseDown
_mouseDown($element[, $isRight[, $combo]])
Arguments
$element | HTML DOM element | element to perform mouse down on |
$isRight | boolean optional | Set to true for a left-hand mouse, default false |
$combo | string optional | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" |
Details
_mouseDown simulates a mousedown on the given element.
_mouseDown simulates a mousedown on the given element.
_mouseDown(_button("Mouse Down"));
_mouseDown(_button("Mouse Down"), true); //mouseDown for a left-hand mouse
_mouseDown(_button("Mouse Down"), false, "CTRL"); //mouseDown with CTRL key pressed
_mouseDown(_button("Mouse Down"), false, "CTRL|SHIFT"); //mouseDown with CTRL and SHIFT keys pressed
_mouseUp
_mouseUp($element[, $isRight[, $combo]])
Arguments
$element | HTML DOM element | element to perform mouse up on |
$isRight | boolean optional | Set to true for a left-hand mouse, default false |
$combo | string optional | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" |
Details
simulates a mouseup on the given element.
simulates a mouseup on the given element.
_mouseup(_button("Mouse up"));
_mouseup(_button("Mouse up"), true); // mouseup for a left-hand mouse
_mouseup(_button("Mouse up"), false, "CTRL"); // mouseup with CTRL key pressed
_mouseup(_button("Mouse up"), false, "CTRL|SHIFT"); // mouseup with CTRL and SHIFT keys pressed
_mouseOver
_mouseOver($element[, $combo])
Arguments
$element | HTML DOM element | element to perform hover over or move the mouse over. |
$combo | string optional | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" |
Details
_mouseOver simulates mouse hovering on the given element.
_mouseOver simulates mouse hovering on the given element.
_mouseOver(_button("Click Me"));
_mouseOver(_button("Click Me"), "CTRL"); // mouseOver with CTRL key pressed
_mouseOver(_button("Click Me"), "CTRL|SHIFT"); // mouseOver with CTRL and SHIFT keys pressed
_check
_check($checkBoxOrRadioElement)
Arguments
$checkBoxOrRadioElement | HTML DOM element | The check box or Radio element to check |
Details
Checks the given checkbox or radio element. If already checked, this API does not do anything.
Checks the given checkbox or radio element. If already checked, this API does not do anything.
_uncheck
_uncheck($checkBoxElement)
Arguments
$checkBoxElement | HTML DOM element | The check box to uncheck |
Details
Unchecks the given checkbox. If already unchecked, this API does not do anything.
Unchecks the given checkbox. If already unchecked, this API does not do anything.
_setSelected
_setSelected($element, $optionToSelect[, $isMultiple])
Arguments
$element | HTML DOM element | Select dropdown |
$optionToSelect | string|integer|array of string and/or int | Option's text, id or index; can also pass an array of options for multi-select |
$isMultiple | boolean optional | set isMultiple true for multiselect |
Details
Selects one or more elements in a select dropdown.
Selects one or more elements in a select dropdown.
_setSelected(_select("Age"), "28"); // Selects the option visible as "28" in a select box
_setSelected(_select("color"), 1); // Selects the second option in a select box
_setSelected(_select("color"), "red"); // Selects red in a multiselect box
_setSelected(_select("color"), "blue", true); // Selects blue also in the multiselect box
_setSelected(_select("color"), ["red", "blue"]); // Unselects previous and selects red and blue in a multiselect box
_setSelected(_select("color"), [1,2,3]); // Unselects previous and selects the second, third and fourth options in a multiselect box
_setSelected(_select("color"), ["green", "yellow"], true); // Keeps previous options selected and selects "green" and "yellow" also
_dragDrop
_dragDrop($dragElement, $dropElement)
Arguments
$dragElement | HTML DOM element | HTML element to be dragged |
$dropElement | HTML DOM element | HTML Element where the dragged element will be dropped |
Details
Simulates a drag and drop action
Simulates a drag and drop action
// Drag the item and drop it in the shopping cart
_dragDrop(_image("item"), _byId("ShoppingCart"));
// Drag the item and drop it at coordinates 20,40 pixels inside shopping cart
_dragDrop(_image("item"), _xy(_byId("ShoppingCart"), 20, 40));
_dragDropXY
_dragDropXY($dragElement, $x, $y[, $isRelative])
Arguments
$dragElement | HTML DOM element | HTML Element to be dragged |
$x | integer | x coordinate of drop point on the page |
$y | integer | y coordinate of drop point on the page |
$isRelative | boolean optional | Specifies whether the coordinates are relative to current position of draggable element. |
Details
_dragDropXY simulates a drag and drop action. It drags the element and drops it at the given x, y coordinate.
_dragDropXY simulates a drag and drop action. It drags the element and drops it at the given x, y coordinate.
// If _image("item") is located at coordinates (50, 150)
// Drag the item and drop it at the coordinate (100, 300)
// The end result is that the element's coordinates will be at (100, 300)
_dragDropXY(_image("item"), 100, 300);
// Drag the item and drop it at the coordinate (50+100, 150+300)
// The end result is that the element's coordinates will be at (150, 450)
_dragDropXY(_image("item"), 100, 300, true);
Touch Events
_tap
_tap($element[, $count])
Arguments
$element | HTML DOM element | HTML form element that needs to be tapped |
$count | integer optional | number of times the element needs to be tapped. Default value is 1. |
Details
Simulates a tap event(touch event) on the HTML element
Simulates a tap event(touch event) on the HTML element
_touch
_touch($element[, $count])
Arguments
$element | HTML DOM element | HTML form element on which we need to fire a touch event |
$count | integer optional | number of times the element needs to be touched. Default value is 1. |
Details
Simulates a touch event on the HTML element
Simulates a touch event on the HTML element
_touchStart
_touchStart($element)
Arguments
$element | HTML DOM element | HTML form element on which we need to fire a touch start event |
Details
Simulates a touch start event on the HTML element
Simulates a touch start event on the HTML element
_touchEnd
_touchEnd($element)
Arguments
$element | HTML DOM element | HTML form element on which we need to fire a touch end event |
Details
Simulates a touch end event on the HTML element
Simulates a touch end event on the HTML element
_touchCancel
_touchCancel($element)
Arguments
$element | HTML DOM element | HTML form element on which we need to cancel the ongoing touch event |
Details
Simulates a touch cancel event on the HTML element
Simulates a touch cancel event on the HTML element
_touchMove
_touchMove($element, $moveX, $moveY[, $isRelative])
Arguments
$element | HTML DOM element | HTML form element which we need to move/drag. |
$moveX | integer | number of pixels the element needs to move in x-direction |
$moveY | integer | number of pixels the element needs to move in y-direction |
$isRelative | boolean optional | if true, the element will move relative to the current location of the element.if false, element will move to the position where the horizontal coordinate and vertical coordinate are 'moveX' and 'moveY'. Default value is true. |
Details
Simulates a touch move event on the HTML element
Simulates a touch move event on the HTML element
_swipe
_swipe($element, $moveX, $moveY, $isRelative)
Arguments
$element | HTML DOM element | HTML form element on which we need to simulate swipe event. |
$moveX | integer | number of pixels the element needs to move in x-direction |
$moveY | integer | number of pixels the element needs to move in y-direction |
$isRelative | boolean | if true, the element will move relative to the current location of the element. If false, element will move to the position where clientX and clientY are moveX and moveY. |
Details
Simulates a touch move event on the HTML element
Simulates a touch move event on the HTML element
Keyboard Events
_setValue
_setValue($element, $value)
Arguments
$element | HTML DOM element | HTML form element whose value is to be set |
$value | string | Value to be set |
Details
Simulates text entry into html form elements (textbox like elements and textareas)
The sequence of events performed are
Focus
Enter Text
Remove focus
Simulates text entry into html form elements (textbox like elements and textareas)
The sequence of events performed are
Focus
Enter Text
Remove focus
// populates textbox identified as _textbox("user") with Ram
_setValue(_textbox("user"), "Ram");
_keyDown
_keyDown($element, $charInfo[, $combo])
Arguments
$element | HTML DOM element | Any HTML element |
$charInfo | charInfo | charInfo can be:
|
$combo | string optional | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" |
Details
Simulates pressing down a key on the given element.
Simulates pressing down a key on the given element.
_keyDown(document.body, 'a');
_keyDown(document.body, 98);
_keyDown(document.body, [13,13]);
_keyDown(document.body, 'a', "CTRL");
_keyUp
_keyUp($element, $charInfo[, $combo])
Arguments
$element | HTML DOM element | Any HTML element |
$charInfo | charInfo | charInfo can be:
|
$combo | string optional | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" |
Details
Simulates releasing a key press on the given element.
Simulates releasing a key press on the given element.
_keyUp(document.body, 'a');
_keyUp(document.body, 98);
_keyUp(document.body, [13,13]);
_keyUp(document.body, 'a', "CTRL");
_keyPress
_keyPress($element, $charInfo[, $combo])
Arguments
$element | HTML DOM element | Any HTML element |
$charInfo | charInfo | charInfo can be:
|
$combo | string optional | Any combo key: can be "CTRL", "SHIFT", "ALT" or "META"; Can also be two or more keys together like "CTRL|SHIFT" |
Details
Simulates pressing a key on the given element. Does keyDown and keyUp together.
Simulates pressing a key on the given element. Does keyDown and keyUp together.
_keyPress(document.body, 'a');
_keyPress(document.body, 98);
_keyPress(document.body, [13,13]);
_keyPress(document.body, 'a', "CTRL");
_type
_type($element, $text)
Arguments
$element | HTML DOM element | element in which the text is to be typed |
$text | string | text to be typed |
Details
Types the text into the element. Different from _setValue. _type does not bring or remove focus from element.
Types the text into the element. Different from _setValue. _type does not bring or remove focus from element.
_type(_textbox("user"), "am");
Focus Events
_focus
_focus($element)
Arguments
$element | HTML DOM element | Any HTML element to focus on |
Details
Brings focus to given element.
Brings focus to given element.
_focus(_textbox("username"));
_removeFocus
_removeFocus($element)
Arguments
$element | HTML DOM element | Any HTML element to remove focus from |
Details
Similar to clicking somewhere else on the window to remove focus from given element.
Forces onblur events to be called.
Blur happens automatically during Sahi's script execution.
This API is rarely used explicitly. Same as _blur.
Similar to clicking somewhere else on the window to remove focus from given element.
Forces onblur events to be called.
Blur happens automatically during Sahi's script execution.
This API is rarely used explicitly. Same as _blur.
_removeFocus(_textbox("username"));
_blur
_blur($element)
Arguments
$element | HTML DOM element | Any HTML element to remove focus from |
Details
Similar to clicking somewhere else on the window to remove focus from given element.
Forces onblur events to be called.
Blur happens automatically during Sahi's script execution.
This API is rarely used explicitly. Same as _removeFocus.
Similar to clicking somewhere else on the window to remove focus from given element.
Forces onblur events to be called.
Blur happens automatically during Sahi's script execution.
This API is rarely used explicitly. Same as _removeFocus.
_blur(_textbox("username"));
Text Selection
Selecting text for manipulation (like selecting text in a Rich Text Editor to change font to bold)_selectRange
_selectRange($element, $rangeStart, $rangeEnd)
Arguments
$element | HTML DOM element | element to select on |
$rangeStart | integer | start position of selection |
$rangeEnd | integer | end position of selection |
Details
Example:
Example:
// If the text was "abcdefghij"
_selectRange(_rte(1), 2, 4); // selects text cd
var $text = _getSelectionText(); // $text = "cd"
_selectRange(_rte(1), 2, 2); // places the cursor at 3rd position without any selection
_selectTextRange
_selectTextRange($element, $searchText[, $position])
Arguments
$element | HTML DOM element | element to select on |
$searchText | string | text to search for and select. The text can be a pure string or a regular expression with an index |
$position | string optional | can be "before" or "after". if specified, the selection moves to the start or end of searchText. |
Details
Example:
Example:
//Given a sample string
//This bright red apple is sweeter than that dull red apple
_selectTextRange(_rte(1), "red apple"); // selects the first red apple
_selectTextRange(_rte(1), "red apple[1]"); // selects the second red apple
_selectTextRange(_rte(1), "/ap.le/[1]"); // selects the second apple
var $text = _getSelectionText(); // $text = "apple"
_selectTextRange(_rte(1), "/ap.le/[1]", "before"); // moves the cursor before the second apple, with no selection
_selectTextRange(_rte(1), "/ap.le/[1]", "after"); // moves the cursor after the second apple, with no selection
Page Navigation
_navigateTo
_navigateTo($url[, $forceReload])
Arguments
$url | string | URL to navigate to. Can be relative to current page. |
$forceReload | boolean optional | If the current page URL is same as url, Sahi will not reload the page by default. Set to true to force reload when urls are same. |
Details
_navigateTo loads the given url in the top frame of the window.
To load in a popupWindow, use _selectWindow to select that window first.
_navigateTo loads the given url in the top frame of the window.
To load in a popupWindow, use _selectWindow to select that window first.
// If current page is not http://sahi.co.in/demo/
_navigateTo("http://sahi.co.in/demo/"); // Will navigate to this page.
// If current page is itself "http://sahi.co.in/demo/"
_navigateTo("http://sahi.co.in/demo/"); // will do nothing
_navigateTo("http://sahi.co.in/demo/", true); // Will force navigation to this page.
_selectWindow("popWin");
_navigateTo("http://sahi.co.in/demo/"); // loads in the popup window.
info
To force reload of the current page without knowing the URL, you may use
_call(top.location.reload()); // reload via Javascript
// or
_windowAction("refresh"); // native event
Waits
_wait
_wait($timeout[, $condition])
Arguments
$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. |
Details
Forces script to wait for given time or given condition to be true, which ever comes first
Forces script to wait for given time or given condition to be true, which ever comes first
_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.
Native Events
In rare cases where Javascript events do not work properly, we switch to native events. These events are created bythe underlying Operating System. The browser needs to be in focus for this to work properly.
These APIs only work if the browser and Sahi's proxy are on the same system. So these APIs are not available on mobile devices.
Some native events may not work on all platforms.
For native events, the window and element SHOULD be in focus.
Use
When using suites, do one of these
Use
_focusWindow()
before using native events in a script.When using suites, do one of these
-
isolate all scripts with native events into its own suite, and run that suite using 1 thread only.
-
OR
Use _lock and _unlock in scripts where contention for window focus is possible.
_typeNative
_typeNative($text)
Arguments
$text | string | Text to type |
Details
Types the text using native events
Types the text using native events
_focus(_textbox("user"));
_focusWindow();
_typeNative("Ram");
_typeKeyCodeNative
_typeKeyCodeNative($keyCode)
Arguments
$keyCode | integer | Key Code of keyboard key to be pressed. |
Details
Presses the keyboard key for given keyCode
java.awt.event.KeyEvent defines keyCodes as constants which can be passed to this function.
Presses the keyboard key for given keyCode
java.awt.event.KeyEvent defines keyCodes as constants which can be passed to this function.
_focusWindow();
_setValue(_textbox("search"), "coffee");
_typeKeyCodeNative(java.awt.event.KeyEvent.VK_ENTER); // Press enter key
_focusWindow
_focusWindow()
Arguments
None |
Details
Brings the window above all other windows.
It is generally needed before using other native events or before taking screen shots
Works only on Windows Operating Systems currently. On Mac and Linux, does nothing.
For popup windows, use _selectWindow first.
Brings the window above all other windows.
It is generally needed before using other native events or before taking screen shots
Works only on Windows Operating Systems currently. On Mac and Linux, does nothing.
For popup windows, use _selectWindow first.
_focusWindow(); // bring window into focus.
_takeScreenShot();
// For popup windows, use _selectWindow first
_selectWindow("popWin"); // target further statements at popWin window
_focusWindow(); // bring popup window into focus.
_takeScreenShot();
_windowAction
_windowAction($action[, $width[, $height]])
Arguments
$action | string | Action can be one of
|
$width | integer optional | Specifies the width of the browser window while using the 'resize' option. |
$height | integer optional | Specifies the height of the browser window while using the 'resize' option. |
Details
Performs various window level actions. Current works only on Windows Operating Systems.
On Mac and Linux does nothing.
For popup windows, use _selectWindow first.
Performs various window level actions. Current works only on Windows Operating Systems.
On Mac and Linux does nothing.
For popup windows, use _selectWindow first.
_windowAction("focus"); // focus window. Same as _focusWindw
_windowAction("maximize"); // mazimize window.
_windowAction("minimize"); // minimize window.
_windowAction("restore"); // restore window.
_windowAction("refresh"); // refresh window.
_windowAction("resize",500,300); // resize the window with the given width and height.
// maximizing a popup window
_selectWindow("popWin"); // first select the popWin window to target further steps on.
_windowAction("maximize");
- Search and edit the following section in sahi.properties
[SAHI_INSTALL_PATH\config\sahi.properties]
window_action_api.wait_after_unique_title_set=300 // waits for 3ms after unique title set.
window_action_api.wait_before_title_revert=200 // waits for 2ms before unique title revert.
window_action_api.wait_after_unique_title_revert=500 // waits for 5ms after unique title revert.
_takeScreenShot
_takeScreenShot([$format[, $resizePercentage[, $fileSysPath[, $noLog]]]])
Arguments
$format | string optional | format of the file Can be GIf, JPG or PNG Default is "sahi.takeScreenShot_image.format" property defines in config/sahi.properties, this can be override in userdata/config/userdata.properties |
$resizePercentage | integer optional | image compression in precentage Default is "sahi.takeScreenShot_image.resize_percentage" property defines in config/sahi.properties, this can be override in userdata/config/userdata.properties 100 means no compression |
$fileSysPath | string optional | file path to copy screen-shot in file system |
$noLog | boolean optional | true to prevent embedding the image in playback logs Default is false |
Details
Takes a screen shot and embeds the image in playback logs
Since Sahi works without bringing the window into focus,
we first need to call
Takes a screen shot and embeds the image in playback logs
Since Sahi works without bringing the window into focus,
we first need to call
_focusWindow
to bring the window into focus.info
Sahi currently takes the full window (desktop) screenshot, not just the browser window
_focusWindow(); // bring window into focus
_takeScreenShot();
// captures screen-shot in D:\dev\capture.jpg(compresses file size to 75% of the full size) without embedding image in playback logs
_takeScreenShot("jpg", 75, "D:\\dev\\capture.jpg", true);
_takeScreenShots
_takeScreenShots($enable)
Arguments
$enable | boolean | true for enabling screenshots, false to disable |
Details
Takes a screen shot after every step and embeds the image in playback logs.
Takes a screen shot after every step and embeds the image in playback logs.
_focusWindow(); // bring window into focus
// Enable screenshots
_takeScreenShots(true);
// perform actions
// screenshot will be taken after each step
// disable screenshots
_takeScreenShots(false);
// screenshots will not be taken now.
File Upload
_setFile and _setFile2 are used to set a file in the file input field.Form elements of type "file" cannot be populated using javascript on the browser.
So Sahi has a workaround for handling file uploads.
Sahi intercepts the request in the proxy, reads the file off the file system and inserts it into the multipart request.
The file has to be present on that path on the machine running the proxy.
_setFile
_setFile($element, $filePath[, $actionURL])
Arguments
$element | HTML DOM element | HTML Form File Element whose value needs to be set |
$filePath | string | Path of the file to be uploaded. |
$actionURL | string optional | The form action URL to which the file is submitted. This is an optional parameter. Use it in cases where the form's action URL is changed on setting the file. By default, it uses the form's current action URL. |
Details
_setFile(_file("id"), "C:\\abc\\efg.jpg");
_setFile(_file("id"), "C:\\abc\\efg.jpg", "formSubmit.jsp");
warning
Note that _setFile works in a round about way. It is not handled at the browser level. It is handled at the proxy. So you will not see the file input box being populated with your desired filename. But when the form is submitted, the proxy will add the correct file to the request before it sends it to your web server. But if there are javascript checks before form submit to see if the filename is non-empty, then the script will not work as desired.
info
If there are javascript validations on the file field, use _setFile2 which works in the same way, but changes the file type using javascript so that validations may pass.
_setFile2
_setFile2($element, $filePath[, $actionURL])
Arguments
$element | HTML DOM element | HTML Form File Element whose value needs to be set |
$filePath | string | Path of the file to be uploaded. |
$actionURL | string optional | The form action URL to which the file is submitted. This is an optional parameter. Use it in cases where the form's action URL is changed on setting the file. By default, it uses the form's current action URL. |
Details
Before submitting the file, _setFile2 internally changes the field's type to "text", and then set its value.
Before submitting the file, _setFile2 internally changes the field's type to "text", and then set its value.
_setFile2
is the same as doing the following:// _setFile2 implementation
// set the file
_setFile(_file("file"), "scripts/demo/uploadme.txt");
// Change the "type" attribute of file field
if (_isIE()){
_call(_file("file").outerHTML = _file("file").outerHTML.replace(/type=['"]?file['"]?/, "type=text"));
}else{
_call(_file("file").type = "text");
}
// Set the value into the textbox
_setValue(_textbox("file"), "scripts/demo/uploadme.txt");
info
If you use relative paths in _setFile and _setFile2, they should be relative to
Either use the correct relative path or the full absolute path.
userdata
folder.Either use the correct relative path or the full absolute path.
Troubleshooting
- Look to see if there are any exceptions on the Sahi console (the command prompt). If it shows any FileNotFoundException, correct the path of your file.
- Check if the URL to which the form is being submitted is correct. Sometimes the URL is changed when the form is submitted, and Sahi needs to be told about it using the 3rd parameter in _setFile/setFile2
Identifying action url for _setFile/_setFile2
-
Launch a browser from the Sahi Dashboard.
- Perform the file upload functionality in your app manually.
-
Check the output on the Sahi server console. It will look something like this.
[java] FileUpload: Multipart Request Found [java] Action URL for upload: [java] http://localhost/demo/php/fileUpload.php [java] The above action URL may be required as the third parameter while [java] calling _setFile and _setFile2 APIs. [java] Recording: false [java] For troubleshooting, click on 'Enable Traffic Logs' link on the Sahi Dashboard [java] and perform the upload operation. Upload logs will be created in [java] sahi/userdata/logs/file_upload/ folder.
As you can see from the output,http://localhost/demo/php/fileUpload.php
is the action url in this case.
-
Once you have identified the action url, use that as the third parameter in _setFile/_setFile2.
info
Complete examples on _setFile and _setFile2 are available in sahi/userdata/scripts/demo/fileUpload.sah
It can be run with start URL http://sahi.co.in/demo/
It can be run with start URL http://sahi.co.in/demo/
File upload using native events
Sometimes file uploads with the previous method may fail. In such cases we resort to native events.function setFileUpload($fileEl, $path) {
_focusWindow();
_wait(1000); // needed
// focus on the element
_focus($fileEl);
// click "space" to bring up the browser dialog
_typeKeyCodeNative(java.awt.event.KeyEvent.VK_SPACE);
_wait(1000);
// type the file path
_typeNative($path);
_wait(1000);
// press enter
_typeKeyCodeNative(java.awt.event.KeyEvent.VK_ENTER);
_wait(1000);
}
// Then invoke it like this:
setFileUpload(_file("id"), "C:\\abc\\efg.jpg");
//or
setFileUpload(_file("id"), _resolvePath("uploadme.txt")); // resolves relative to this file
warning
_focusWindow is available since Sahi Pro V4.3. It works only on Windows currently.
File Download
File download overview
Sahi's proxy detects file downloads, and automatically saves them tosahi/userdata/temp/download
directory.Sahi also adds the sessionId to the file name, so that multiple simultaneous tests do not overwrite each others files.
So if you were clicking on a "download" link which downloads a "setup.exe" file, this is how Sahi will handle it.
- Click on "download" link
- Sahi detects that it is a downloadable file, based on its MimeType and Content-Disposition headers.
It then downloads and saves the file into sahi/userdata/temp/download/ after renaming it to
something like: sahi_0384a26207e6104f5f08868032bd170de76d__setup.exe - Once the file is downloaded Sahi exposes the original name of the file ("setup.exe")
through the API: _lastDownloadedFileName() - Another API, _saveDownloadedAs, allows the file to be renamed and copied over to a convenient directory for you to work on.
- API: _clearLastDownloadedFileName() clears out the _lastDownloadedFileName() so that further files can be downloaded and worked upon.
_lastDownloadedFileName
_lastDownloadedFileName()
Arguments
None |
Details
Returns the last downloaded file name.
Returns the last downloaded file name.
_saveDownloadedAs
_saveDownloadedAs($path)
Arguments
$path | string | File path to copy this file into. Needs to be a file path not a directory. If path is relative, it is resolved relative to userdata directory. |
Details
Renames/copies the file into specified directory for further processing.
Renames/copies the file into specified directory for further processing.
_clearLastDownloadedFileName
_clearLastDownloadedFileName()
Arguments
None |
Details
Clears out the _lastDownloadedFileName() so that further files can be downloaded and worked upon
Clears out the _lastDownloadedFileName() so that further files can be downloaded and worked upon
File download APIs example
_assertNull(_lastDownloadedFileName()); // nothing so far
_click(_link("download")); // click on download link
_assertEqual("setup.exe", _lastDownloadedFileName()); // check if downloaded
_saveDownloadedAs("c:/path/myfile.txt"); // save to another path
_clearLastDownloadedFileName(); // clear the variable
_assertNull(_lastDownloadedFileName()); // check to see if cleared.
File download troubleshooting
info
Sahi detects that a file is to be downloaded, based on
- its content type (configurable via sahi/userdata/config/download_contenttypes.txt)
- The Content-Disposition: attachment header
- Whether the URL is configured in sahi/userdata/config/download_urls.txt
If you see a file download dialog during playback, do the following:
- Check if the download URL follows a specific pattern. If yes, add the pattern of the URL to download_urls.txt
Eg., if your download url ishttp://mysite.example.com/export_doc.jsp?id=12318812
, add
to.*export_doc[.]jsp.*
sahi/userdata/config/download_urls.txt
- If there are multiple files that are to be downloaded, and they all are of a particular content-type,
add the content type tosahi/userdata/config/download_contenttypes.txt
- If your file download response always has content-disposition as "attachment", you can tell sahi to
download them by default by setting
indownload.download_if_contentdisposition_is_attachment=true
sahi/userdata/config/userdata.properties
. This is the default since Sahi Pro 4.3.2
Handling file downloads triggered in a new window
Sometimes a webpage may open a new window to show a PDF file.In this case, we need to ask Sahi to send a HTML response back using
_sendHTMLResponseAfterFileDownload API (need Sahi Pro V4.2+).
_sendHTMLResponseAfterFileDownload
_sendHTMLResponseAfterFileDownload($enable)
Arguments
$enable | boolean | true enables html response behaviour, false disables html response |
Details
Forces Sahi to send back an HTML response after file download. Useful when file opens/downloads in a new window.
Add
Forces Sahi to send back an HTML response after file download. Useful when file opens/downloads in a new window.
Add
_sendHTMLResponseAfterFileDownload(true);
before the statement which triggers the download and Sahi will send back an HTML response. To turn it off, call_sendHTMLResponseAfterFileDownload(false);
Use it like this:
_sendHTMLResponseAfterFileDownload(true);
_click(_link("Show PDF in new Window"));
if (_lastDownloadedFileName() != null) {
_saveDownloadedAs("test.pdf"); //Change this to whatever your download directory is
}
_clearLastDownloadedFileName();
_popup("/.*/")._click(_link("Close Window")); // Close the newly opened window
info
Technical Explanation
When the browser navigates to a downloadable file, Sahi automatically downloads the file.
After the file has downloaded Sahi sends a 204 response which essentially asks the page to stay where it is.
Now if that original page has Sahi's code in it, the Sahi script will proceed normally.
If it does not, then the script will stop. Since the PDF window is a fresh window, there is no content in it and Sahi's script stops.
When the browser navigates to a downloadable file, Sahi automatically downloads the file.
After the file has downloaded Sahi sends a 204 response which essentially asks the page to stay where it is.
Now if that original page has Sahi's code in it, the Sahi script will proceed normally.
If it does not, then the script will stop. Since the PDF window is a fresh window, there is no content in it and Sahi's script stops.
File download from a different domain
When a file is downloaded from a different domain than the invoking page, the file will get downloaded touserdata\temp\download
folder successfully. But since the download is from a different domain,it is not associated with the current script session. Hence _lastDownloadedFileName() will return null and
so _saveDownloadedAs() will fail.
To solve this problem, add _addToSession("http://newdomain") in the script before triggering download.
_addToSession
_addToSession($domain)
Arguments
$domain | string | Domain to be associated with the current script session |
Details
Adds the domain to the current script session.
Example:
Adds the domain to the current script session.
Example:
_addToSession("http://downloaddomain.com"); // Here the download url is http. Change downloaddomain.com to your domain.
_addToSession("https://downloaddomain.com"); // Here the download url is https. Change downloaddomain.com to your domain.
danger
NOTE: If it is a https url, it is a MUST to prefix the domain name with "https://".
// add new domain url to Sahi's playback session
_addToSession("http://downloads.mydomain.com");
// NOTE _addToSession comes before click
_click(_link("Download"));
// The download APIs should now work.
_saveDownloadedAs("file.txt");
Once we add _addToSession, _lastDownloadedFileName() will return the correct downloaded file name, and hence _saveDownloadedAs() will work correctly.
Window open/close APIs
_closeWindow
_closeWindow()
Arguments
None |
Details
Closes the current window.
This will work only for popups.
Eg.
Closes the current window.
This will work only for popups.
Eg.
_popup("popWin")._closeWindow();
_closeBrowser
_closeBrowser()
Arguments
None |
Details
Closes the browsers in this session in the middle of a script.
Closes the browsers in this session in the middle of a script.
warning
Use with caution.
- This can be only used when singleSession is false in a suite.
- ALWAYS follow this with _openBrowser(). Otherwise the script will hang.
- A wait(5000) may be needed after closing to allow the browser to clean up properly.
_openBrowser
_openBrowser()
Arguments
None |
Details
Opens the browser in this session in the middle of a script. Used to reopen browser after _closeBrowser.
Opens the browser in this session in the middle of a script. Used to reopen browser after _closeBrowser.
warningUse with caution.
- This can be only used when singleSession is false in a suite.
- Always use it after a _closeBrowser() command
- This will not allow multiple browsers in the same session. Use _launchNewBrowser and _selectBrowser for that
Calling Generic Code
_call
_call($expression)
Arguments
$expression | expression | Any expression which needs to be evaluated on the browser Note that the expression is not quoted and is NOT a string. |
Details
_call is a generic API to bypass Sahi's action APIs and directly call javascript on the DOM.
_call is a generic API to bypass Sahi's action APIs and directly call javascript on the DOM.
// For example, a date field may bring up the calendar, but selecting the year,month etc. may be time consuming.
// For repeated flows, one may want to bypass this by directly setting the value of the field through javascript.
_call(_textbox("date").value = "25/02/1990");
_eval
_eval($evalString)
Arguments
$evalString | string | Any string which needs to be javascript 'eval'ed on the browser |
Details
_eval, like _call, is a generic API to bypass Sahi's action APIs and directly call javascript on the DOM.
However, _eval takes a string instead of an expression.
_eval, like _call, is a generic API to bypass Sahi's action APIs and directly call javascript on the DOM.
However, _eval takes a string instead of an expression.
// For example, a date field may bring up the calendar, but selecting the year,month etc. may be time consuming.
// For repeated flows, one may want to bypass this by directly setting the value of the field through javascript.
_eval("_textbox(\"date\").value = \"25/02/1990\"");
warning_call is recommended over _eval since _call is easier to use.