Wednesday, April 18, 2012

JavaScript - Generate random number(Integer) with in a range.

JavaScript - Generate random number(Integer) with in a range.

Recently I was working on Neoload script (Performance Testing) where I need to generate random number between 10 to 300.

Random number can be generated using random()
alert(Math.random()); // returns number like 0.98899988888

To generate integers with in the range, I have used following logic.

alert(randomXToY(10,300));
function randomXToY(minVal,maxVal,floatVal)
{
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

minVal - Minimum value
maxVal - Maximum value
floatVal - (Optional) Floating point digits. Value is not defined, it will round to integer value.


---

Friday, April 6, 2012

Webdriver - Timeouts

Webdriver - Timeouts

In webdriver there are three different kinds of time outs. Proper values should be assigned, so that your script run efficiently without waiting for too log or short when page is not loaded and element not preset.

Method Summary
 WebDriver.TimeoutsimplicitlyWait(long time, java.util.concurrent.TimeUnit unit)
          Specifies the amount of time the driver should wait when searching for an element if it is not immediately present.
 WebDriver.TimeoutspageLoadTimeout(long time, java.util.concurrent.TimeUnit unit)
          Sets the amount of time to wait for a page load to complete before throwing an error.
 WebDriver.TimeoutssetScriptTimeout(long time, java.util.concurrent.TimeUnit unit)
          Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error.

Timeouts can also be implemented using TestNG @Test annotation

Example

driver = new InternetExplorerDriver();
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);


Timeouts can also be implemented using TestNG @Test annotation
@Test(groups = { "SampleTest" }, enabled = true, timeOut = 9000)


driver.manage().timeouts().implicitlyWait(ImplicitWait,TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(PageLoadWait,TimeUnit.SECONDS); (Not implemented in IE)
driver.manage().timeouts().setScriptTimeout(AsyScripWait,TimeUnit.SECONDS);

Method Detail

implicitlyWait

WebDriver.Timeouts implicitlyWait(long time,
                                  java.util.concurrent.TimeUnit unit)
Specifies the amount of time the driver should wait when searching for an element if it is not immediately present.When searching for a single element, the driver should poll the page until the element has been found, or this timeout expires before throwing aNoSuchElementException. When searching for multiple elements, the driver should poll the page until at least one element has been found or this timeout has expired.
Increasing the implicit wait timeout should be used judiciously as it will have an adverse effect on test run time, especially when used with slower location strategies like XPath.
Parameters:
time - The amount of time to wait.
unit - The unit of measure for time.
Returns:
A self reference.


setScriptTimeout

WebDriver.Timeouts setScriptTimeout(long time,
                                    java.util.concurrent.TimeUnit unit)
Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. If the timeout is negative, then the script will be allowed to run indefinitely.
Parameters:
time - The timeout value.
unit - The unit of time.
Returns:
A self reference.
See Also:
JavascriptExecutor.executeAsyncScript(String, Object...)


pageLoadTimeout

WebDriver.Timeouts pageLoadTimeout(long time,
                                   java.util.concurrent.TimeUnit unit)
Sets the amount of time to wait for a page load to complete before throwing an error. If the timeout is negative, page loads can be indefinite.
Parameters:
time - The timeout value.
unit - The unit of time.
Returns:


Thursday, April 5, 2012

Webdriver - Can't Click On element

Webdriver - Can't Click On element

Can't Click On element?
Webdriver identified the element correctly, but the element is hidden or disabled so it can't click on it. This is built in validation in webdriver aka Selenium2, this kind of validation was not there in Selenium1.

This kind of validation is good, but some time I am not sure why it throws the error "Can't Click On element".

I came across a scenario where elements are visible on the screen and I am able to select it, but for Webdriver element is not displayed. Run the following statements to check how Webdriver is considering the element attributes.

System.out.println(driver.findElement(By.xpath("//div[1]/img[@alt='Copy Criterion']")).isDisplayed());

System.out.println(driver.findElement(By.xpath("//div[1]/img[@alt='Copy Criterion']")).isEnabled());

These kind of issues occur when there are dynamic changes on the screen using JavaScript, due to some reason Webdriver is not able to update the with the new attributes.

If the element was having an id, I would have run the following statement to click using JavaScript.


script = "document.getElementById('ctl00_cpheRFx_btnCriteriaAdd').click();";
((JavascriptExecutor) driver).executeScript(script);

I will explain my issue using below screenshot. When user select from the drop down, boxes appear on the screen, need to select the icons(Pointed in the screen shot). When I click using following state it says "Can't Click On element".

driver.findElement(By.xpath("//div[1]/img[@alt='Copy Criterion']")).click();


When verified the properties
.isDisplayed() = false
isEnabled() = true

Then I came to the conclusion that I can't use webdriver to click it as the built in validation block the code.
So started working on the click action using JavaScript. Below code resolved my problem. Carefully change the class names and regular expression as per your html.


String Script = "";
Script += "var elements = document.getElementsByTagName('img');";
Script += "var regex = new RegExp('^Copy Criterion');";
Script += "for(i=0;i<elements.length;i++){";
Script += "  if(elements[i].title.match(regex)){";
Script += "     elements[i].click();";
Script += "   }";
Script += "}";
((JavascriptExecutor) driver).executeScript(Script);


Now you got power to click any element on the screen.

Also read

Webdriver -  Issues with Sendkeys & Click

Webdriver - Select list box items
--


Wednesday, April 4, 2012

Webdriver - Store data on disk

Webdriver - Store data on disk.

There are situations where the data of the current test need to be used in the next test. In this scenario we can't store the values in variables, they are lost once the test is completed (Java program closed). It is advisable to store the data on disk using Java files.

Following are the two methods that are used to read and write data to the files.
I have used one single string where all the values are separated by ";". I can use split method to split the string into separate values.

public static void xFileWriteData(String FileName, String DataSemicolnSeperated) throws Exception   {
FileOutputStream out; 
PrintStream p; 
try
{
out = new FileOutputStream(FileName);
p = new PrintStream(out);
p.println (DataSemicolnSeperated); //Insert for loop if there is more than one line
p.close();
out.close();
}
catch (Exception e)
{
Print("Error writing to file");
}
}

public static String xFileReadData(String FileName) throws Exception   {
String DataSemicolnSeperated = null;
String Line;
try
{
BufferedReader br = new BufferedReader(new FileReader(FileName));
while ((Line = br.readLine()) != null) { 
DataSemicolnSeperated = Line;

br.close();

catch (Exception e)
{
Print("Error reading the file");
}
return DataSemicolnSeperated;
}


---- 

Webdiver - Developed in following language

Webdiver - Developed in following language

Select this link for more details


---

Tuesday, April 3, 2012

Webdriver - Not functioning or Missing clicks

Webdriver - Not functioning or Missing clicks.

I ran Webdriver code on different systems. There are instances where the code work fine in all the systems except 1 or 2 systems.
Following are the some of the solutions in this kind of scenario.

1. Files not copied properly or ant build file not created properly.

2. Browser zoom should be 100%. If it is more or less, clicks will fail.


3. When browser loose focus, sometimes clicks are not processed.

4. Browser to be operated in maximized mode. There are situation where Auto suggests values are not selected when working on not maximized mode.
JS code to maximize the browser

String script = "if (window.screen){window.moveTo(0,0);window.resizeTo(window.screen.availWidth,window.screen.availHeight);};"; 
((JavascriptExecutor) driver).executeScript(script);  

5. LAN settings to be Automatically detect settings

There are some of the trouble shooting areas.

Monday, April 2, 2012

Webdriver - How to handle UltraWebGrid

Webdriver - How to handle UltraWebGrid.

In my application to update any cell, use need to "DoubleClick" to get the cell focus and type the text. Initially I have used "SendKeys" and ".innerHTML" values get displayed on the screen, but they are not getting saved.

I have used below code to solve the issue.


Actions action = new Actions(driver);
action.doubleClick(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")));
action.perform();
action.sendKeys(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")), "Bharath");
action.perform();
Wait(5000);
action.doubleClick(driver.findElement(By.id("ctl00_cpheRFx_lblComputed")));
action.perform();
Wait(5000);

driver.findElement(By.id("ctl00_cpheRFx_btnAddRow")).click();
Wait(5000);

UltraWebGrid Screen shot



---



Webdriver - Doubleclick an element

Webdriver - Doubleclick an element.

In order to perform there events we need to use actions class. Below is the sample code.


Actions action = new Actions(driver);
action.doubleClick(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")));
action.perform();
action.sendKeys(driver.findElement(By.id("ctl00xcpheRFxxUltraWebGrid1_rc_4_1")), "Bharath");
action.perform();
Wait(5000);


---