Automation Scripts
Automation Scripts
• Selenium is an open source testing tool to automate web applications across many
platforms.
• This tool is developed in Java Script and supports all the major browsers on all the
platforms.
• There are 3 variants in selenium, which can be used to create automation suite for web
application.
Selenium IDE
Selenium IDE
Selenium Core
Selenium Core tests run directly in a browser, just as real users do.
Selenium Core tests run directly into application web server. This allows the tests to run in any
supported browser on the client-side.
1. A server which automatically launches and kills browsers, and acts as a HTTP proxy for
web requests from them.
2. Client libraries for your favorite computer language.
The RC server also bundles Selenium Core, and automatically loads it into the browser.
Selenium Grid
Selenium Grid is a tool that speeds up functional testing of web-apps. It allows running multiple
tests in parallel, on multiple machines, in a heterogeneous environment. Selenium Grid
coordinates multiple selenium remote control servers, so that test can be run on different
platforms concurrently, which saves time and allows wider testing.
Overall architecture of the selenium
Classification of selenium
The same origin policy states that JavaScript is only allowed to read/modify HTML from the
same origin as its source.
That policy makes a lot of sense. Let's say you've got your browser window pointing at, for
example, your bank's website, but you also have another webpage open pointing to someone's
blog. JavaScript is allowed to read values from web pages, as well as change data appearing on
webpages you've loaded. If not for the same origin policy, a malicious blogger could read your
bank data, or worse, rewrite your bank page to make you think it was saying something else. The
blogger could use JavaScript to trick you into giving him sensitive information.
Selenium Core needs to be installed on the same website as the Application Under Test (AUT),
because of the Same Origin Policy, a security policy which prevents cross-site scripting. That
means that one can't just sit down and write a Selenium Core test that runs on google.com; to do
that, one should need to install Selenium Core on google.com. The same origin policy states that
JavaScript is only allowed to read/modify HTML from the same origin as its source. If a js file is
designed to test google.com, the same origin policy denies to run that js file with google.com;
instead, selenium RC can be used to test the site. Selenium RC makes a proxy server, which
allows running the test against the site. Selenium JS files were actually available on the remote
server and the proxy server tricks the browser into thinking there is a directory example:
http://www.google.com/selenium/
Installation of Selenium
1. Selenium IDE
Setting up Selenium RC
Note:
• If you are going to use firefox 3, then make sure that your download support for
the latest version.
• Before going to test the automations close all the firefox process in your system,
which may also restrict to start browser.
3. Selenium Grid
Selenium Grid requires java-1.5(+) and also Ant 1.7 (+) to start the hub.
Setting up of selenium Grid
4. Selenium Eclipse
Developing the selenium java along with eclipse makes the work simpler. Test cases can
be written in java and it can be executed using eclipse plug-in. Download Selenium
Eclipse. (Add the downloaded selenium plug in to your eclipse\plugins folder) Eclipse
requires JUnit/TestNG along with selenium to run the script. The selenium project can
also be developed using JUnit4.4.
• Set system variables for junit
JUNIT_HOME=“/*--path of junit jar file c:\selenium\junit-4.4\junit-
4.4.jar--*/”
5. Logging Selenium
Logging selenium is required for selenium Junit project to produce log report for the test
cases. Logging selenium is a java plug-in which can be included to the selenium project.
Logging selenium also requires commons-langs 2.4 to generate log report for the test
case.
Getting Started with Selenium IDE
Selenium IDE
Selenium RC can also run html test suite in test runner and it produce log report.
For example: java –jar selenium-server.jar –htmlSuite -browser=”*chrome” –
url=”http://www.google.com” c:\selenium workspace\testsuite.html c:\selenium
workspace\report\log-Result.html
Selenium RC can also run the selenium java test case from eclipse.
A. To run the test in sequence, launch only one remote control. To launch the remote
control, in new command prompt, type
ant launch-remote-control
then in a new command prompt, type
ant run-demo-in-sequence
B. To run the test in parallel in same machine, launch two or more remote control. Start
new terminal for each remote control, then type
ant -Dport=5555 –Denvironment=”*chrome” launch-remote-control
ant -Dport=5566 –Denvironment=”*iexplore” launch-remote-control
ant -Dport=5577 –Denvironment=”*chrome” launch-remote-control
(Note: To check, type http://localhost:4444/console in browser, this will display the details of the
remote control)
C. To run the test in parallel in multiple machine, launch two or more remote control.
Start new terminal for each remote control, then type
ant -Dport=5555 –Dhost=192.170.50.32” –
DhubURL=“http//192.170.50.96:4444” –Denvironment=”*chrome” launch-remote-
control
ant -Dport=5555 –Dhost=”192.170.50.64” –
DhubURL=”http//192.170.50.96:4444” –Denvironment=”*chrome” launch-remote-
control
Then in a new terminal, type
ant run-demo-in-parallel
In Third case, the hub is launched in the system with the ip=192.170.50.96 but the remote control
is launched in two different machines with ip=192.170.50.32 and ip=192.170.50.64. In this case
console details can be viewed using http://192.170.50.96:4444/console
To run this in command prompt, move to the project location (build.xml), then type
ant AllTests
Creating Simple Test Case in Selenium
Create a new selenium project and create a new JUnit Test case. Record a simple test using
selenium IDE and export the test to new test case.
For Example:
import com.thoughtworks.selenium.*;
import junit.framework.*;
public class GoogleTest extends TestCase {
private Selenium selenium;
Now launch the selenium hub in a new terminal and launch a remote control with environment as
“*chrome” in another terminal. Now run the test in JUnit, which automatically open a new
firefox browser, opens a google.com and automate the test.
(Note: Selenium may not work properly in firefox 3.0 browser, but it works properly in firefox
2.x)
Creating Simple Test Suite in Selenium
Create two or more selenium test cases in same project. Then create a new JUnit test suite. Now
add each test case class to new test suite. Here is an example for a test suite which includes
different user test cases.
import junit.framework.Test;
import junit.framework.TestSuite;
import com.EvalinvalidUser;
import com.Evalowner;
import com.Evaluser;
import com.Owner;
public class UserTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for user test cases");
suite.addTestSuite(Evaluser.class);
suite.addTestSuite(EvalinvalidUser.class);
suite.addTestSuite(Owner.class);
suite.addTestSuite(Evalowner.class);
return suite;
}
}
Now run the test suite as same as the test case. That is launch a hub and a remote control and run
the suite in JUnit Test. This will automatically launch a browser and automate the first test case
and tear down the browser. Then it will launch another browser and automate the second test
case and tear down the browser and so on.
JUnit uses annotations to identify which methods should be used for testing. The following are
the list of annotation which can be used to write a test. These annotations can be import to the
class using org.junit.<annotation>
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
Public void helloWorld() throws Exception{
}
@RunWith(Suite.class)
@Suite.SuiteClasses({
EvalUser.class, EvalinvalidUser.class
})
public class UserTests {
}
Generating HTML Log Report for Test
Selenium test result can be logged using LoggingSelenium. LoggingSelenium can generate
html/xml log report for the test. HTML result report can be viewed directly in browser which is
almost similar to the htmlsuite report generated by selenium RC. Here is the basic usage for the
loggingselenium.
@Before
public void setUp() {
final String resultPath = "absolute-path-to-where-your-result-will-be-written";
final String resultHtmlFileName = resultPath + File.separator + "result.html";
final String resultEncoding = "UTF-8";
loggingWriter = LoggingUtils.createWriter(resultHtmlFileName, resultEncoding);
LoggingResultsFormatter htmlFormatter = new HtmlResultFormatter(loggingWriter,
resultEncoding);
htmlFormatter.setScreenShotBaseUri(""); // this is for linking to the screenshots
htmlFormatter.setAutomaticScreenshotPath(resultPath);
// wrap HttpCommandProcessor from remote-control
LoggingCommandProcessor log_Processor = new LoggingCommandProcessor(new
HttpCommandProcessor("localhost",4444,"*chrome",”http://google.com”), htmlFormatter);
selenium = new LoggingDefaultSelenium(myProcessor);
selenium.start();
}
@After
public void tearDown() {
selenium.stop();
try {
if (null != loggingWriter) {
loggingWriter.close();
}
} catch (IOException e) {
// do nothing
}
}
In Loggingselenium, the result path of the html file should be specified. Then the result type
encoding should be specified. Then create an object to the loggingWriter which automatically
log each and every command of the test. LoggingResultsFormatter is used to specify the format
log report. LoggingCommandProcessor will start the selenium test as well as log the command
of test.
LoggingSelenium will also be used for taking screenshot of the test. Screenshots can be taken
automatically by the loggingselenium when an exception occurs. Screenshots are stored at the
absolute path of the system, so screenshots may throw error while testing it on multiple system.
Screenshots can also be captured manually whenever it is required for the test.
System.getProperty(SELENIUM_BROWSER_STARTCOMMAND),
System.getProperty(SELENIUM_BROWSER_URL));
The above code can be included into the test which will get the command-line arguments. While
using eclipse for developing the selenium project, command line arguments can be given at the
run dialog box. To run in eclipse, Select Run->Open Run Dialog. Then in run dialog box, select
Arguments tab, in VM arguments specify the command line arguments than click run.
-Dselenium.server.host=localhost
-Dselenium.server.port=4444
-Dselenium.browser.startCommand=*chrome
-Dselenium.browser.url=http://google.com
This command line arguments value can be changed to test in different browser directly without
changing the browser name in code.
Page Object Pattern
The Page Object pattern represents the screens of web application as a series of objects. This
reduces the amount of duplicated code and means that if the UI changes, the fix needed to be
applied in only one place. Page Objects may not be necessarily a screen of web application; it
may be a part of the screen. In Page Object pattern has two faces, one is the facing towards the
page and another one is facing away from the page. Facing towards the page is defining a class
with various methods and attributes for a particular page. Facing away is the test case which uses
those page objects methods for the test.
@Test
public void loginTest() throws InterruptedException, ParseException {
selenium.open("/");
selenium.type("txtUserId", "User_NameXXX");
selenium.type("txtPassword", "PasswordXYZ");
selenium.click("//input[@type='signin']");
selenium.waitForPageToLoad("30000");
selenium.click("link=Sign out");
selenium.waitForPageToLoad("30000");
}
The above test case can be implemented using page object pattern. To use a page object, it needs
a separate class for login page with various methods.
@Test
public void testUserLogin() {
IndexPage index = new IndexPage(); // Open home page
LoginPage loginPage = index.loginPage(); // Go to login page
HomePage homepage = loginPage.login("user", "password");
assertTrue(homepage.checkID());
homepage.signOut();
}
Selenium Commands
Selenium commands are mainly depends on three objects, which is used to tell HTML element
of the page.
1. Element Locators
Element Locators are used to specify the exact location of the page. These element
locators are used by the selenium commands as an argument. The following are the
element locators which is supported in the selenium,
• identifier=id
• id=id (Select the element with the specified @id attribute.)
• name=name (Select the element with the specified @name attribute)
• dom=javascript Expression
• xpath=xpath Expression(XPath uses path expressions to select nodes or node-sets
in an XML document.)
• link=textPattern
• css=cssSelector syntax(CSS Selector is a flat description of the HTML or XML
fragment corresponding to the selection structure.)
The selenium can be located using without the explicit prefix/value. The following are
used to specify without the explicit prefix/values.
• dom
• xpath
• id
2. Element Filters
Element filters can be used with a locator to refine a list of candidate elements.
filterType=argument
For Example:
xpath=//form[@type='input' and @name='xxx']
In this example @name is an attribute which is used as filter to fetch the element with
name=xxx.
3. String-match patterns
Selenium uses the string-match patterns to fetch the matching string values.
• glob(default pattern, which is the limitation of the regular expression)
• regexp
• exact
Limitation of Selenium
void selectWindow(windowID)
once a popup window has been selected, all commands go to that window. To select the
main window again, use null as the target/windowID.
Selenium has several strategies for finding the window object referred to by the
"windowID" parameter.
If windowID is null, then it is assumed the user is referring to the original window
instantiated by the browser.
If the value of the "windowID" parameter is a JavaScript variable name in the
current application window, then it is assumed that this variable contains the return
value from a call to the JavaScript window.open() method.
Otherwise, selenium looks in a hash it maintains that maps string names to window
objects. Each of these string names matches the second parameter "windowName"
past to the JavaScript method window.open(url, windowName, windowFeatures,
replaceFlag) (which selenium intercepts).
void selectFrame(locator)
This command is used multiple times to select nested frames. To select the parent
frame, use "relative=parent" as a locator; to select the top frame, use "relative=top" and
to select the immediate parent, use “relative=up”.
(NOTE: While navigating from non-framed page to a framed page, selenium uses selectFrame to
navigate between the frames. Whereas, moving from a frameset page to a non-framed page,
selenium may close all the frames in page. This may lead to termination of selenium.)
boolean getWhetherThisWindowMatchWindowExpression
(java.lang.String currentWindowString , java.lang.String target)
Determine whether current/locator identify the frame/window containing this running code.
This is useful in proxy injection mode, where this code runs in every browser frame and window,
and sometimes the selenium server needs to identify the "current" frame/window. In this case,
when the test calls selectFrame/selectWindow, this routine is called for each frame/window to
figure out which one has been selected. The selected frame/window will return true, while all
others will return false.
3. Pop-up dialog box problem
java.lang.String getAlert()
java.lang.String getConfirmation()
java.lang.String getPrompt()
JavaScript dialog box is generated during the previous action or fail if there were no
alerts.
Getting an alert or confirmation or prompt has the same effect as manually clicking
OK/CANCEL. If a dialog box is generated but you do not get/verify it, the next
Selenium action will fail.
NOTE: under Selenium, JavaScript alerts will NOT pop up a visible dialog box.
NOTE: Selenium does NOT support JavaScript alerts that are generated in a page's
onload() event handler. In this case a visible dialog WILL be generated and Selenium
will hang until someone manually clicks OK.
Applet Application can’t be tested directly using selenium. Applet Application can be
exported as javascript enabled application and then the javascript can be tested using
selenium.
Selenium can’t able to test Flash and Flex Application directly. To Test a Flash and
Flex Application, Selenium-Flash and Selenium-Flex API plug-ins are needed. These
Flash and Flex Plug-in has separate action script file which should be included in the
project to test the application. So Flash and Flex applications are very difficult to test in
selenium grid.
Limitations Selenium over HeyMath!
Almost all the popup window in HeyMath site doesn’t have window name/id.
Lessons are opening as popup window which don’t have any popup window name/id,
so these popup window can’t be accessed during the automation.
(Suggestion: Popup window page can be tested by directly opening the site by its URL
and it can be tested.
For eg:
Selenium.open(/lessons/lesson1.jsp);
This can open the page directly, instead clicking the link and opening it in a popup
window.)
Links like CMS, Benchmark, etc are opening the page in a separate page using
javascript about blank page. Tough these pages are more similar to popup window
page; these pages are not really a popup window. These pages are opening as a
separate window or new window. These types of pages are not visible to selenium
test runner, so creating automation for these types of links are not possible.
(Note: selenium open command can also be used to test this type of pages, but there
should not be anymore javascript about blank page)
After moving from free zone page to Home page, site is moved from non-framed
page to a framed page. HeyMath! Banner and Sign Out are two places where the
page move to a non framed page, which closes all other non related frames in the
page, So this may terminate the selenium.
(Suggestion: selenium open command can be used to go to free zone page and log out the
user)
The Places like create assignments, do assignments, upload and download of files,
etc., are possibility of occurrence of dialog box. So failure test cases can’t be tested
for these places.