Tuesday, December 18, 2012

Selenium 2.28 ready for download


Selenium 2.28
Download from this link.

v2.28.0
=======

WebDriver:
* "null" can now be passed to executeScript
* .Net: Corrected FileUtilities.FindFile() to correctly return the
current directory if the specified file is located there.
* .Net: Introduces the Updating the CustomFinderType property to the
.NET FindsByAttribute. This allows use of custom By subclasses in
the PageFactory. The custom finder must be a subclass of By, and
it must expose a public constructor that takes a string argument.
* SafariDriver: better attempts to catch native dialogs from user
defined onbeforeunload handlers.
* Updating HtmlUnit to 2.11
* Added the PhantomJS bindings to the release. You'll still need to
download PhantomJS itself separately.

RC:
* Implemented getAllWindowNames in WebDriverBackedSelenium
* Implemented openWindow in WebDriverBackedSelenium to allow opening
relative URLs


v2.27.0
=======

WebDriver:
* Added support for native events for Firefox 17.
* Added support for ghostdriver (PhantomJS)
* Adding new capability "enableElementCacheCleanup" to the IE
driver. When set to true, the IE driver will clean the
known-element cache of invalid elements after every page
load. This is intended to keep memory usage down and improve
performance. However, it is an intrusive change, so this
capability is provided temporarily to allow disabling this
behavior if problems arise. The default of this new capability is
"true", meaning this behavior is turned on by default.
* Added shift key handling to the synthetic keyboard actions.
* Modifying scroll behavior in IE driver SendKeysCommandHandler to
call Element::GetLocationOnceScrolledIntoView() instead of calling
the DOM scrollIntoView() function. Should result in less page
scrolling during test runs.
* Checking if CSS transforms on elements, or their parents, are
hiding them and therefore returning they arent visible.
* Add not, refreshed, invisibilityOfElementWithText to
ExpectedConditions.
* Added support for new IE10 pointer events.
* FIXED: 1543: Allowing equal sign in a cookie value.
* FIXED: 2103, 3508: Modified to no longer hang on alerts triggered
by onchange of <select> elements or by onsubmit of <form>
elements.
* FIXED: 2035: Returning a simple result (null) after opening a new
window instead of the window object (that can't be serialized to
JSON).
* FIXED: 2353: Only call blur() for IE if the element is not the
<body> element.
* FIXED: 3043: Better error message reporting when browser launch
fails.
* FIXED: 4490: Checking script evaluation result to prevent null
reference exception.
* FIXED: 4736: Added all of the extended colour keywords to the
Colors enum in support of
http://www.w3.org/wiki/CSS3/Color/Extended_color_keywords.
* FIXED: 4800: Fixed calculation of coordinates for elements in
frames/iframes where the element is scrolled out of view within
the frame.

Grid:
* FIXED: 3818: Generating session identifiers with UUID to prevent duplication.

RC:
* FIXED: 4668: Fixing ability to open relative URLs in WDBS.
* FIXED: 4273: Added getCssCount to the list of the methods
supported by WebDriverBackedSelenium.
* FIXED: 4055: WDBS implementation of getValue for radio buttons now
reflects behaviour of RC.
* FIXED: 4784: Processing locators before use in getCssCount and
getXpathCount.

----

Sunday, November 25, 2012

Selenium - java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.ie.driver system property;

Selenium - java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.ie.driver system property;

IE browser will fail with the above mentioned exception if we upgrade the Selenium webdriver with 2.26.

Reason?
From 2.26 vesrion, IE driver got decoupled from selenium jar file and entire IE driver software is stored in a separate exe file, there are 32 and 64 bit versions.
You need to download the exe file similar to chrome driver and use the following code to run the test.

Sample code Java/TestNG

  WebDriver driver;
@BeforeMethod public void StartDriver() { File file = new File("C:/Seleniumjars/IEDriverServer.exe"); System.setProperty("webdriver.ie.driver", file.getAbsolutePath()); driver = new InternetExplorerDriver(); } @AfterMethod(alwaysRun = true) public void StopDriver() throws Exception { driver.quit(); } @Test(groups = { "GoogleTest" }, enabled = true,timeOut = 90000) public void Test_TC_01_1() throws Exception { driver.get("www.google.com"); }

Technical Reason?
IE driver original implementation was in dll using native C++. As per the client language bindings .dll was extracted during run-time.
For Java extracting from the .jar file.
For .NET extracting it from resource package into WebDriver.dll assembly.
Ruby and Python directly relied on the files, no extraction is required, just reference to the path.
The language bindings would use following method to load the dll and expose the API
JNI for Java
P/Invoke for .NET
ctypes for Python
FFI for Ruby
It works fine for simple scenarios, but due to above differences, IEdriver was showing different behavior between language bindings.
The way .NET bindings loading and managing the .dll, it was able to support multiple instances of IE.
Java bindings was not able to support multiple instances.

In order to unify the experience across all the languages, separate process was created IEDriverServer.exe because now the process management is defined my the operating system (Different version of Windows) and client bindings can interact directly with the process API.

As there is windows limitation where 32 bit process can't be loaded with 64 bit dll, separate 32 and 64 bit process are created.

As the IE driver got decoupled from the selenium release, it is possible to ship the fixes of IE driver without having to wait for complete selenium release.

It is easy to debug a standalone dll then dll loaded by the laungage binding.

Thanks a lot to Jim Evans (IE driver and .NET bindings project lead) for sharing the details and contributing to the open source community.

---

Sunday, November 18, 2012

VS2012 - Web Performance Test - Virtual Users Limit

VS2012 - Web Performance Test - Virtual Users Limit.

I was surprised to see there is no virtual users restrictions (Number of users) for conducting load test using Visual Studio 2012 Ultimate. Generally any commercial load test tool fix the tool cost based on the number of virtual users, technologies (AJAX, Flex, Silver-light..) and monitoring agents, now the trend got changed, need to see how other commercial load test tools like HP loadrunner, Neoload change the licence structure.


---

Friday, November 16, 2012

Visual Studio 2012 - Versions for GUI and Performance Testing

Visual Studio 2012 - Versions for GUI and Performance Testing

Recently I started working with CodedUI and Performance testing using Visual Studio. I have VS2012 Professional and didn't find any option to select CodedUI project, so started investigating which all versions of VS2012 support GUI testing and performance testing. Below screen shot helped me to understand the supported versions of VS2012.



Approx cost of VS2012.


---

Thursday, November 8, 2012

Selenium 2.26 is ready for download.

Selenium 2.26
Download from this link.
Following are the major bug fixes and enhancements.
Hats-off to the development team for frequent releases and you determination to enhance the tool.

v2.26.0
=======
WebDriver:
* Updated OperaDriver to 0.15.
* Added transparency support to the Color class.
* Increased lock time a bit for the FirefoxDriver to make tests more
stable on Windows.
* Added the enablePersistenHover capability to allow the user to specify
whether to use the persistent hover thread in the IE driver. Defaults
to true for IE.
* Added support for native events for Firefox 15 and 16.
* Removed deprecation from ChromeDriver constructors that take a Capabilities
object. Also added a method to set experimental options in ChromeOptions
which may be used to set options that aren't exposed through the ChromeOptions
API.
* Fixed SafariDriver to allow calling .quit() consecutively without error.
* Modified FirefoxDriver to use atoms to switch between frames.
* FIXED: 4535: Hover still does not work perfectly in IE.
* FIXED: 4676: Unable to fire javascript events into SVG's.
* FIXED: 4320: Impossible to IE run tests in parallel via TestNG.
* FIXED: 4309: 'Could not convert Native argument arg 0' error with Firefox.
* FIXED: 4593: Alert.accept() Cancels the Resend Alert/Dialog Box.
* FIXED: 4321: Upgrade HtmlUnitDriver to HtmlUnit 2.10.
* FIXED: 4639: Webdriver 2.25 fails to quit on Windows.
* FIXED: 3774: New SafariDriver sessions do not come with a clean profile.
* FIXED: 4375: Executing javascript hangs Firefox.
* FIXED: 4203: Java SafariDriver has limited websocket frame size.
* FIXED: 4165: WebDriver fails on a machine with no IP address.
* FIXED: 3969: SafariDriver should auto-dismiss alerts.

WebDriverJS:
* FIXED: 4648: findElement errros not helpful.
* FIXED: 4687: webserverjs cannot find module in node.js.
* FIXED: 4649: Wrong Content-Length calculation in webdriverjs.
* FIXED: 4425: Webdriver.js regression: webdriver.By.* selectors defect when
using Node.js.

Grid:
* FIXED: 4433: NPE at grid launch if invalid servlet class name is specified.
* FIXED: 4526: elenium node stop responding when there are 2 or more tests
waiting for a specific node.
* FIXED: 2549: "-role hub" doesn't allow Firefox to starts. ---

Thursday, November 1, 2012

Webdriver - Display Browser Version and Name

Webdriver - Display Browser Version and Name.

Tests are getting executed on different browsers, some time getting confused with the browser name and version of the test results, so I have implemented following code to make an entry in the log file.

  String script = "return navigator.appName;";
Temp = (String) ((JavascriptExecutor) driver).executeScript(script);
Print(Temp);
script = "return navigator.appVersion;";
Temp = (String) ((JavascriptExecutor) driver).executeScript(script);
Print(Temp);
  script = "return navigator.platform;";
  Print((String) ((JavascriptExecutor) driver).executeScript(script));

Print() is a user defined method created in our framework, to know more details select this link

---

Sunday, October 14, 2012

Webdriver - Modal dialog support

Webdriver modal dialog support

How to handle IE modal pop-up in Selenium Webdriver?

Modal dialog? When it is called system displays a dialog that user need to deal with before interacting with the rest of the page.

We can handle the modal dialog through selenium2.0 (Webdriver) in IE, but at few places Selenium is getting stuck with the modal dialog, need to use alternative approach to over come this limitations ( Java Robot class). Currently, Selenium don’t support the modal dialog in Firefox, Safari, Chrome and Opera. 

IE support the modal dialog from Version 4.
Firefox added the support from Version 3.
Safari added the support from version 5.1.
Opera don’t support.
Chrome support from initial versions, but has following bugs Issue 16045, Issue 42939.

Other issues:
1.       Modal dialog as popup – Firefox, chrome and safari consider it as popup and default block it, user need to turn it on.
2.       Debugging – We can’t debug the code even on the latest IE9. Firefox, safari and chrome will let us open the Firebug/Web inspector but difficult to debug.
3.       Mobile – Currently no mobile browser support modal dialog.

It is an old API, but it has been added to the HTML5 spec as there are many old applications written using modal dialog, better to eliminate the “Modal dialog” in the new implementation where multi browser support is required  and usefollowing better options.



---

Wednesday, October 3, 2012

webdriver - modal dialog present

selenium webdriver modal dialog present

Recently we came across a situation where there is no modal dialog or alert, but selenium through "modal dialog present" exception, this issue occurred when there are multiple alerts in the same transaction.

Even the JavaScript executor is not working at this stage, I think Selenium team need to remove the "Modal Dialog Present" validation from the executor, so that when can proceed ahead by running code through JavaScript .

In order to overcome this situation we have used alert.dismiss(), so that selenium proceeded ahead without any exception.

---

Sunday, September 23, 2012

Webdriver change-log URL

Webdriver change-log URL

http://code.google.com/p/selenium/source/browse/trunk/java/CHANGELOG

This link will help you understand the changes and bug-fixes made to Webdriver.

--- 

Wednesday, September 19, 2012

Webdriver NodeJS

What languages do Selenium2/ Webdriver support ?


I think many people are not aware of NodeJS.

Selenium server speaks a simple language called the Webdriver Protocol.
We have NodeJS module called wd that has implemented Webdriver protocol in JavaScript.

What is NodeJS? Below screen shot can help you understand




---

Thursday, September 13, 2012

Smartest smart phone?

Smartest smart phone?



---

Sunday, September 9, 2012

SeleniumWebdriver - Page objects Implementation - Part 2

SeleniumWebdriver - Page objects Implementation - Part 2

SeleniumWebdriver - Page objects Implementation - Part 1

After numerous requests, today I have got time to remove the unnecessary and confidential code and upload the entire project.

This framework is built by integrating Selenium2 + TestNG + ANT + VB Script.

It has taken lot of time to develop this framework, as Selenium is open-source I would like to dedicate this framework to the open-source community. Thanks a lot to Selenium Team for developing awesome  tool.


Download Link (Extract the files into a folder, Elclipse can't extract the files)

1. Create new project "MercuryTours" in eclipse, download the rar file and extract directly into new MercuryTours folder of your corresponding work space.
2. Add the Selenium libraries using configure build path and refresh the project. If there are no error, every thing went fine, attaching the screen shot below.
How to setup Selenium?



3. If you have ANT setup, you can directly run the entire project by selecting the "run", attaching the screen shot below OR you can run the test directly in the eclipse by selecting any class or method and hit play.



4. Test results will be automatically stored the following location "C:\Selenium2_Results\MercuryTours" with time stamp. It will automatically send email notifications, update the details in the "SendEmail.vbs".

I hope above framework will be used for those people who are planning to implement keyword driven framework using page objects.

There are lot of things to explain in this framework, I would suggest to go through the part1 and explore the code.

Good Luck!




Thursday, September 6, 2012

Selenium - java.lang.NullPointerException

Selenium - java.lang.NullPointerException

When do we get this exception?

If we don't initialize the driver object and start using it in the code we can notice this exception.
In the below screen shot I have commented the initialize code and started running the test, system displayed  NullPointerException. In my case, unknowing commented it while debugging the code.

When you get this king of exception, check the driver object initialization.


---
  

Friday, July 27, 2012

How To Setup - Selenium 2.0(Webdriver), JDK, TestNG, ANT on Windows


How To Setup - Selenium 2.0(Webdriver), JDK, TestNG, ANT on Windows

I have written similar post for Selenium1, now it is updated to Selenium2(Webdriver)

Selenium setup checklist
1. JDK
2. ANT
3. Eclipse IDE
4. Eclipse TestNG
5. Selenium
6. How to create selenium project in Eclipse IDE
7. How to execute code in eclipse IDE using TestNG

Select following link to for Selenium full-fledged implementation.

Note: You need to have admin privileges to install few software's.

1. JDK

Download from http://www.oracle.com/technetwork/java/javase/downloads/index.html



JDK is machine and OS dependent, Check whether your machine is 32 OR 64 Bit.
How to Check?
Programs -> Accessories -> System Tools -> System Information

Download your corresponding JRE file and install on your PC.


Check whether it is installed correctly?
Type java  -version at the command prompt, you should see the version related info.

2. ANT (Optional, required to build standalone jar files and scheduling the run)


It is a self installable exe file, located the java JDK directory during installation. 
Logoff and login for complete installation.
Check whether it is installed correctly?
Type ant  - version at the command prompt, you should see the version related info.

3. Eclipse IDE


It is not required to install this software, just run the exe file to open the editor.

4. Eclipse TestNG

Inside the eclipse, select   Help - > Eclipse Market Place
Search for TestNG and install directly into IDE.



5. Selenium


Download Selenium-Server-Standalone-xxx.jar, it is a single jar file and easy to manage.

7. How to create selenium project in Eclipse IDE


Open the Eclipse IDE by selecting eclipse.exe file.
Select File->New -> Java Project


Enter project name and hit “Next”




Select “Finish”
Now you will see the project name "MyFirstProject"  in the “Package Explorer” window.
Right click on the project name and create “Package”


Click on finish after typing the package name "Selenium".


In the package explorer, right click on the package name “Selenium” and select “Configure Build Path”.



Add downloded JAR files showed in the below screen by selecting “Add external jar” button.
You will not be able to run your test without this file, it contain the all the Selenium methods.





Now, right click on the package "Selenium" and select class


Enter class name “Test” and select Finish.



You will notice a new class is created in the package explorer.
In the same way create classes as per your requirement and place necessary code.

8. How to execute code in eclipse IDE using TestNG

Copy the code from the below link and execute the test by selecting the "Play" button.
http://bharath-marrivada.blogspot.com/2011/07/selenium-testng-parameterization-excel.html
http://bharath-marrivada.blogspot.in/2012/06/selenium2webdriver-startiefirefoxchrome.html


If you still see any errors on the screen, place the cursor over the error code, Eclipse IDE provide auto suggestion on how to resolve the issue.


---

Thursday, July 12, 2012

Mobile Platforms

Mobile Platforms

Recently I have started working on the mobile devices and trying to understand all the major platforms available for mobile. Below screen shot help me to understand.




---

Thursday, July 5, 2012

Android - Setting up Office 365

Android - Setting up Office 365
Recently we have migrated to office 365, following video helped me to setup on my mobile with ease.
Find your server related details by logging into www.portal.microsoftonline.com and select the link "Settings for POP, IMAP..." shown in the following screen shot.




Note: Following items are not covered in the below video 
(1) Setting - Accounts and Sync - Background Data need to be checked.
(2) Once mail is configured, you will get - "Update Security Settings" Alert. Select this message from the notifications and Select "Allow" button. 




---

Monday, July 2, 2012

Optical fiber router picture


Optical fiber router data capacity

My ISP provide around 30 Mbps speed which is far greater than my office internet speed (6Mbps), so I was curious to know how he is able to provide me huge bandwidth, this made me to open the router box and investigate the connections, I was amazed to see that one single optical fiber string (size of human hair) is carrying the data, awesome technology. Now I can understand why we left the copper wires technology. Attaching the router box picture, there are 4 optical fibers, out of which 3 are made dummy, only one is connected to the router.



---

Friday, June 29, 2012

Webdriver - Calculate Page Load Time

Webdriver - Calculate Page Load Time

I have a similar post for Selenium1.
Selenium2 automatically wait during page load this is an awesome feature not required to write explicit wait or sync statement, but for AJAX calls need to write extra line of code.
How to calculate the page load time? Using java timers.

You can implement the following code in 3 different ways.

long start;
start = System.currentTimeMillis();
driver.get(url); or click();
Print (driver.getTitle() + " - " + (System.currentTimeMillis() - start) + " MilliSec");

1. Copy the above code where page response calculation is required, but it create redundancy.

2. Implement the code in page object. Below code contain 3 classes, 1 test class and 2 page objects. This code will help you to understand page object implementation and calculate the page download time.

package MercuryTours;


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import MercuryTours.PageObjects.UtilityScript;
import MercuryTours.PageObjects._01_Initilize;
import MercuryTours.PageObjects._02_Login;

public class MercuryTours_TC_05 extends UtilityScript {

private static WebDriver driver;
@BeforeMethod
public static void StartDriver() {
      driver = new InternetExplorerDriver();
}

@AfterMethod(alwaysRun = true)
public void StopDriver() {
driver.quit();
}

@Test(groups = { "MercuryToursTestCases" }, enabled = true,timeOut = 90000)
public void Test_TC_01() throws Exception {
_01_Initilize Initilize = PageFactory.initElements(driver,_01_Initilize.class);
Initilize.zOpen("http://newtours.demoaut.com/");
_02_Login Login = PageFactory.initElements(driver,_02_Login.class);
Login.zEnterCrediantials("qtp123", "qtp123");
}
}


package MercuryTours.PageObjects;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;

public class _01_Initilize extends UtilityScript {

private WebDriver driver;

public _01_Initilize(WebDriver driver) throws InterruptedException {
this.driver = driver;
}

public _01_Initilize zOpen(String url) throws Exception {
driver.manage().timeouts().implicitlyWait(ImplicitWait, TimeUnit.SECONDS);
driver.manage().window().maximize();
long start;
start = System.currentTimeMillis();
driver.get(url);
Print (driver.getTitle() + " - " + (System.currentTimeMillis() - start) + " MilliSec");
return this;
}

} 


package MercuryTours.PageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class _02_Login extends UtilityScript {
private WebDriver driver;

public _02_Login(WebDriver driver) throws InterruptedException {
this.driver = driver;
}

public _02_Login zEnterCrediantials(String UserNameTxt, String PasswordTxt)
throws InterruptedException {
Wait(3000);
driver.findElement(By.name("userName")).sendKeys(UserNameTxt);
driver.findElement(By.name("password")).sendKeys(UserNameTxt);
//driver.findElement(By.name("login")).click();
click(driver.findElement(By.name("login")));
Print("UserName:" + UserNameTxt);
Print("---Login");
Wait(3000);
return this;
}
public void click(WebElement element)  {
long start;
start = System.currentTimeMillis();
element.click();
Print (driver.getTitle() + " - " + (System.currentTimeMillis() - start) + " MilliSec");
}

}

Note: Print() is a custom function written in Utility class, replace it with System.out.Println();

3. By extending the click() method using Webdriver interface.

--- 
   

Wednesday, June 13, 2012

Webdriver - How to start different browsers.

Webdriver - How to start different browsers.

Following example will help you understand how to invoke different browsers using Webdriver, you can also implemented case structure so that browser selection is automatic instead of comment and uncomment the code.


package MercuryTours;


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

//@Listeners({ MercuryTours.TestNG.TestNGCustom.class, MercuryTours.TestNG.TestNGCustomeListener.class })
public class MercuryTours_TC_04 {

private static WebDriver driver;
@BeforeMethod
public static void StartDriver() {

      driver = new InternetExplorerDriver();

/* //Download chromedriver.exe from http://code.google.com/p/chromedriver/downloads/list and place in following location
System.setProperty("webdriver.chrome.driver","C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe");            
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--start-maximized");
        driver = new ChromeDriver(options);*/
     
/*    FirefoxProfile Profile = new FirefoxProfile();
        Profile.setPreference("browser.safebrowsing.malware.enabled", false);
        driver = new FirefoxDriver(Profile);*/

//Safari driver still in experimental stage and run only on Mac
//For Windows need to relay on Selenium1 or RC
//Selenium browser = new DefaultSelenium("localhost", 4444, "*safari", "http://www.google.com");

 //driver = new OperaDriver();


}

@AfterMethod(alwaysRun = true)
public void StopDriver() {
driver.quit();
}

@Test(groups = { "MercuryToursTestCases" }, enabled = true,timeOut = 90000)
public void Test_TC_01() throws Exception {
driver.get("http://newtours.demoaut.com/");
Thread.sleep(7000);

}


}

-----------------

Sunday, May 6, 2012

Tracert - Visually trace the packet flow

Tracert - Visually trace the packet flow.

"Tracert" is a command line program to find number of hops between source and destination. Visual Trace display the hops in the google map, so that people understand the packet route easily.

http://www.yougetsignal.com/tools/visual-tracert/

To start the trace from your computer, type the desired domain and select "Proxy Trace".


---

Understanding cloud response time

Understanding cloud response time

There are many cloud hosting providers, in order to understand the effect of latency on distance select this link.
It provide global statistics from specific geographical locations, so that you can select the right cloud service provider based on your targeted geographical locations.


---

Saturday, May 5, 2012

Gartner report on Application Performance Monitoring(APM)

Magic Quadrant for Application Performance Monitoring(APM)

Gartner report on APM providers list.


APM technologies is subdivided into five dimensions of functionality:
(1)End-user experience monitoring
(2)Application runtime architecture discovery, modeling and display
(3)User-defined transaction profiling
(4)Component deep-dive monitoring in application context
(5)Application performance analytics


Magic Quadrant


For more details select this link

---

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.