Showing posts with label Learn Selenium. Show all posts
Showing posts with label Learn Selenium. Show all posts

Wednesday, February 4, 2015

How to handle alert and confirm boxes and avoid the Race Condition

Method 1
-----------
Alert alert = null;
Wait<WebDriver> wait = new WebDriverWait(driver, 10, 50);
try {
   alert = wait.until(ExpectedConditions.alertIsPresent());
} catch (TimeoutException ignored) {
}
if (alert != null) {
   alert.accept(); // this line throws the exception
}

Method 2
-------------

public void clickOkOnAlertDialog(String dialogText) {

        Sync sync = Sync.start(20);
        while (sync.continueWaiting()) {
            wait = new WebDriverWait(driver, pageTimeoutInSeconds);
            wait.until(ExpectedConditions.alertIsPresent());
            Alert statusConfirm = driver.switchTo().alert();
            junit.framework.Assert.assertEquals(dialogText, statusConfirm.getText());
            try {
                statusConfirm.accept();
                return;
            } catch (WebDriverException e) {
                sync.sleep(250);
            }
        }
        throw new TimeoutException("Unable to locate and dismiss alert dialog: " + dialogText);
    }
   
Method 3 (Not a good way though)
-----------

((JavascriptExecutor) driver).executeScript("window.alert = function(msg){};");
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg){return true;};");

How FirefoxDriver opens Firefox Browser 
A beta features which makes Firefox Faster 
Enable Firebug in Session started by FirefoxDriver 
How FirefoxDriver Executes the Selenium Commands 

How FirefoxDriver opens the firefox browser?

When the following line is executed

FirefoxDriver driver = new FirefoxDriver();

1)Grab the port
    a)By default firefox attempts to grab the port 7055
    b)7055-1 = 7054, This is called as locking port, which we use as a mutex to make sure only one instance of firefox is started at the time
    c)Sit in a loop waiting the the locking port to become free
    d)Exit loop when we can establish a connection to the server socket(A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.) to the locking port. This driver now has the mutex

2)Find the next free port up from the locking port
    Identify the next free port above the locked one by attempting to bind to each of them in turn. Release the newly found port. For the first driver, this will be 7055.

Until this point the FirefoxDriver has created a socket and FirefoxDriver is listening at the port 7055 for the incoming commands that needs to be executed
But we have not yet launched the browser

3)Locate the Firefox profile to use. This is normally an anonymous one

4)Copy the existing profile to a temporary directory,

5)Delete the current "extensions.cache" to force Firefox to look for newly installed extensions on start up.

6)Update "user.js" with the preferences required to make WebDriver work as expected.
(This is where the Capabilities are set for the browser, Eg EnableJavascript etc)

7)Set the "webdriver_firefox_port" value to the one that we found in the step 2.

Until this point the FirefoxDriver has created a socket and FirefoxDriver is listening at the port 7055 for the incoming commands that needs to be executed
We have selected the profile(default) or the one given from code and the Desired Capabilities are set

8)Start Firefox with the "-silent" flag and telling it to use the freshly minted directory as the profile.
Finally, we launch the Firefox Browser which we can see..!!

9)Wait until that Firefox instance has finished and the process has died.

10)Release the locking port. The mutex has now been freed.

Handle Race Condition in Alerts with Webdriver 
A beta features which makes Firefox Faster 
Enable Firebug in Session started by FirefoxDriver  
How FirefoxDriver Executes the Selenium Commands 

A Beta feature which makes Firefox Webdriver considerable fast


There is beta feature to make firefox not wait for the full page to load after calling .get or .click. This may cause immediate find's to break, so please be sure to use an implicit or explicit wait too. This is only available for Firefox and not other browsers.

   FirefoxProfile fp = new FirefoxProfile();
   fp.setPreference("webdriver.load.strategy", "unstable");
   WebDriver driver = new FirefoxDriver(fp);

Handle Race Condition in Alerts with Webdriver 
How FirefoxDriver opens Firefox Browser 
Enable Firebug in Session started by FirefoxDriver
How FirefoxDriver Executes the Selenium Commands

How to Enable Firebug in the Mozilla session started by Webdriver

Download the firebug xpi file from mozilla and start the profile as follows:

   File file = new File("firebug-1.8.1.xpi");
   FirefoxProfile firefoxProfile = new FirefoxProfile();
   firefoxProfile.addExtension(file);
   firefoxProfile.setPreference("extensions.firebug.currentVersion", "1.8.1"); // Avoid startup screen

   WebDriver driver = new FirefoxDriver(firefoxProfile);

Handle Race Condition in Alerts with Webdriver 
How FirefoxDriver opens Firefox Browser 
A beta features which makes Firefox Faster 
How FirefoxDriver Executes the Selenium Commands 

How Firefox executes the Selenium commands

//How webdriver sends commands to Firefox
--------------------------------
1)Webdriver creates a map/dictionary(based on programming language) with

context : String, opaque key by client language(Redundant)
commandName : The name of the command to execute
parameters : A list of parameters, The typoe depends on the command, This can be empty
elementId : String and an opaquekey that represents the identifier for a particular element

2)Serialize the map using JSON

3)Connect to the socket opened by the Firefox

4)Send the JSON across wire to Firefox

5)It will be Block until the response is sent

//Firefox executes the command
------------------------------

6)Once the command has reached the Firefox, it is deserialized from JSON to Javascript Object

7)The command name is interpreted

8)Some commands don't pay attention to context, for some that do, context is interpreted as window or frame.

9)In order to execute the command, it is looked up in FirefoxDriver prototype.

     eg :
     String url = "http://google.com"
     driver.get(url);

is same as

FirefoxDriver.prototype.get = function(respond, url)

Each function takes at least one parameter: the object that represents the response

FirefoxDriver.prototype.getCurrentUrl = function(respond) {
respond.context = this.context;
respond.response = Utils.getBrowser(this.context).contentWindow.location;
respond.send();
}

10) Calling the "send" method causes the response to be sent via the socket connection back to the client

//Webdiver reads the response
------------------------------

11)The response is another map serialzed in JSON,

methodName : String, Should match "commandName" from the original command sent
context : same as what was sent
isError : Indicated some error has occured(In java this will cause the exception)
responseText A string who's meaning differs depending on the command.

12)If "isError" is true, this will be a description of the error that actually occurred.

Handle Race Condition in Alerts with Webdriver 
A beta features wihich makes Firefox Faster
How FirefoxDriver opens Firefox Browser
Enable Firebug in Session started by FirefoxDriver 
How FirefoxDriver Executes the Selenium Commands

Sunday, January 25, 2015

How to move Slider using Selenium Webdriver


import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;


public class slider {

    public static void main(String[] args) {
       
       
        WebDriver driver = new FirefoxDriver();
        driver.get("http://jqueryui.com/demos/slider/");
        //Identify WebElement
        driver.manage().window().maximize();
        driver.switchTo().frame(0);
       
        WebElement slider = driver.findElement(By.xpath("//span[@class='ui-slider-handle ui-state-default ui-corner-all']"));
       
        //Using Action Class
        Actions move = new Actions(driver);
        Action action = move.dragAndDropBy(slider, 100, 0).build();
        action.perform();

        //driver.quit();

    }

}

Sunday, December 7, 2014

How to download files in Mozilla using Selenium Webdriver

FirefoxProfile firefoxProfile = new FirefoxProfile();

firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

Here text/csv is a mime type, change this mime type depending on the file type you want to download

Popular mine types

PDF => application/pdf
Text file => text/plain
.exe => application/octet-stream
MS Doc => application/msword
xls => application/excel
.zip => application/x-compressed
.tgz => application/gnutar

How to download files in IE using Selenium Webdriver

public void clickAndSaveFileIE(WebElement element) throws AWTException, InterruptedException {

    Robot robot = new Robot();

    // Get the focus on the element..don't use click since it stalls the driver        
    element.sendKeys("");

    //simulate pressing enter          
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

    // Wait for the download manager to open          
    Thread.sleep(2000);

    // Switch to download manager tray via Alt+N
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_ALT);

    // Press S key to save          
    robot.keyPress(KeyEvent.VK_S);
    robot.keyRelease(KeyEvent.VK_S);
    Thread.sleep(2000);

    // Switch back to download manager tray via Alt+N
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_ALT);

    // Tab to X exit key
    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    // Press Enter to close the Download Manager
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

}

How to download files in Chrome using Selenium Webdriver

//Get Chrome Driver
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
String downloadFilepath = "/path/to/download";

//Save Chrome Preferences in Hash Map
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);

//Save Chrome Opions
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
options.setExperimentalOptions("prefs", chromePrefs);
options.addArguments("--test-type");

//Set desired capability
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);

//Start Chrome Driver
WebDriver driver = new ChromeDriver(cap);

Sunday, November 30, 2014

If there is a pop-up coming on the page for a fraction of second, and if you have to capture the text appearing on it, how would you capture it?

Answer to a question from LinkedIn

https://www.linkedin.com/groups/If-there-is-popup-coming-4285318.S.5942940576692314114?view=&item=5942940576692314114&type=member&gid=4285318&trk=eml-b2_anet_digest-hero-4-hero-disc-disc-0&midToken=AQHTpw42IOK2Ew&fromEmail=fromEmail&ut=3htuvU3cBnrSw1

If you using webdriver, then does not matter if what you see on screen or how long it actually appears
Selenium Webdriver just works on the source of your web page, Since you said it is a pop up, either it is alert msg or a javascript pop up.

It cannot be a alert since it appeard for a fraction of second and withtout user input it goes away, so it must be a Javascipt pop up.

To capture this there are two ways.
First, directly invoke the javascript from selenium and capture it seperately and then use them in your actual scipt
Second, Use any Man in the middle Software such as Fiddler(for asp .net but can be used for jsp as well) and stop the screen when the particular Javascript is called so you can capture it.

Sunday, November 23, 2014

Contains() and starts-with() function in Xpath

Certain sites like Google and Yahoo have dynamic attributes,

Eg : <input id="text-12345" />
next time when you try to run in a new sesion the same tag will have the values <input id="text-12567" />
Here 12567 is dynammically generated everytime a new session is created

To handle such dynamic attributes we can use certain Xpath functions like 'starts-with' and 'contains'

tag => <input id="text-12345" />
xpath => //input[starts-with(@id, 'text-')]

When you use starts-with, a part of xpath should remain same and other part will be dynamically generated.

What if the complete xpath is dynamically generated? In this case you cannot automate for external website, whereas if your company owns the site then you can talk to developer and get the script which dynamically generates the xpath and use in your program

contains Xpath functions

Consider the tag
tag => <span class="top heading bold">
Xpath => //span[contains(@class, 'heading')]

Contains is used when an element can be located by a value that could be surrounded by other text, the contains function can be used.

Better way of writing the same would be with CSS selectors
xpath => //div[contains(@class, 'article-heading')]
CSS => css=div.article-heading

For complex xpaths or compound xpaths

Compound Xpaths => //ul[@class='featureList' and contains(li, 'Type')]

Saturday, August 30, 2014

Log4j for Selenium

Apache log4j is a Java-based logging utility.
Logging helps us collect information about how the application is running and also helps us debug if any failure occurs.
With log4j it is possible to enable logging at runtime
When logging is wisely used, it can prove to be an essential tool.

There are many places you can use Log4j,
log4c - It is C based logging library
log4js - Log4js logs the events of the browser remotely on the server, with Ajax you can send logs in XML or JSON format as well
Apache Log4net - Logging for .NET framework
Similarly we have log4perl, PL-SQL-Logging-Utility and Log4db2 providing logging capability for all types of applications

Here is an example for Log4j with JAVA

1)Create a project and add an xml file log4j.xml to it and paste the following contents
Remember, log4j should be at project level, to make it available for all your scripts

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

<appender name="fileAppender" class="org.apache.log4j.FileAppender">

<param name="Threshold" value="INFO" />

<param name="File" value="logfile.log"/>

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" />

</layout>

</appender>

<root>

<level value="INFO"/>

<appender-ref ref="fileAppender"/>

</root>

</log4j:configuration>

2) Understnading the log4j.xml

<appender name="fileAppender" class="org.apache.log4j.FileAppender">
This line will ensure your logs will get appended each you run, rather than creating a new log file for your each run

<param name="File" value="logfile.log"/>
This line will ensure it creates a file by name logfile.log at project level for all logs

<param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" />
Tells in which way you want to print your logs,

Ex
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=
      %d{yyyy-MM-dd}-%t-%x-%-5p-%-10c:%m%n

 Will create log as

 2010-03-23-main--DEBUG-log4j :

You can find more info on pattern mataching in the below link
https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

3)In your Framework's base script add the line

 private static Logger Log = Logger.getLogger(Log4j.class.getName());
 DOMConfigurator.configure("log4j.xml");

 Then, in each of the scripts you can use Log.info and Log.error

Ex

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;


public class Basics_Log4j {


private static Logger Log = Logger.getLogger(Basics_Log4j.class.getName());


public static void main(String[] args) {

DOMConfigurator.configure("log4j.xml");

        Log.info("Printing Info Log from Log4j using Log.info");
        Log.debug("Printing Debug Log from Log4j using Log.debug");
        Log.error("Printing Error Log from Log4j using Log.error");
        Log.trace("Printing Trace Log from Log4j using Log.trace");
}

}

Output in logfile.log

2014-08-30 16:29:21,116 INFO  [Basics_Log4j] Printing Info Log from Log4j using Log.info
2014-08-30 16:29:21,116 ERROR [Basics_Log4j] Printing Error Log from Log4j using Log.error




Jenkins with ANT

Jenkins with ANT

With Jenkins you can perform both local builds and Remote builds, Here is an example which shows how to perform local builds

1) Start the jenkins server


In cmd prompt go to the folder where Jenkins.war and type java -jar Jenkins.war

2)Once the Jenkins server is started, open localhost:8080

3)Click on New item link to add project to Jenkins



4)Enter Project Description and select Build Free style Software Project radio button



5)In bottom of Screen, you will find, a button,Add Build Step, click on it and select Invoke Ant Option
Then click on Advanced, it will shows options as shown in picture

Enter your Ant targets and Path of Build File, Save Changes



6)Go to Dashboard and from project, select Build Now to automatically perform Build


Friday, August 29, 2014

Jenkins - Configuration/Installation

Jenkins - Configuration/Installation

Jenkins CI is the leading open-source continuous integration server.
Built with Java, it provides 975 plugins to support building and testing virtually any project.

Configuring Jenkins

1)Go to https://wiki.jenkins-ci.org and download the latest Jenkins war file
2)Go to cmd prompt and go to the folder where Jenkins.war is present
3)Type java -jar jenkins.war
Jenkins by default will start on localhost:8080, incase you need to start on a different port then use

java -jar jenkins.war --httpPort 9090
This will start Jenkins on localhost:9090

Once done it will show a message like this


JUnit - Parallel Testing

Running your tests in parallel is a powerful way to speed up your tests.
Good automated tests should be independent, isolated and reproducible, making them ideal candidates for being run concurrently
But in real world scenarios of web testing this hardly happens and when it does we must make use of JUnit parallel testing capability to speed up the testing

Example

@Test
public void Test1() {
System.out.println("In Test 1");
}

@Test
public void Test2() {
System.out.println("In Test 2");
}

@Test
public void Test3() {
System.out.println("In Test 3");
}

Runner class

@RunWith(ParallelSuite.class)
@SuiteClasses({Test1.class, Test2.class, Test3.class})
public class ABCSuite {}


Dependencies 

<dependency>
    <groupId>com.googlecode.junit-toolbox</groupId>
    <artifactId>junit-toolbox</artifactId>
    <version>2.0</version>
</dependency>

JUnit - Download and Install

Download the following jars file from http://search.maven.org/

junit.jar
hamcrest-core.jar

Maven Dependencies

JUnit

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>

Hamcrest

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-parent</artifactId>
<version>1.3</version>
</parent>
<artifactId>hamcrest-core</artifactId>
<packaging>jar</packaging>
<name>Hamcrest Core</name>
<description>
This is the core API of hamcrest matcher framework to be used by third-party framework providers. This includes the a foundation set of matcher implementations for common operations.
</description>
</project>

JUnit Exception Testing

In Automation, it is not only important to check if screens behave as expected with correct data, it is also important to check if tests would throw exception when invalid/inappropriate data is given, this will make the Framework more robust

Lets see how JUnit allows us to do Excepton Testing

Example 1

new ArrayList<Object>().get(0); // Array list is empty, so it should result in IndexOutOfBoundsException

  @Test(expected= IndexOutOfBoundsException.class)
    public void empty() {
         new ArrayList<Object>().get(0);
    }
So this test case would pass, if IndexOutOfBoundsException is thrown else the Test case fails

Example 2

 @Test
    public void testExceptionMessage() {
        try {
            new ArrayList<Object>().get(0);
            fail("Expected an IndexOutOfBoundsException to be thrown");
}

         catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {
            assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));
            }
    }

In this way we can not only test what Exception we get but we can also validate what message is thrown 

JUnit Assertions

Assertions is one of the most used and important part of your Framework
JUnit provides overloaded Assertions for all primitive types(ie int, string etc), Objects and Arrays(Primitive and Objects)

Syntax for Assertions
<expected_value> , <actual_value>
or
<String output for failure>, <expected_value> , <actual_value>

Examples

1)Compares if text are same
 @Test
  public void testAssertEquals() {
    org.junit.Assert.assertEquals("failure - strings are not equal", "text", "text");
  }

2)Checks if condition passed results in false, if false_var is evaluated to true then error is shown
Remember this condition can be used to optionally run your test case, if you include this in your @Before Class

  @Test
  public void testAssertFalse() {
    org.junit.Assert.assertFalse("failure - should be false", false_var);
  }

3)Checks if the obect passed is null or not, if not null, then shows error
   @Test
  public void testAssertNotNull() {
    org.junit.Assert.assertNotNull("should not be null", new Object());
  }

4)Checks if two obects are same
  @Test
  public void testAssertNotSame() {
    org.junit.Assert.assertNotSame("should not be same Object", new Object(), new Object());
  }

A slightly different assertion is assertThat, usage is

Syntax
<optional_failure_msg> , <actual_value> , <matcher_Object>

asserThat is used in the suitations, where the actual value is dynamically generated and you can use a matcher obect to verify it at run time with a pattern

Examples

1) This can be used to check your order_num pattern, date etc
 @Test
  public void testAssertThatBothContainsString() {
    org.junit.Assert.assertThat("albumen", both(containsString("a")).and(containsString("b")));
  }

2)Checks the Array List

  @Test
  public void testAssertThatEveryItemContainsString() {
    org.junit.Assert.assertThat(Arrays.asList(new String[] { "fun", "ban", "net" }), everyItem(containsString("n")));
  }

  

Monday, August 25, 2014

What is Reflection API? Advantages of Reflection API and Disadvantages of Reflection API

The Reflection API allows Java code to examine the classes and objects at run time.
The new Reflection classes allows you to call another class methods dynamically a the run time

EXAMPLE

Say you have an object of unknown type in java, you would like to call a method, dosomething on it if it exists

Static typing languages isn't really designed to support this, unless the object conforms to a known interface. But with reflection your code can look at the object and find if it has a method called dosomething and then call if it want to

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class Learn_reflection {


public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {


Learn_reflection t = new Learn_reflection();
Method met[] = t.getClass().getMethods();

for(int i = 0; i<met.length; i++){
if(met[i].getName().equals("Test1")){
met[i].invoke(t);
}
}
}

public void Test1() {
System.out.println("Test1");
}

public void Test2() {
System.out.println("Test2");
}

}


Advantages of Reflection API
1) Helps to look at the methods and objects at run time

DisAdvantages of Reflection API
1) Performance overload, since everything is dynamically resolved, JVM may not be able to perform certain optimizations
2)Security Restrictions : Refecion requires runtime permission to the code, which might not always be allowed

Hover Over Menu in Mozilla, IE and Chrome

There are two ways to do it

Method 1
String menuhoverlink = "//input[xpath]";
String sublink = '//input[xpath]';
Actions builder = new Actions(driver);
builder.moveToElement(driver.findElementBy(menuhoverlink).build.perform();
driver.findElementBy(sublink).click();

Method 2
IWebElement element = driver.findElement(By.XPath("urelementxpath"));
ILocatable hoverItem = (ILocatable)element;
IMouse mouse = ((IHasInputDevices)driver).Mouse;
mouse.MouseMove(hoverItem.Coordinates);
driver.findElement(By.XPath("submenuelementxpath")).Click();