Selenium 2 & keypress - keypress

I just upgraded to Selenium 2 and having trouble simulating a keypress in firefox (maybe other browsers?). First of all, the new API, using IWebDrivers, does not provide a keypress funktion. I can acquire a ISelenium instance with the 1.0 API (WebDriverBackedSelenium) functions, however I receive an error when using this. E.g.
new WebDriverBackedSelenium(driver, TestServerUrl).KeyDownNative("27");
yields
System.NotSupportedException : keyDownNative
The same is the case for KeyDown, KeyPress etc. Is this not supported in Selenium v2?
Thanks in advance!
/Jasper

Ok so to future reader - I read some of ThoughtWorks documentation and the Selenium v2 API is not quite implemented yet.
So note to self - Big difference between v1 and v2 and v2 API not fully implemented.

To send key presses to an WebElement using Selenium 2 (i.e. to an input field) you can do the following:
// Retrieve the required WebElement object of interest //
WebElement myElement = getWebelement();
// send some chars
myElement.sendKeys("Some Test Text");
Also, to delete text from a WebElement (i.e. an input box) you could do the following:
String BACK_SPACE_UNICODE_CODE = "\u0008";
WebElement inputElement = getWebelement();
String currentValue = inputElement.getAttribute("value");
if (!"".equals(currentValue))
{
for (int count=0;count< currentValue.length();count++)
{
inputElement.sendKeys(BACK_SPACE_UNICODE_CODE);
}
}
Probably best to put this code within a function so it can be used throughout your tests.

Related

How can we use existing selenium scripts (java) to get some end to end performance metrics (low load)

I am trying to leverage existing selenium automation scripts in java developed by Automation team to get some end to end performance metrics (total page load time etc) - very minimal load, in parallel to api load testing.
Please let me know what will be the most efficient way to do that. Also i am looking for making minimum changes to the selenium scripts because this will be an ongoing activity with each release and i am looking for to use functional scripts as it is with performance wrapper around it.
Your suggestions will be appreciated.
thank you!
I would avoid using Selenium for load testing. If setting up dedicated perf tests is not an option, you could at least do this:
//Put this into the loaded scripts of your page under test. Make sure loadTimeMs is a global variable or saved to a hidden control.
var loadTimeMs = 0;
var pageContentRecieved = (new Date()).getTime();
$(window).load(function () {
var pageLoaded = (new Date()).getTime();
loadTimeMs = pageLoaded - pageContentRecieved;
});
That will give you an approximate time to load the sync parts of a page. More importantly is the time for the web server to provide you the content. I recommend doing that in a controlled way by calling the page back as an API in the javascript.
//Return previous value for page load time.
JavascriptExecutor je = (JavascriptExecutor)driver;
int pageLoad = je.executeAsyncScript("return loadTimeMs;");
//Goes into Java code.
je = (JavascriptExecutor)driver;
int apiResponseTime = je.executeAsyncScript(
"var loadTimeMs = 0;" +
"var pageContentRecieved = (new Date()).getTime();" +
"$.ajax({url: "demo_test.txt", success: function(result){" +
"var pageLoaded = (new Date()).getTime();" +
"return pageLoaded - pageContentRecieved;" +
"}});" +
);
int fullLoadTime = pageLoad + apiResponseTime;
Finally, add the two values together for a rough/approximate performance check in the middle of your existing selenium tests.

Google Cast custom receiver timing out

Using the Google CAF Receiver SDK, how do we prevent the receiver from timing out and automatically killing the cast session when we're not using the receiver player?
The standard Google Cast use case is to send media from a device to the cast receiver and have the receiver render the media using a player. The CAF receiver SDK provides this functionality in a beautiful, simple way using the element cast-media-player.
But for those instances when we want to cast from a device and render content where it's not relevant to use the cast-media-player (e.g. an HTML dashboard), how do we keep the receiver alive?
The following custom receiver for example (HAML for brevity), results in the cast session automatically terminating after 5 minutes...
!!! 5
%html
%head
:css
cast-media-player {
display: none;
}
= javascript_include_tag 'https://www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js'
%body
%cast-media-player
:javascript
const context = cast.framework.CastReceiverContext.getInstance();
const player = context.getPlayerManager();
player.setMessageInterceptor(cast.framework.messages.MessageType.LOAD, loadRequestData => {
...[load custom view]...
return false;
});
context.start();
The receiver log shows the line cast.framework.common.IdleTimeoutManager] timer expired and then shuts down. Example receiver log shown here.
I've tried:
Increasing cast.framework.CastReceiverOptions#maxInactivity to a very large number
Periodically loading new data from the sender
Periodically sending custom messages from the receiver to the sender
Periodically sending custom messages from the sender to the receiver
Any help is very much appreciated!
I ran into the same problem while developing a custom receiver app that does not play media. Here is the solution I implemented:
var idleTime = 0;
const context = cast.framework.CastReceiverContext.getInstance();
const CUSTOM_CHANNEL = '[MY CHANNEL HERE]';
context.addCustomMessageListener(CUSTOM_CHANNEL, function(customEvent) {
var eventData = customEvent.data;
parseCommand(eventData);
idleTime = 0;
});
const options = new cast.framework.CastReceiverOptions();
options.disableIdleTimeout = true;
context.start(options);
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 4) { // 5 minutes
context.stop();
}
}
With CastReveiverOptions I disable idle timeout, which according to the documentation: "If true, the receiver will not set an idle timeout to close receiver if there is no activity. Should only be used for non media apps."
https://developers.google.com/cast/docs/reference/caf_receiver/cast.framework.CastReceiverOptions#constructor_1
Since mine is a "non media app," I believe this is correct usage.
I then set my own time out based on 5 minutes of inactivity in my custom channel.
I figured out an alternative way to stop this which is more efficient than periodically sending a silent clip, but it feels dirty. Basically we have to stop Chromecast's setTimeout from firing and closing the connection due to no media. The quickest solution is to simply re-declare setTimeout as a dummy no-op function before loading the Chromecast receiver script. It does not seem to break anything Chromecast-related in this scenario because it looks like Chromecast's timeouts are all related to video which aren't relevant to this use case.
window._setTimeout = window.setTimeout;
window.setTimeout = function(a, b) {
// disable setTimeout so chromecast won't kill us after 5 minutes...
};
Then in our own app if we need to use a timeout we call _setTimeout instead.
I would be interested if anyone has discovered a better way to achieve this, aside from manually hosting cast_receiver_framework.js with the offending line commented out (which is inside the Wn(a, b) function) or sending a silent clip every few minutes. But self-hosting isn't recommended by Google.
A better solution may be to dig deep in the minified code to work out how Xn(a) is called as that disables the timeout whenever media is playing, and then find a way to call that from within the Chromecast app.
Loading a short inaudible audio clip from the sender to the receiver every 4 minutes seems to do the trick. This should not impact performance much if the file is small. Here is some android code.
MediaMetadata metadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MUSIC_TRACK);
MediaInfo mediaInfo = new MediaInfo.Builder("https://some-inaudible-clip.mp3")
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setContentType("audio/mpeg")
.setMetadata(metadata)
.build();
RemoteMediaClient remoteMediaClient = castSession.getRemoteMediaClient();
remoteMediaClient.load(mediaInfo, true);
It is possible to send a custom namespace message from the receiver to the sender. That should keep the heartbeat live. However, your use case is not directly supported by the Cast SDK, so you would have to experiment on a solution.

How to get the battery level from Kontakt.io beacons using AltBeacon API

I need to get the battery level from the kontakt.io beacons. I have set the layout as below and the DataFields are empty when I read the beacons in RangingBeaconsInRegion.
I was expecting I could read the battery level from the last bit as described in the Kontakt.io documentation.
This is my current code:
private BeaconManager InitializeBeaconManager()
{
BeaconManager bm = BeaconManager.GetInstanceForApplication(Xamarin.Forms.Forms.Context);
var iBeaconParser = new BeaconParser();
iBeaconParser.SetBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
bm.BeaconParsers.Add(iBeaconParser);
_rangeNotifier.DidRangeBeaconsInRegionComplete += RangingBeaconsInRegion;
bm.Bind((IBeaconConsumer)Xamarin.Forms.Forms.Context);
return bm;
}
void RangingBeaconsInRegion(object sender, RangeEventArgs e)
{
if (e.Beacons.Count > 0)
{
var beacon = e.Beacons.FirstOrDefault();
var data = beacon.DataFields.FirstOrDefault();
// here DataFields is empty!
}
}
I am using Xamarin Forms and this is the code for the Android Version.
Is this possible? or do I need to use the Kontakt.io API?
UPDATE
I have removed all parsers before apply the new layout and I am able to read the dataFields. However, I am getting a value 8 which I have no idea what this value means.
I am not positive the syntax on Xamarin, but try removing all existing beacon parsers before adding your custom one. I suspect the built in iBeacon parser is still active And it is matching first.
The battery level in Kontakt.io beacons are part of their "scan response packet", not part of the iBeacon structure, you'll have to use CoreBluetooth to read Characteristic 1, Service 5.
A quick breakdown of how this works is also described here, and the recently launched Xamarin component uses the same CoreBluetooth approach.

How to click UI element using JXA

Please tell me how do I click in point coordinates in application window?
I trying to UI automate my application on OSX 10.10 using JXA technology.
In documentation I found that it's possible using click at event. By I'am beginner of JXA and cant find how make a call.
Code snippet which I tried in Script Editor:
var app = Application('my_application_path')
app.window.click.at('{100,100}')
Thank you for help
You can interact with an application's user interface using the System Events application. Here is a script that clicks at certain coordinates in Safari:
// Activate Safari, so you will be able to click like a user
Application("Safari").activate()
// Access the Safari process of System Events
var SystemEvents = Application("System Events")
var Safari = SystemEvents.processes["Safari"]
// Call the click command, sending an array of coordinates [x, y]
Safari.click({ at: [300, 100] })
If you want to click a specific button (or other element of the user interface), it is more appropriate to click that specific element. For example:
// Click the third button of Safari's first window to minimize it
Safari.windows[0].buttons[2].click()
To learn what user interface elements can be interacted with and how, check out the Processes Suite in System Events' scripting dictionary. To open the dictionary, in Script Editor's menu bar, choose Window > Library, then select System Events in the Library window.
See https://github.com/dtinth/JXA-Cookbook/wiki/System-Events#clicking-menu-items
For example:
var fileMenu = proc.menuBars[0].menuBarItems.byName('File');
Below is an example of a portion of a script I wrote that automates creating mailboxes (aka folders) in Mail. I ended up using the UI file menus and click because using make() in the Mail DOM had issues for me. Hope it helps someone.
(() => {}
//this is part of a script that automates creating mailboxes (ie folders) in Apple Mail
//I used the file menu UI because when I tried the Mail library and make() method
//there was strange behavior when trying to interact with the new mailbox.
//However, when creating the new mailboxes thru the file menu, all seems to work fine
const Mail = Application('Mail');
const strId = Mail.accounts.byName('Exchange').id();
const exchange = Mail.accounts.byId(strId);
const activeClientFolder = exchange.mailboxes.byName('ActiveClient');
const SysEvents = Application('System Events');
const mail = SysEvents.processes.byName('Mail');
//next two lines insure Mail will be open and in front
mail.windows[0].actions.byName('AXRaise').perform();
mail.frontmost = true;
const mailboxMenu = mail.menuBars[0].menus.byName('Mailbox');
//below shows EXAMPLES of using .click(), keystroke(), and keyCode()
let newFolder = function (parentFolder, newFolderName, addTrailingDelay = true) {
//next line will select the parent mailbox (aka folder) where the new mailbox will be inserted
Mail.messageViewers[0].selectedMailboxes = parentFolder;
mailboxMenu.click();
delay(.2);
mailboxMenu.menuItems.byName('New Mailbox…').click();
delay(.2);
SysEvents.keystroke(newFolderName);
SysEvents.keyCode(36);
//delay is needed when creating multiple mailboxes with a loop
if (addTrailingDelay == true){
delay(1);
}
}
//now the payoff
const count = newActiveClients.length;
for(let i=0;i<count;i++){
/* Client Root Mailbox */
newFolder(activeClientFolder, newActiveClients[i], true);
/* Client Email Folders */
newFolder(activeClientFolder.mailboxes.byName(newActiveClients[i]), 'Client', true);
newFolder(activeClientFolder.mailboxes.byName(newActiveClients[i]).mailboxes.byName('Client'), 'Client_FYI_Sent');
newFolder(activeClientFolder.mailboxes.byName(newActiveClients[i]).mailboxes.byName('Client'), 'Client_FYI_Inbox');
newFolder(activeClientFolder.mailboxes.byName(newActiveClients[i]).mailboxes.byName('Client'), 'Client_FYI_Client_To');
newFolder(activeClientFolder.mailboxes.byName(newActiveClients[i]).mailboxes.byName('Client'), 'Client_From', false);
}
})()

Selenium webdriver- Click on moving espot images - Amazon.in

I am trying to learn selenium by automating amazon.in
I would like to click on a moving image in an e-spot. It seems there is no class or id. Then how can i proceed?
WebDriver driver= new FirefoxDriver();
#Test
public void test() {
driver.get("http://amazon.in");
driver.manage().window().maximize();
WebElement menu = driver.findElement(By.xpath("//li[#id='nav_cat_2']"));
Actions builder = new Actions(driver);
builder.moveToElement(menu).build().perform();
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[#class='nav_a nav_item' and .=\"All Books\"]")));
WebElement menuOption = driver.findElement(By.xpath("//a[#class='nav_a nav_item' and .=\"All Books\"]"));
menuOption.click();
I have reached on the page. But dont know how to proceed after that.
URL
http://www.amazon.in/Books/b/ref=nav_shopall_books_all/280-9259056-7717210?_encoding=UTF8&node=976389031
As I can see, the images are getting scrolled, so just wait for the concerned image first and then click on it. I have added a code based on that:
wait = new WebDriverWait(driver,60);
wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[#class='acsux-hero-wrap']//li[2]//img")));
WebElement ele = driver.findElement(By.xpath("//div[#class='acsux-hero-wrap']//li[2]//img"));
ele.click();
In the above code, the driver waits till the visibility of the 2nd image is located under 60 seconds. Then, it clicks on that element.
Similarly you can just replace the number li[2] with "li[1]" for first element, "li[4]" for fourth element, and so on.
Use other attributes such as width or alt
//img[contains(#alt,'Children')]
I was able to click on the highlighted image shown in your screenshot although its a different image with different keywords i reckon you'll need some bonded attribute for that image there to be able to click it regardless of its content or so and that'll be something like know the exact div the img tag this and so on.
hope this helps

Resources