Saturday, December 17, 2011

Clear Browser Cache

We can press Control + F5 using webdriver to clear the browser cache.

            Actions actionObject = new Actions(driver);
            actionObject.keyDown(Keys.CONTROL).sendKeys(Keys.F5).keyUp(Keys.CONTROL).perform();

Disabling caching in ChromeDriver

For disabling caching in ChromeDriver we can use the chrome switches with  DesiredCapabilities

DesiredCapabilities dc = DesiredCapabilities.chrome();
                ArrayList<String> switches = new ArrayList<String>();
                switches.add("--proxy-server="+InetAddress.getLocalHost().getHostAddress()+ ":" + Integer.parseInt(port));
                switches.add("--proxy-bypass-list=local.addthis.com");
                switches.add("--disable-application-cache");
                dc.setCapability("chrome.switches", switches);

More details about chrome switches

Maven ant run plugin

Simulate all the tasks of ant script and also used to call external ant targets from a maven pom.


<groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.7</version>
    <configuration>
      <tasks>
        <echo message="hello ant, from Maven!" />
        <echo>Maybe this will work?</echo>

        <ant antfile="${basedir}/build.xml">
          <target name="test" />
        </ant>

       <exec dir="${basedir}" executable="cmd"
         failonerror="true">
         <arg line="/K start" />
         <arg line="one.bat" />
       </exec>

      </tasks>
    </configuration>
   </plugin>
Sample Usage : mvn antrun:run

Tuesday, November 1, 2011

Disabling caching in FirefoxDriver

 Firefox profile with no caching enabled.

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.cache.disk.enable", false);
profile.setPreference("browser.cache.memory.enable", false);
profile.setPreference("browser.cache.offline.enable", false);
profile.setPreference("network.http.use-cache", false);
WebDriver driver = new FirefoxDriver(profile);

Similarly profile with alert, prompt etc disabled

  profile.setPreference("capability.policy.policynames", "strict") ;
  profile.setPreference("capability.policy.strict.Window.alert", "noAccess") ;
  profile.setPreference("capability.policy.strict.Window.confirm", "noAccess") ;
  profile.setPreference("capability.policy.strict.Window.prompt", "noAccess") ;

Saturday, October 29, 2011

CSS selectors

For selecting a particular column in a table.

XPATH : //table[@class='stb']//tr[2]/td[2]

CSS : css=table.stb tr:nth-child(2)>td:nth-child(1)

XPATH : //input[@name="myName"]

CSS : css=input[name=myName]

 XPATH : //a[@title="Sign In"]

CSS : css=a[title='Sign In']

css=a.addthis_counter>a:nth-child(2)

a class="addthis_counter addthis_bubble_style"  //With space btw css
driver.findElement(By.cssSelector("a[class~='addthis_bubble_style']"));

More information here

Using properties file

There are a number of ways to perform data driven testing. Here i will mention how to use a properties file to get data and use it for testing purpose.   


        InputStream is = this.getClass().getResourceAsStream("/conf/datasuite.properties"); 
        Properties prop = new Properties(); 
        prop.load(is);
        String directory = prop.getProperty("Directory"); 
        String numberOfFiles = prop.getProperty("NumberOfFiles"); 
        String  fileExtension = prop.getProperty("Extension"); 
        is.close();
       
        System.out.println(directory+" "+numberOfFiles+" "+fileExtension);

Contents of datasuite.properties file.

       Directory = C:/prodFiles/
       NumberOfFiles = 25
       Extension = javaworlddfg


One thing to note is that the 'conf' folder is referenced with respect to the class files created.

Friday, October 28, 2011

Check mails using Java

 Instead of automating logging into gmail and checking each mail use the below code to get the contents of required mail 

Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        try {
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("imaps");
            store.connect("imap.gmail.com", "xxxxx@gmail.com", "xxxxxx");
            System.out.println("Store : "+store);

            Folder inbox = store.getFolder("Inbox");
            inbox.open(Folder.READ_ONLY);
            System.out.println("Messge count "+inbox.getUnreadMessageCount());

            Message messages[] = inbox.search(new SubjectTerm("Flags.Flag (JavaMail API documentation)"), inbox.getMessages());
            Date date = new Date();
            System.out.println("Date "+date);

            for (Message message : messages) {
                System.out.println("Seen Flag "+message.isSet(Flags.Flag.SEEN));
                System.out.println("Messge Send Date "+message.getSentDate());

                if(!message.isSet(Flags.Flag.SEEN)){
                    if(date.compareTo(message.getSentDate())<=0){
                        String line;
                        StringBuffer buffer = new StringBuffer();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(message.getInputStream()));
                        while ((line = reader.readLine()) != null) {
                            buffer.append(line);
                        }
                        System.out.println(buffer);
                    }
                }
            }
        } catch (MessagingException e) {
            e.printStackTrace();
            System.exit(2);
        }

Selenium test report as mail attachment

Consider a situation where an user wants to mail the reports after all the automation tests have been done. Maven has provided with a plugin maven-postman-plugin.  It is available in the maven repo.

<plugin>
        <groupId>ch.fortysix</groupId>
        <artifactId>maven-postman-plugin</artifactId>
        <configuration>
            <mailhost>smtp.gmail.com</mailhost>
            <mailport>465</mailport>
            <mailssl>true</mailssl>
            <mailAltConfig>true</mailAltConfig>
            <mailuser>xxxx@gmail.com</mailuser>
            <mailpassword>xxxxxxx</mailpassword>
            <from>your_gmail_emailer_account@gmail.com</from>
            <receivers>
                <receiver>receipient@domain.com</receiver>
            </receivers>

            <subject>Important subject</subject>
            <failonerror>true</failonerror>
            <htmlMessage>
                    <![CDATA[
                    <p>Hi,</p>
                    <p>Check out the attached report.</p>
                    ]]>
            </htmlMessage>
            <fileSets>
                <fileSet>
                    <directory>${basedir}/${tests}</directory>
                    <includes>
                        <include>**/emailable-report.html</include>
                    </includes>
                </fileSet>
            </fileSets>
        </configuration>
    </plugin>

The above configuration will send the emailable-report.html as an attachment to all the recipients. If can be configured to send mail at any phase of maven. The following command is used to send mail after the test phase mvn test postman:send-mail.

Will send the mail after the test phase.

Monday, October 3, 2011

Data providers for selenium

  There are different methods to provide data to selenium tests.

One of these is using the properties file. User can store the data in properties file and use its content for the selenium test

Here is a properties file with some content. Name it as datasuite.properties
     
      Directory = C:/prodFiles/
      NumberOfFiles = 25
      Extension = javaworld


and the corresponding java code to manipulate it


        InputStream is = this.getClass().getResourceAsStream("/conf/datasuite.properties");  
        Properties prop = new Properties();  
        prop.load(is); 
        String directory = prop.getProperty("Directory");  
        String numberOfFiles = prop.getProperty("NumberOfFiles");  
        String  fileExtension = prop.getProperty("Extension");  
        is.close(); 
        
        System.out.println(directory+" "+numberOfFiles+" "+fileExtension);

Below is the folder structure

src/main/java(Source Folder)
>com(Package)
  >DataDrivenTest.java
src/main/resource(Source Folder)
>conf(Package)
 >datasuite.properties

Friday, September 30, 2011

Wait For Elements using webdriver

One of the main issues facing automation scripts is using the proper wait for element functions so not to break 
the test and avoid using sleep statements. The WebDriver provides the class WebDriverWait to handle this scenario. The WebDriverWait constuctor can be passed with the required time to wait for each element. It uses the wait() function to handle individual elements which needs to be checked. The wait() function can either check for a boolean condition or a WebElement is actually present.
 
The below example shows the use of WebDriverWait.
 
import com.google.common.base.Function;
import com.google.common.base.Predicate;


Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) { 
  return new Function<WebDriver, WebElement>() { 
    public WebElement apply(WebDriver driver) { 
      return driver.findElement(locator); 
    }
  };
}

Predicate<WebDriver> presenceOfElementLocated1() { 
  return new Predicate<WebDriver>() { 
            public boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().endsWith("demosd");
    }
  };
}

@Test
public void ajxTest() throws InterruptedException{
selenium.open("http://60.240.240.221/web1");
WebDriverWait wait = new WebDriverWait(driver, /*seconds=*/10);
wait.until(presenceOfElementLocated1());
// selenium.click("//input[@type='button']");
  WebElement clickElement = wait.until(presenceOfElementLocated(By.id("anc_5")));
  clickElement.click();
WebElement element = wait.until(presenceOfElementLocated(By.id("anc_4")));
element.click();
Thread.sleep(4000);
}

Note the useage of Predicate and Function above. User needs to import guava.jar
The Predicate interface will return a boolean condition and Function interface converts WebDriver to WebElement.

Monday, August 22, 2011

Start a maven project for selenium

Create a new Maven project using eclipse. The "artifactId" given for the project will be the name of the project.
Now a a new project is created. It will be having the following two directory structures.

All classes for the project will be under src/main/java  and all unit tests will be under  src/test/java.

For a selenium project there will be no need for both these folder. So we can omit src/test/java and add all tests to src/main/java. The pom file should be updated with the entry  <testSourceDirectory>${basedir}/src/main/java</testSourceDirectory> to point that all tests are in folder structure src/main/java. If only configured like this,  the surefire plugin will execute the tests.

User should specify the class which needs to be executed. It can be specified using "test" option of surefire plugin.
So if all testng tests are written in the file BaseFile.java. Then use this command from cmd mvn test -Dtest=BaseFile.java to run the test. Else the class which needs to be executed can be specified in a suite file and the "suiteXmlFiles" option of surefire  be used.

eg :
      <suiteXmlFiles>
             <suiteXmlFile>sample.xml</suiteXmlFile>
       </suiteXmlFiles>

Use "reportsDirectory"   option of surefire plugin to create a custom folder to store the emailable report.

eg:
     <reportsDirectory>${directory}</reportsDirectory>

Where 'directory' is the argument passed from cmd.

Saturday, August 20, 2011

Run tests using Maven

By default mvn test, tries to execute the unit tests in the folder src/test/java. In order to override that behavior the parameter "testSourceDirectory" can be provided.  If "testSourceDirectory" is specified as src/main/java, then the classes under that directory can be executed using mvn test command.

Tuesday, August 2, 2011

Javascript and WebDriver

It is possible using webdriver to handle javascript. For this it uses interface JavascriptExecutor.

1. Sample code for getting page title

WebDriver driver = new FirefoxDriver();
JavascriptExecutor js =  (JavascriptExecutor)driver;
js.executeScript("return document.title");


2. Executing a javascript function declared.

Sample Page Code

<script>
function showAlert(){
alert('success');
}
</script>


Sample code

WebDriver driver = new FirefoxDriver();
JavascriptExecutor js =  (JavascriptExecutor)driver;
js.executeScript("showAlert()");
On executing above code, the alert will be shown.

Thursday, July 21, 2011

Execute a suite file using Ant

Ant file for running a suite file

For running a suite file provide the ant script with the task "testng". The "testng" task will only be executed if a task definition for testng is specified.

    <property name="xml" value=""/>


    <taskdef name="testng" classname="com.beust.testng.TestNGAntTask" classpathref="classpath"/>


    <target name="run_tests" depends="compile the code">
       <echo message="running tests" />
       <testng classpathref="classpath of jars and other classes used" haltOnfailure="true">
               <xmlfileset file="${xml}" />
       </testng>
    </target>

A xml suite file can be used to specify the test to be run. The parameters to be passed to the test etc.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
 <suite name="Suite1" verbose="1" >
  <test name="Regression1" preserve-order="true">
  <parameter name="env" value="test"/>
  <parameter name="driver" value="ie"/>
    <classes>
   <class name="mytests.First">
    </class>
    </classes>
    </test>
</suite>

Save the above suite as Sample.xml. It contains the class to be executed, the parameters to be passed to the test etc.

Ant Command
   ant -Dxml = Sample.xml

Yaml as config file

One of the best options to specify a config file for java based selenium project is by using a yaml file. In the yaml file the commonly changing config values or values which are used in all tests can be given. There are number of parsers available. I am using snakeyaml.

Jar File

snakeyaml-1.6.jar

Sample yaml file

base: &base                                  # defines anchor label base
  location_username: 'xpath'
  location_password: 'xpath'
  location_submit: 'xpath'
  page: 'http://xxxxxxxxxxx'

test:
  <<: *base                                 #  merges key : value from base anchor
  username: 'testtest'
  password: '123456'
  page: 'http://xxxxxxxxxxx'

prod:
  <<: *base
  username: 'testprod'
  password: '123456'
  page: 'http://xxxxxxxxxxx'

I have saved the above as sample.yaml in my config folder. The use of  "*" and "&" is the inherit the values defined in "base" to "test" and "prod"

Sample java program

import org.yaml.snakeyaml.Yaml;

public class xxx{
 protected Map<String, Map<String,Object>> fullConf;
 protected Map<String,Object> conf;

             Yaml yaml = new Yaml();
             InputStream input = new FileInputStream(new File(System.getProperty("user.dir") + "/config/sample.yaml"));
                this.fullConf = ((Map<String, Map<String,Object>>) yaml.load(input));
                System.out.println("values of fullConf "+fullConf);
                if (fullConf.containsKey("test")) {
                    this.conf = fullConf.get("test");
                    System.out.println("values of test env "+conf);
                    System.out.println("Username "+conf.get("username"));
                    System.out.println("Passowrd "+conf.get("password"));
                    System.out.println("Page "+conf.get("page"));
                    System.out.println("location_username "+fullConf.get("location_username"));
                    System.out.println("location_password "+fullConf.get("location_password"));
                }

}

This program prints the contents of yaml. The variable "fullConf " contains all data of the yaml file as a "key, Map". The variable "conf " will have data of any specific node.


Project home
   src
      test.com
  one/two/three
      config/config.yaml


         InputStream in = this.getClass().getClassLoader().getResourceAsStream("config/config.yaml");
        System.out.println("Hello1 : "+in);

        in = this.getClass().getResourceAsStream("/config/config.yaml");
        System.out.println("Hello3 : "+in);

http://viralpatel.net/blogs/2009/10/loading-java-properties-files.html

Sunday, July 17, 2011

Execute a java class using Ant

Sample Ant Script

<project name="selenium-demo" default="compile" basedir=".">

    <property name="build.dir" value="build" />
    <property name="src.dir" value="src"/>
    <property name="lib.dir" value="lib"/>
    <property name="reports.dir" value="report"/>
    <property name="xml" value="Sample.xml"/>
    <property name="main-class"  value="mytests.Sample"/>
 
    <path id="classpath">
        <pathelement location="${build.dir}/classes"/>
        <fileset dir="${lib.dir}" includes="**/*.jar"/>
    </path>

    <target name="compile">
        <delete dir="${build.dir}"/>
        <mkdir dir="${build.dir}/classes"/>
        <javac srcdir="${src.dir}" destdir="${build.dir}/classes"  executable="javac">
            <classpath refid="classpath"/>
        </javac>
    </target>

    <target name="run_tests" depends="compile">
        <java classname="${main-class}">
             <classpath refid="classpath"/>
        </java>
    </target>

</project>

Save the above file as ant.xml.

Sample Java File


package mytests;

import java.io.IOException;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;


public class Sample{
 
    public static void main(String str[]){
         WebDriver driver = new FirefoxDriver();
         driver.get("http://www.addthis.com");
         try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }
        driver.close();
    }

}

Save the java file as Sample.java and put it into a folder named "src" . Create a new folder and name it "lib" and paste the jar files to be used in the project. For above project only "selenium-server-standalone" will be enough. From the CMD go to the project location and excute the command ant run_tests. Now a new folder called build will be created and it will have all compiled classes.

Thursday, June 30, 2011

RemoteWebDriver

We can run the tests in a remote machine by using remotewebdriver. For this user needs to start a server in the remote machine where he intends to run the test. More details are here    .

Once the server is started execute the below code.

   DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
//        URL remoteAddress = new URL("http://127.0.0.1:4444/wd/hub");
      HttpCommandExecutor executor = new HttpCommandExecutor(new URL("http://Remote address:4444/wd/hub"));
        WebDriver driver = new RemoteWebDriver(executor, desiredCapabilities);
          driver.get("http://www.google.com/");
          driver.quit();

We can see the firefox browser getting invoked in remote machine.

Friday, May 13, 2011

Fucking Railways

I recently had to travel from alleppy to nagercoil. It was the worst experience i ever had. I don't remember the name of that fucking thing. Anyway it started from Alleppey by around 11:50 am. So i thought to have lunch from the train itself. I have heard that the food served by irctc is really tasty. Why i opted for this specific train bcoz was actually a super fast train.So from Alleppey the next stop will be Kayamkulam , followed by Kollam and Trivandrum.

After a half hour journey it reached some where and waited for a crossing. From there starts the worst part. As it was a really hot day i thought of drinking some water and searched the entire train for person supplying water. It was then i realized that the train had no pantry car. We waited for the crossing for about an hour. No food no water, i was really tired. Same condition for the other passengers. Finally the train started again and before another half hour journey halted for another crossing. Luckily this time it was in a railway station. So i thought of buying some water plus food from the  station. But to my surprise that station had only a ticket counter and a small waiting shed. I searched outside of station but no luck. Same condition. Not even a small shop anyway near. I cursed the whole railways and i got into train. Finally out of exhaustion i slept.

Wednesday, May 11, 2011

Select new window using selenium

Selecting a newly opened window using selenium will me a nightmare for all who are trying to automate using selenium.

 Selenium provides selectWindow(windowID) method for handling this situation. In most cases we wont get the window id. So we are forced to go with other parameters like "title= Title of newly opened page" or "name = Name of Window" etc. Most often window.open method will be provided with a window name. If so we can go for selectWindow("name=window_Name").


If both the above cases cannot be applied go for the code snippet given below.

        Selenium selenium;
        String new_Window = this.driver.getWindowHandle();

        Set<String> wh1 = driver.getWindowHandles();
        selenium.click("Link of window");
        Set<String> wh2 = driver.getWindowHandles();
        wh2.removeAll(wh1);
        new_Window = (String) wh2.toArray()[0];
        selenium.selectWindow(new_Window);

Measure it!

Did you ever wonder or check out for a tool which can be used to measure the length/width of page elements in pixels. Yes, Mozilla has got an addon "Measure it" which does the exact purpose. Just install the addon. Now a icon of  "Measure it" will be rendered in the bottom left corner of  status bar. Just click on it and measure the length of any page element.

Measure it is also available as a Chrome pluigin.

Tuesday, April 26, 2011

Tools to check whether links are 404ing

Checking whether all links are working properly in one of the worst nightmares of a tester. Firefox has come with an addon, PINGER to check whether any link is 404ing.

After installing the addon, right click on the page to render the context menu. There will be the option "Ping All links". Click on it to check whether any links are 404ing. Once the test is run, the different links in the page will be colored based on the type of link.

Check the options of pinger addon the see the different options provided.Firefox is claiming that it is much faster than other tools. My own experience also proves the same.

Monday, April 11, 2011

Maven and Selenium

Sample pom for testng based selenium script

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Sample</groupId>
  <artifactId>Sample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
 <build>
  <plugins>
             <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.6</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
  </plugins>
 </build>
  <dependencies>
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>5.8</version>
      <classifier>jdk15</classifier>
    </dependency>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium</artifactId>
      <version>2.0b3</version>
      <type>pom</type>
    </dependency>
  </dependencies>
</project>



Sample  selenium code


package foo;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;


public class MavenBackedSelenium
{

    WebDriver webdriver;
    WebDriverBackedSelenium selenium;


    @BeforeClass
    public void firstTest()
    {
        webdriver = new FirefoxDriver();
        selenium = new WebDriverBackedSelenium(webdriver, "");

    }

    @Test
    public void openGoogle(){
        String page = "http://www.google.com";
        selenium.open(page);
        selenium.type("q", "water");
        selenium.click("search");

    }

    @AfterClass
    public void closeSession(){
        selenium.close();
    }

}

Monday, March 21, 2011

Hudson slave in remote windows machine

Here i am using hudson slave to run an automation script which is written using selenium. As my local machine is not having the required browser, best option before me is to use the hudson slave.

In my local machine the hudson console is opened using http://hudon_jack:8080

Steps to set up remote slave

1.Login in to remote machine.

2.Enter the following url into any browser

http://hudon_jack:8080/

If you are in some vpn or other network use the ip of the local machine.

http://local machine ip:8080/

3.From the "Manage Hudson" page click on "Manage Nodes".

4.Click on "New Node" to create a new slave node. Give a new name for node and save the settings.

5.Enter the details like "# of executers" and "remote FS root". "remote FS root" is the folder where user intends to set up the workspace. Under "Node Properties" user needs to specify the tools used for execution of the project. If maven is used specify the directory location of maven. Similar of the case of java.

There are various ways to start the slave agent. Here i will mention about starting a slave agent using jnlp.

6.Open cmd and execute this
java -jar slave.jar -jnlpUrl http://hudson_jack:8080/computer/slave_node_name/slave-agent.jnlp

Where slave_node_name is the name of the newly created slave node. Now a tcp/ip connection is established between slave and master.
slave.jar should be downloaded or it will be available in the folder assigned for slave.

Steps to run a test in slave

1. From the local machine open the hudson console.

2. Select the newly created slave job and check the radio button "Restrict where this project can be run" and give the name of the slave node just created.

Tuesday, March 15, 2011