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.