Tuesday, May 13, 2014

Selenium User Guide

Selenium User Guide

Prerequisites:
Selenium IDE : This is a Mozilla Firefox’s addon and can be downloaded from http://release.seleniumhq.org/selenium-ide/1.0.10/selenium-ide-1.0.10.xpi . An addon will ask permission for installation. Follow the steps and restart firefox. Now Selenium IDE is installed and can be accessed through Mozilla Firefox > Tools > Selenium IDE.(Note: The provided link should be opened only through Mozilla Firefox Browser)
SeleniumRCServer: This can be downloadedhttp://selenium.googlecode.com/files/selenium-remote-control-1.0.3.zip .
Nunit:Thiscanbedownloadedfromhttp://launchpad.net/nunitv2/2.5/2.5.9/+download/NUnit-2.5.9.10348.msi .
Microsoft Visual Studio
JRE 1.5 or later

Test Script types in Selenium:

Basic tabular scripts.
Advanced scripts.

Basic tabular scripts

The scripts recorded by Selenium IDE are initially in this format. These scripts are in the tabular format and run by Selenium IDE itself.


Advanced scripts


These scripts are programming language specific. And can run through Nunit + RC Server.

Steps to run Basic Scripts
Start Selenium IDE.
Go to File > Open (Navigate to the location where basic scripts are available)
Select the script(the script will be selected to run)
Click the PLAY button and the script will run.

Result Evaluation

Result can be analyzed from result status bar. If script is passed then Failure=0 and Run = 1 (in case one test script is run at a time). If script is passed then Failure=1 and Run = 0.

Steps to run Advanced scripts


Download and install Nunit, JRE 1.5 or later, Visual Studio and Mozilla Firefox.
Download Selenium RC server.
Configure dot net client drivers (as specified below)
Copy and paste the advanced script into the class1 created in Visual studio in step 3.
Click f6 to Build.
Now open command prompt.
Navigate to the location where Selenium RC is downloaded.
e.g. if it is located in ‘E’ drive then go to: “E:\selenium-remote-control-1.0.3\selenium-server-1.0.3”
In the command prompt run the command. “java -jar selenium-server.jar”. (Don’t close the command prompt)
Open Nunit.
Go to File > Open Project
Navigate to the Visual Studio 2008 > Projects > Selenium Project > Selenium Project > Bin > Debug.
Select Selenium Project.dll.
In Nunit click ‘Run’.
The script will run now in 2 Mozilla Firefox browsers and if the status will be failed then there will be a red bar in Nunit and if status will be passed then the bar will be green.
Among two browsers one will display the log and other will execute the script in GUI format.
The browsers will be automatically closed when the test case is completed.
.NET client driver configuration
.NET client Driver can be used with Microsoft Visual Studio. To configure it with Visual Studio do as Following.
1. Launch Visual Studio and navigate to File > New > Project.
2. Select Visual C# > Class Library > Name your project > Click on OK button.
3. A Class (.cs) is created. Rename it as appropriate.Under right hand pane of Solution Explorer right click on References > Add References.
4. Select following dll files - nmock.dll, nunit.core.dll, nunit.framework.dll,ThoughtWorks. Selenium.Core.dll, ThoughtWorks.Selenium.IntegrationTests.dll, ThoughtWorks.Selenium.UnitTests.dll and click on Ok button.

Monday, May 12, 2014

Working with WebDriver

In this Post, we shall:
‹‹ Run a test with Firefox
‰‰ Working with Firefox profiles
‹‹ Run a test with Google Chrome or Chromium
‰‰ Updating the capabilities of the browser
‹‹ Run a test with Opera
‰‰ Working with Opera Profiles
‹‹ Run a test with Internet Explorer
‰‰ Working with Internet Explorer Driver
So let's get on with it...



Working with FirefoxDriver

FirefoxDriver is the easiest driver to use, since everything that we need to use is all bundled
with the Java client bindings that we used in the previous chapter.
In the next section we are going to see about loading the browser and typing to the screen.
This is what we will be doing in most of our applications.

We are going to do the basic task of loading the browser and type into the page.
1. Update the setUp() method to load the FirefoxDriver();
driver = new FirefoxDriver();
2. Now we need to find an element. In this section we will find the one with
the ID nextBid:
WebElement element = driver.findElement(By.id("nextBid"));
3. Now we need to type into that element:
element.sendKeys("100");
4. Run your test and it should look like the following:
public class TestChapter6 {
WebDriver driver;
@Before
public void setUp(){
driver = new FirefoxDriver();
driver.get("http://book.theautomatedtester.co.uk/chapter4");
}
@After
public void tearDown(){
driver.quit();

Working with WebDriver


}
@Test
public void testExamples(){
WebElement element = driver.findElement(By.id("nextBid"));
element.sendKeys("100");
}

}


A lot of people like to use Firebug with WebDriver but get really annoyed with the First
Run page.
1. To get around this, we are going to have to update the version of Firebug in your
Firefox Preferences.
2. We will set the version to 99.9:
public class TestChapter6 {
WebDriver driver;
@Before
public void setUp(){
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension("firebug.xpi");
profile.setPreference("extensions.firebug.currentVersion",
"99.9");
driver = new FirefoxDriver(profile);
driver.get("http://book.theautomatedtester.co.uk/chapter4");
}
@After
public void tearDown(){
driver.quit();
}
@Test
public void testExamples(){
WebElement element = driver.findElement(By.id("nextBid"));
element.sendKeys("100");
}

}

Monday, May 5, 2014

Introduction to Selenium

Introduction to Selenium


What is Selenium?

Selenium is a free (open source) automated testing suite for web applications across different browsers and platforms.It is quite similar to HP Quick Test Pro (QTP) only that Selenium focuses on automating web-based applications.
Selenium is not just a single tool but a suite of softwares, each catering to different testing needs of an organization. It has four components.
  • Selenium Integrated Development Environment (IDE)
  • Selenium Remote Control (RC)
  • WebDriver
  • Selenium Grid

At the moment, Selenium RC and WebDriver are merged into a single framework to form Selenium 2. Selenium 1, by the way, refers to Selenium RC. 

Who developed Selenium?

Since Selenium is a collection of different tools, it had different developers as well. Below are the key persons who made notable contributions to the Selenium Project
Birth of Selenium Core
Primarily, Selenium was created by Jason Huggins in 2004. An engineer at ThoughtWorks, he was working on a web application that required frequent testing. Having realized that the repetitious manual testing of their application was becoming more and more inefficient, he created a JavaScript program that would automatically control the browser's actions. He named this program as the "JavaScriptTestRunner."
Seeing potential in this idea to help automate other web applications , he made JavaScriptRunner open-source which was later re-named as Selenium Core.

The Same Origin Policy Issue

Same Origin policy prohibits JavaScript code from accessing elements from a domain that is different from where it was launched. Example, the HTML code in www.google.com uses a JavaScript program "randomScript.js". The same origin policy will only allow randomScript.js to access pages within google.com such as google.com/mail, google.com/login, or google.com/signup. However, it cannot access pages from different sites such as yahoo.com/search or guru99.com because they belong to different domains.

This is the reason why prior to Selenium RC, testers needed to install local copies of both Selenium Core (a JavaScript program) and the web server containing the web application being tested so they would belong to the same domain

Birth of Selenium Remote Control (Selenium RC)

Unfortunately; testers using Selenium Core had to install the whole application under test and the web server on their own local computers because of the restrictions imposed by the same origin policy. So another ThoughtWork's engineer, Paul Hammant, decided to create a server that will act as an HTTP proxy to "trick" the browser into believing that Selenium Core and the web application being tested come from the same domain. This system became known as theSelenium Remote Control or Selenium 1.


Birth of Selenium Grid

Selenium Grid was developed by Patrick Lightbody to address the need of minimizing test execution times as much as possible. He initially called the system "Hosted QA." It was capable of capturing browser screenshots during significant stages, and also of sending out Selenium commands to different machines simultaneously.




Birth of Selenium IDE

Shinya Kasatani of Japan created Selenium IDE, a Firefox extension that can automate the browser through a record-and-playback feature. He came up with this idea to further increase the speed in creating test cases. He donated Selenium IDE to the Selenium Project in 2006.



Birth of WebDriver


Simon Stewart created WebDriver circa 2006 when browsers and web applications were becoming more powerful and more restrictive with JavaScript programs like Selenium Core.It was the first cross-platform testing framework that could control the browser from the OS level.




Birth of Selenium 2


In 2008, the whole Selenium Team decided to merge WebDriver and Selenium RC to form a more powerful tool  called Selenium 2, with WebDriver being the core. Currently, Selenium RC is still being developed but only in maintenance mode. Most of the Selenium Project's efforts are now focused on Selenium 2.

So, Why the Name Selenium?

It came from a joke which Jason cracked one time to his team. Another automated testing framework was popular during Selenium's development, and it was by the company called Mercury Interactive (yes, the company who originally made QTP before it was acquired by HP). Since Selenium is a well-known antidote for Mercury poisoning, Jason suggested that name. His teammates took it, and so that is how we got to call this framework up to the present.

Brief Introduction Selenium IDE

Selenium Integrated Development Environment (IDE) is the simplest framework in the Selenium suite and is the easiest one to learn. It is a Firefox plugin that you can install as easily as you can with other plugins. However, because of its simplicity, Selenium IDE should only be used as a prototyping tool. If you want to create more advanced test cases, you will need to use either Selenium RC or WebDriver.

 

Brief Introduction Selenium Remote Control (Selenium RC)

Selenium RC was the flagship testing framework of the whole Selenium project for a long time. This is the first automated web testing tool that allowed users to use a programming language they prefer.As of version 2.25.0, RC can support the following programming languages:
  • Java
  • C#
  • PHP
  • Python
  • Perl
  • Ruby

Brief Introduction WebDriver

The WebDriver proves itself to be better than both Selenium IDE and Selenium RC in many aspects. It implements a more modern and stable approach in automating the browser's actions. WebDriver, unlike Selenium RC, does not rely on JavaScript for automation. It controls the browser by directly communicating to it.
The supported languages are the same as those in Selenium RC.
  • Java
  • C#
  • PHP
  • Python
  • Perl
  • Ruby

Selenium Grid

Selenium Grid is a tool used together with Selenium RC to run parallel tests across different machines and different browsers all at the same time. Parallel execution means running multiple tests at once.
Features:
  • Enables simultaneous running of tests in multiple browsers and environments.
  • Saves timeenormously.
  • Utilizes the hub-and-nodes concept. The hub acts as a central source of Selenium commands to each node connected to it.

Note on Browser and Environment Support

Because of their architectural differences, Selenium IDE, Selenium RC, and WebDriver support different sets of browsers and operating environments.

Selenium IDE
Selenium RC
WebDriver
Browser
Support
Mozilla Firefox
Mozilla Firefox
Internet Explorer
Google Chrome
Safari
Opera
Konqueror
Others

Internet Explorer versions 6 to 9, both 32 and 64-bit

Firefox 3.0, 3.5, 3.6, 4.0, 5.0, 6, 7 and above
(current version is 16.0.1)

Google Chrome 12.0.712.0 and above
(current version is 22.0.1229.94 m)

Opera 11.5 and above
(current version is 12.02)

Android - 2.3 and above for phones and tablets
(devices & emulators)

iOS 3+ for phones (devices & emulators) and 3.2+ for tablets (devices & emulators)

HtmlUnit 2.9 and above
(current version is 2.10)
Operating System
Windows
Mac OS X
Linux

Windows
Mac OS X
Linux
Solaris
All operating systems where the browsers above can run.

How to Choose the Right Selenium Tool for Your Need



Tool
Why Choose ?
Selenium IDE
  • To learn about concepts on automated testing and Selenium, including:
  • Selenese commands such as type, open, clickAndWait, assert, verify, etc.
  • Locators such as id, name, xpath, css selector, etc.
  • Executing customized JavaScript code using runScript
  • Exporting test cases in various formats.
  • To create tests with little or no prior knowledge in programming.
  • To create simple test cases and test suites that you can export later to RC or WebDriver.
  • To test a web application against Firefox only.
Selenium RC
  • To design a test using a more expressive language than Selenese
  • To run your test against different browsers (except HtmlUnit) on different operating systems.
  • To deploy your tests across multiple environments using Selenium Grid.
  • To test your application against a new browser that supports JavaScript.
  • To test web applications with complex AJAX-based scenarios.
WebDriver
  • To use a certain programming language in designing your test case.
  • To test applications that are rich in AJAX-based functionalities.
  • To execute tests on the HtmlUnit browser.
  • To create customized test results.
Selenium Grid
  • To run your Selenium RC scripts in multiple browsers and operating systems simultaneously.
  • To run a huge test suite, that need to complete in soonest time possible.

A Comparison between Selenium and QTP

Quick Test Professional(QTP) is a proprietary automated testing tool previously owned by the companyMercury Interactive before it was acquired by Hewlett-Packard in 2006. The Selenium Tool Suite has many advantages over  QTP (as of version 11) as detailed below -
Advantages of Selenium over QTP
Selenium
QTP
Open sourcefree to use, and free of charge.
Commercial.
Highly extensible
Limited add-ons
Can run tests across different browsers
Can only run tests in Firefox , Internet Explorer andChrome
Supports various operating systems
Can only be used in Windows
Supports mobile devices
Supports mobile devise using 3rd party software
Can execute tests while the browser is minimized
Needs to have the application under test to be visible on the desktop
Can execute tests in parallel.
Can only execute in parallel but using Quality Center which is again a paid product.

Advantages of QTP over Selenium
QTP
Selenium
Can test both web and desktop applications
Can only test web applications
Comes with a built-in object repository
Has no built-in object repository
Automates faster than Seleniumbecause it is a fully featured IDE.
Automates at a slower rate because it does not have a native IDE and only third party IDE can be used for development
Data-driven testing is easier to perform because it has built-in global and local data tables.
Data-driven testing is more cumbersome since you have to rely on the programming language's capabilities for setting values for your test data
Can access controls within the browser(such as the Favorites bar, Address bar, Back and Forward buttons, etc.)
Cannot access elements outside of the web application under test
Provides professional customer support
No official user support is being offered.
Has native capability to export test datainto external formats
Has no native capability to export runtime data onto external formats
Parameterization Support is in built
Parameterization can be done via programming but is difficult to implement.
Test Reports are generated automatically
No native support to generate test /bug reports.

Though clearly, QTP has more advanced capabilities, Selenium outweighs QTP in three main areas:
  • Cost(because Selenium is completely free)
  • Flexibility(because of a number of programming languages, browsers, and platforms it can support)
  • Parallel testing(something that QTP is capable of but only with use of Quality Center)

Summary


  • The entire Selenium Tool Suite is comprised of four components:
  • Selenium IDE, a Firefox add-on that you can only use in creating relatively simple test cases and test suites.
  • Selenium Remote Control, also known as Selenium 1, which is the first Selenium tool that allowed users to use programming languages in creating complex tests.
  • WebDriver, the newer breakthrough that allows your test scripts to communicate directly to the browser, thereby controlling it from the OS level.
  • Selenium Gridis also a tool that is used with Selenium RC to execute parallel tests across different browsers and operating systems.
  • Selenium RC and WebDriver was merged to form Selenium 2.
  • Selenium is more advantageous than QTP in terms of costs and flexibility. It also allows you to run tests in parallel, unlike in QTP where you are only allowed to run tests sequentially.

Selenium Defination

Selenium is an open source automation testing tool for web based applications. Its easy to use,strong and is very flexible. You can work on many operating systems using selenium and you can code in any one of the following languages when using selenium.

Languages supported by Selenium
- Java
- C#
- Ruby
- Pyton
- PHP
- Pearl

Browsers supported by Selenium
- Mozilla(till latest version)
- IE 6,7,8
- Google chrome
- Opera8,9,10


The language which you use is independent of the language in which your application is made. Fox example if your application is made in C#, then you can use selenium with any languages mentioned above to test it. You need to know atleast one programming languages mentioned above in order to learn selenium.
Operating systems Supported by Selenium include windows, mac, linux, unix and many more.


Components of Selenium
- Selenium IDE: Installs as an addon in Mozilla.Only runs in Mozilla. Its got a strong feature of record and run. You can also extend IDE functionality with the help of user extensions. It supports regular extensions, loops, if statements and many other features. You can also parameterize your test cases using IDE. Click here to view 4 hours of Selenium IDE video tutorial.
- Selenium RC: This is the older version of selenium. It works on multiple browsers. RC can be implemented in any one of the programming languages mentioned abve. Click here to view a tutrial covering selenium RC installation and Selenium Tests.
- Webdriver: Webdriver is the new version of selenium. It also works on multiple browsers. Its removed many drawbacks and issues in Selenium RC. It also supports Android and Iphone Testing. Click here to view a tutorial on Webdriver installation and writing Selenium tests.
- Grid: Grid is used to run test cases parallely on multiple machines and browsers.

Certain Features which make it a strong tool to use are:
- Open source
- Works on multiple browsers and multiple operating systems as compared to other tools in market.
- You can develop selenium code and make it run parallely on multiple machines using different browsers.
- Support for Android and Iphone Testing.
- Selenium IDE is a simple tool which comes as an addon in firefox and is easy to use. It has the record and run feature which is very strong.
- You can also extend the functionality/scope of IDE with the help of many plugins available
- You can also create your own Selenium IDE plugins
- Selenium RC is the older version of selenium and is supporting all the languages mentioned above
- Webdriver is the latest version of selenium and is very strong. Its removed lots of drawbacks in RC and introduced many more features in selenium. - Selenium when used with Hudson can be used for Continuous integration.
- Object oriented datadriven or hybrid testing framework can be made very easily.
- You can use open source frameworks such as junit, testng, nuint etc and can write selenium test cases in them 

Thursday, March 27, 2014

SELENIUM GRID


Grid allows you to 

  • scale by distributing tests on several machines ( parallel execution )
  • manage multiple environments from a central point, making it easy to run the tests against a vast combination of browsers / OS.
  • minimize the maintenance time for the grid by allowing you to implement custom hooks to leverage virtual infrastructure for instance.
This example will show you how to start the Selenium 2 Hub, and register both a WebDriver node and a Selenium 1 RC legacy node. We’ll also show you how to call the grid from Java. The hub and nodes are shown here running on the same machine, but of course you can copy the selenium-server-standalone to multiple machines.
Step 1: Start the hub
The Hub is the central point that will receive all the test request and distribute them the the right nodes.
Open a command prompt and navigate to the directory where you copied the selenium-server-standalone file. Type the following command:
java -jar selenium-server-standalone-2.14.0.jar -role hub
The hub will automatically start-up using port 4444 by default. To change the default port, you can add the optional parameter -port when you run the command. You can view the status of the hub by opening a browser window and navigating to:
Step 2: Start the nodes
Regardless on whether you want to run a grid with new WebDriver functionality, or a grid with Selenium 1 RC functionality, or both at the same time, you use the same selenium-server-standalone jar file to start the nodes.
java -jar selenium-server-standalone-2.14.0.jar -role node  -hub http://localhost:4444/grid/register
Note: The port defaults to 5555 if not specified whenever the "-role" option is provided and is not hub.
For backwards compatibility "wd" and "rc" roles are still a valid subset of the "node" role. But those roles limit the types of remote connections to their corresponding API, while "node" allows both RC and WebDriver remote connections.

Using grid to run tests

( using java as an example ) Now that the grid is in-place, we need to access the grid from our test cases. For the Selenium 1 RC nodes, you can continue to use the DefaultSelenium object and pass in the hub information:
Selenium selenium = new DefaultSelenium(“localhost”, 4444, “*firefox”, http://www.google.com”);
For WebDriver nodes, you will need to use the RemoteWebDriver and the DesiredCapabilities object to define which browser, version and platform you wish to use. Create the target browser capabilities you want to run the tests against:
DesiredCapabilities capability = DesiredCapabilities.firefox();
Pass that into the RemoteWebDriver object:
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
The hub will then assign the test to a matching node.
A node matches if all the requested capabilities are met. To request specific capabilities on the grid, specify them before passing it into the WebDriver object.
capability.setBrowserName();
capability.setPlatform();
capability.setVersion()
capability.setCapability(,);
Example: A node registered with the setting:
 -browser  browserName=firefox,version=3.6,platform=LINUX
will be a match for:
capability.setBrowserName(“firefox ); 
capability.setPlatform(“LINUX”);  
capability.setVersion(“3.6”);
and would also be a match for
capability.setBrowserName(“firefox ); 
capability.setVersion(“3.6”);
The capabilities that are not specified will be ignored. If you specify capabilities that do not exist on your grid (for example, your test specifies Firefox version 4.0, but have no Firefox 4 instance) then there will be no match and the test will fail to run.

Configuring the nodes

The node can be configured in 2 different ways; one is by specifying command line parameters, the other is by specifying a json file.

Configuring the nodes by command line

By default, this starts 11 browsers : 5 Firefox, 5 Chrome, 1 Internet Explorer. The maximum number of concurrent tests is set to 5 by default. To change this and other browser settings, you can pass in parameters to each -browser switch (each switch represents a node based on your parameters). If you use the -browser parameter, the default browsers will be ignored and only what you specify command line will be used.
-browser browserName=firefox,version=3.6,maxInstances=5,platform=LINUX
This setting starts 5 Firefox 3.6 nodes on a linux machine.
If your remote machine has multiple versions of Firefox you’d like to use, you can map the location of each binary to a particular version on the same machine:
-browser browserName=firefox,version=3.6,firefox_binary=/home/myhomedir/firefox36/firefox,maxInstances=3,platform=LINUX -browser browserName=firefox,version=4,firefox_binary=/home/myhomedir/firefox4/firefox,maxInstances=4,platform=LINUX
Tip: If you need to provide a space somewhere in your browser parameters, then surround the parameters with quotation marks:
-browser browserName=firefox,version=3.6,firefox_binary=c:\Program Files\firefox ,maxInstances=3, platform=WINDOWS

Optional parameters

  • -port 4444 (4444 is default)
  • -timeout 30 (30 is default) The timeout in seconds before the hub automatically releases a node that hasn't received any requests for more than the specified number of seconds. After this time, the node will be released for another test in the queue. This helps to clear client crashes without manual intervention. To remove the timeout completely, specify -timeout 0 and the hub will never release the node.
Note: This is NOT the WebDriver timeout for all ”wait for WebElement” type of commands.
  • -maxSession 5 (5 is default) The maximum number of browsers that can run in parallel on the node. This is different from the maxInstance of supported browsers (Example: For a node that supports Firefox 3.6, Firefox 4.0  and Internet Explorer 8, maxSession=1 will ensure that you never have more than 1 browser running. With maxSession=2 you can have 2 Firefox tests at the same time, or 1 Internet Explorer and 1 Firefox test).
  • -browser < params > If -browser is not set, a node will start with 5 firefox, 1 chrome, and 1 internet explorer instance (assuming it’s on a windows box). This parameter can be set multiple times on the same line to define multiple types of browsers.
Parameters allowed for -browser: browserName={android, chrome, firefox, htmlunit, internet explorer, iphone, opera} version={browser version} firefox_binary={path to executable binary} chrome_binary={path to executable binary} maxInstances={maximum number of browsers of this type} platform={WINDOWS, LINUX, MAC}
  • -registerCycle = how often in ms the node will try to register itself again.Allow to restart the hub without having to restart the nodes.
  • Relly large (>50 node) Hub installations may need to increase the jetty threads by setting -DPOOL_MAX=512 (or larger) on the java command line.

Configuring timeouts (Version 2.21 required)

Timeouts in the grid should normally be handled through webDriver.manage().timeouts(), which will control how the different operations time out.
To preserve run-time integrity of a grid with selenium-servers, there are two other timeout values that can be set.
On the hub, setting the -timeout command line option to "30" seconds will ensure all resources are reclaimed 30 seconds after a client crashes. On the hub you can also set -browserTimeout 60 to make the maximum time a node is willing to hang inside the browser 60 seconds. This will ensure all resources are reclaimed slightly after 60 seconds. All the nodes use these two values from the hub if they are set. Locally set parameters on a single node has precedence, it is generally recommended not to set these timeouts on the node.
The browserTimeout should be:
  • Higher than the socket lock timeout (45 seconds)
  • Generally higher than values used in webDriver.manage().timeouts(), since this mechanism is a "last line of defense".

Configuring the nodes by JSON

java -jar selenium-server-standalone.jar -role node -nodeConfig nodeconfig.json
A sample nodeconfig file can be seen athttps://code.google.com/p/selenium/source/browse/java/server/src/org/openqa/grid/common/defaults/DefaultNode.json

Configuring the hub by JSON


Hub diagnostic messages

Upon detecting anomalious usage patterns, the hub can give the following message:
Client requested session XYZ that was terminated due to REASON
ReasonCause/fix
TIMEOUTThe session timed out because the client did not access it within the timeout. If the client has been somehow suspended, this may happen when it wakes up
BROWSER_TIMEOUTThe node timed out the browser because it was hanging for too long (parameter browserTimeout)
ORPHANA client waiting in queue has given up once it was offered a new session
CLIENT_STOPPED_SESSIONThe session was stopped using an ordinary call to stop/quit on the client. Why are you using it again??
CLIENT_GONEThe client process (your code) appears to have died or otherwise not responded to our requests, intermittent network issues may also cause
FORWARDING_TO_NODE_FAILEDThe hub was unable to forward to the node. Out of memory errors/node stability issues or network problems
CREATIONFAILEDThe node failed to create the browser. This can typically happen when there are environmental/configuration problems on the node. Try using the node directly to track problem.
PROXY_REREGISTRATIONThe session has been discarded because the node has re-registered on the grid (in mid-test)

Wednesday, March 26, 2014

Selenium Help for Handling Advanced Scripts

Selenium Help for Handling Advanced Scripts


Pause Command:

Thread.Sleep(60000);

(60000 is the time to wait for in milliseconds.)
=============================
Popup Handling:



selenium.WindowFocus();
selenium.WaitForFrameToLoad("aspForm", "10000");


//place this code in place of code:

selenium.SelectFrame("sb-player");

===================================

Order id Store and Use Command:



string ProPrice = "";
string PID = "";
string OrderID = "";
OrderID = selenium.GetEval("this.browserbot.getUserWindow().ya_tid");
PID = selenium.GetEval("this.browserbot.getUserWindow().ya_pid");
ProPrice=selenium.GetEval("this.browserbot.getCurrentWindow().ya_dv");
Assert.IsTrue(selenium.IsTextPresent(OrderID));


=========================================

To open Advanced script in IE:

replace "*chrome" by "*iexplore" in

selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://ecp.fd2009.dev.fdwork.com/");


To maximize browser automatically:



selenium.Open("/");
selenium.WindowMaximize();


=================================
Random No. generation code:



Random ra = new Random();
int iRandom = ra.Next();
string sScheduleName = "test" + iRandom;


in place of parameter name , use "sScheduleName"

i.e.
selenium.Type("ctl00_ContentPlaceHolderBody_txtScheduleName", "test");

will be changed to


selenium.Type("ctl00_ContentPlaceHolderBody_txtScheduleName", sScheduleName);


e.g-2:

selenium.Click("link=test");

will be changed to

selenium.Click("link=" + sScheduleName);

e.g-3:

selenium.Type("ctl00_ContentPlaceHolderBody_txtAddListName", "rough");

will be changed to


string sNewList = "New_List" + iRandom;
selenium.Type("ctl00_ContentPlaceHolderBody_txtAddListName", sNewList);



e.g-4

selenium.Type("ctl00_ContentPlaceHolderBody_txtNewList", "shweta");

will be changed to

string sMergeList = "Merge_List" + iRandom;
selenium.Type("ctl00_ContentPlaceHolderBody_txtNewList", sMergeList);


Executing a block of code for n no of times:


int i;
for (i = 1; i < 3; i++)
{
//selenium.Click("//table[@id='ctl00_ContentPlaceHolderBody_gvWebsite']/tbody/tr[17]/td[11]/a");
selenium.Click("//table[@id='ctl00_ContentPlaceHolderBody_gvWebsite']/tbody/tr['" + i + "'+1]/td[11]/a");
// the value of 17 is changed to ('" + i + "'+1), Note the use of single quotes, double quotes and +1.
}

===============================================================

Executing a block of code if a condition is satisfied and exit the loop if condition is false:


{
if (!Convert.ToBoolean(selenium.IsTextPresent("Preview"))) //if the condition will true then it will exit the loop, else will continue the rest code in the loop
{
continue;
}
//rest code
-----
-----
}

===============================================================

Selenium RC

SELENIUM 1 (SELENIUM RC)
(http://seleniumhq.org/docs/05_selenium_rc.html)

Introduction
As you can read in Brief History of The Selenium Project, Selenium RC was the main Selenium project for a long time, before the WebDriver/Selenium merge brought up Selenium 2, the newest and more powerful tool.
Selenium 1 is still actively supported (mostly in maintenance mode) and provides some features that may not be available in Selenium 2 for a while, including support for several languages (Java, Javascript, PRuby, HP, Python, Perl and C#) and support for almost every browser out there.


How Selenium RC Works
First, we will describe how the components of Selenium RC operate and the role each plays in running your test scripts.

RC Components
Selenium RC components are:
The Selenium Server which launches and kills browsers, interprets and runs the Selenese commands passed from the test program, and acts as an HTTP proxy, intercepting and verifying HTTP messages passed between the browser and the AUT.
Client libraries which provide the interface between each programming language and the Selenium RC Server.
Here is a simplified architecture diagram....
for execution. Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands. The browser, using its JavaScript interpreter, executes the Selenium command. This runs the Selenese action or verification you specified in your test script.

Selenium Server
Selenium Server receives Selenium commands from your test program, interprets them, and reports back to your program the results of running those tests. The RC server bundles Selenium Core and automatically injects it into the browser. This occurs when
your test program opens the browser (using a client library API function). Selenium-Core is a JavaScript program, actually a set of JavaScript functions which interprets and executes Selenese commands using the browser’s built-in JavaScript interpreter.
The Server receives the Selenese commands from your test program using simple HTTP GET/POST requests. This means you can use any programming language that can send HTTP requests to automate Selenium tests on the browser.

Client Libraries
The client libraries provide the programming support that allows you to run Selenium commands from a program of your own design. There is a different client library for each supported language. A Selenium client library provides a programming interface (API), i.e., a set of functions, which run Selenium commands from your own program. Within each interface, there is a programming function that supports each Selenese command.
The client library takes a Selenese command and passes it to the Selenium Server for processing a specific action or test against the application under test (AUT). The client library also receives the result of that command and passes it back to your program. Your program can receive the result and store it into a program variable and report it as a success or failure, or possibly take corrective action if it was an unexpected error.
So to create a test program, you simply write a program that runs a set of Selenium commands using a client library API. And, optionally, if you already have a Selenese test script created in the Selenium- IDE, you can generate the Selenium RC code. The Selenium-IDE can translate (using its Export menu item) its Selenium commands into a client-driver’s API function calls. See the Selenium-IDE chapter for specifics on exporting RC code from Selenium-IDE.


Installation
After downloading the Selenium RC zip file from the downloads page, you’ll notice it has several subfolders. These folders have all the components you need for using Selenium RC with the programming language of your choice. Once you’ve chosen a language to work with, you simply need to:
Install the Selenium RC Server.
Set up a programming project using a language specific client driver.

 Installing Selenium Server
The Selenium RC server is simply a Java jar file (selenium-server.jar), which doesn’t require any special installation. Just downloading the zip file and extracting the server in the desired directory is sufficient.

Running Selenium Server
Before starting any tests you must start the server. Go to the directory where Selenium RC’s server is located and run the following from a command-line console.
java -jar selenium-server.jar
This can be simplified by creating a batch or shell executable file (.bat on Windows and .sh on Linux) containing the command above. Then make a shortcut to that executable on your desktop and simply double-click the icon to start the server. For the server to run you’ll need Java installed and the PATH environment variable correctly configured
to run it from the console. You can check that you have Java correctly installed by running the following on a console:
java -version
If you get a version number (which needs to be 1.5 or later), you’re ready to start using Selenium RC.

Using the .NET Client Driver
Download Selenium RC from the SeleniumHQ downloads page
Extract the folder
Download and install NUnit ( Note: You can use NUnit as your test engine. If you’re not familiar yet with NUnit, you can also write a simple main() function to run your tests; however NUnit is very useful as a test engine.)
Open your desired .Net IDE (Visual Studio, SharpDevelop, MonoDevelop)
Create a class library (.dll)
Add references to the following DLLs: nmock.dll, nunit.core.dll, nunit. framework.dll,
ThoughtWorks.Selenium.Core.dll, ThoughtWorks.Selenium.IntegrationTests.dll and Thought-Works.Selenium.UnitTests.dll
Write your Selenium test in a .Net language (C#, VB.Net), or export a script from Selenium-IDE to a C# file and copy this code into the class file you just created.
Write your own simple main() program or you can include NUnit in your project for running your test. These concepts are explained later in this chapter.
Run Selenium server from console
Run your test either from the IDE, from the NUnit GUI or from the command line
For specific details on .NET client driver configuration with Visual Studio, see the appendix .NET client driver configuration.

Selenese as Programming Code
Here is the test script exported (via Selenium-IDE) to each of the supported programming languages. If you have at least basic knowledge of an object- oriented programming language, you will understand how Selenium runs Selenese commands by reading one of these examples. To see an example in a specific language, select one of these buttons.
In C#:
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using Selenium;
namespace SeleniumTests
{
[TestFixture]
public class NewTest
{
private ISelenium selenium;
private StringBuilder verificationErrors;
[SetUp]
public void SetupTest()
{
selenium = new DefaultSelenium( "localhost" , 4444, "*firefox" , "http://www.selenium.Start();
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
try
{
selenium.Stop();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual( "" , verificationErrors.ToString());
}
[Test]
public void TheNewTest()
{
selenium.Open( "/" );
selenium.Type( "q" , "selenium rc" );
selenium.Click( "btnG" );
selenium.WaitForPageToLoad( "30000" );
Assert.AreEqual( "selenium rc - Google Search" , selenium.GetTitle());
}
}
}

Programming Your Test
Now we’ll illustrate how to program your own tests using examples in programming language. There are essentially two tasks:
Generate your script into a programming language from Selenium-IDE, optionally modifying the result.
Write a very simple main program that executes the generated code. Optionally, you can adopt a test engine platform NUnit for .NET.

C#
The .NET Client Driver works with Microsoft.NET. It can be used with any .NET testing framework
like NUnit or the Visual Studio 2005 Team System.
Selenium-IDE assumes you will use NUnit as your testing framework. You can see this in the generated
code below. It includes the using statement for NUnit along with corresponding NUnit attributes
identifying the role for each member function of the test class.
You will probably have to rename the test class from “NewTest” to something of your own choosing.
Also, you will need to change the browser-open parameters in the statement:
selenium = new DefaultSelenium("localhost", 4444, "*iehta", "http://www.google.com/");
The generated code will look similar to this.
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using Selenium;
namespace SeleniumTests
{
[TestFixture]
public class NewTest
{
private ISelenium selenium;
private StringBuilder verificationErrors;
[SetUp]
public void SetupTest()
{
selenium = new DefaultSelenium( "localhost" , 4444, "*iehta" ,
"http://www.google.com/" );
selenium.Start();
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
try
{
selenium.Stop();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual( "" , verificationErrors.ToString());
}
[Test]
public void TheNewTest()
{
// Open Google search engine.
selenium.Open( "http://www.google.com/" );
// Assert Title of page.
Assert.AreEqual( "Google" , selenium.GetTitle());
// Provide search term as "Selenium OpenQA"
selenium.Type( "q" , "Selenium OpenQA" );
// Read the keyed search term and assert it.
Assert.AreEqual( "Selenium OpenQA" , selenium.GetValue( "q" ));
// Click on Search button.
selenium.Click( "btnG" );
// Wait for page to load.
selenium.WaitForPageToLoad( "5000" );
// Assert that "www.openqa.org" is available in search results.
Assert.IsTrue(selenium.IsTextPresent( "www.openqa.org" ));
// Assert that page title is - "Selenium OpenQA - Google Search"
Assert.AreEqual( "Selenium OpenQA - Google Search" ,
selenium.GetTitle());
}
}
}
You can allow NUnit to manage the execution of your tests. Or alternatively, you can write a simple main() program that instantiates the test object and runs each of the three methods, SetupTest(), The- NewTest(), and TeardownTest() in turn.

Learning the API
The Selenium RC API uses naming conventions that, assuming you understand Selenese, much of the interface will be self-explanatory. Here, however, we explain the most critical and possibly less obvious aspects.

Starting the Browser
In C#:
selenium = new DefaultSelenium( "localhost" , 4444, "*firefox" , "http://www.google.com/" selenium.Start();

This example opens the browser and represents that browser by assigning a “browser instance” to a program variable. This program variable is then used to call methods from the browser. These methods execute the Selenium commands, i.e. like open or type or the verify commands. The parameters required when creating the browser instance are:
host Specifies the IP address of the computer where the server is located. Usually, this is the same machine as where the client is running, so in this case localhost is passed. In some clients this is an optional parameter.

port Specifies the TCP/IP socket where the server is listening waiting for the client to establish a connection. This also is optional in some client drivers.

browser The browser in which you want to run the tests. This is a required parameter.

url The base url of the application under test. This is required by all the client libs and is integral information for starting up the browser-proxy-AUT communication.

Note that some of the client libraries require the browser to be started explicitly by calling its start() method.