Monday, 7 May 2012

Example - Creating and running python (selenium2) script

Aim: How to start with the python scripts?

Difficulty Level: Medium

Pre-requisites:
  • Download the python from URL https://www.python.org/getit/ and install as well
  • Set the path of python into the System environment variable
  • Download the Autopy from URL http://pypi.python.org/pypi/autopy and install it as well
Steps to implementation:
  • Run the command for install the selenium easy_installSelenium
  • Record the script using selenium IDE
  • Export the recorded script into the python 2(web driver)
  • Save the script in .py extension
  • launch the command prompt
  • Go to the path where script is saved
  • Run the command python filename.py
Recorded script:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re

class Srcipt(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "http://foundation.time2test.co.uk/"
        self.verificationErrors = []
    
    def test_srcipt(self):
        driver = self.driver
        driver.get("http://foundation.time2test.co.uk/")
        driver.find_element_by_link_text("Log in").click()
        driver.find_element_by_id("user_login").clear()
        driver.find_element_by_id("user_login").send_keys("admin")
        driver.find_element_by_id("user_pass").clear()
        driver.find_element_by_id("user_pass").send_keys("time4test")
        driver.find_element_by_id("wp-submit").click()
        driver.find_element_by_css_selector("#menu-posts > div.wp-submenu > ul > li.wp-first-item > a.wp-first-item").click()
        driver.find_element_by_css_selector("a.button.add-new-h2").click()
        driver.find_element_by_id("title").clear()
        driver.find_element_by_id("title").send_keys("This is new post")
        driver.find_element_by_id("publish").click()
        driver.find_element_by_id("title").clear()
        driver.find_element_by_id("title").send_keys("Edit the post")
        driver.find_element_by_id("publish").click()
        driver.find_element_by_xpath("//div[@id='wphead-info']/div[@id='user_info']/p/a[2]").click()
    
    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True
    
    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()


Helpful Video:

Python2Video by time2test

Wednesday, 2 May 2012

Example - Running selenium2 scripts in cucumber framework

Aim: How to run Selenium 2 scripts in cucumber?

Difficulty Level: High

Tools used:
  • Ant
  • JDK
  • Cucumber API
  • Selenium2 API
Pre-requisites in running the scripts:
  • ant and jdk should be configured
  • Download the project name "Selenium2Cucumber" from the link
Steps:
  • Extract the downloaded project into the C drive
  • Open CMD
  • Go to the project  path using cd.. command
  • Run the command ant runcukes
  • See your script runs into the Firefox browser
Used Commands:
  • cd\
  • cd Selenium2Cucumber
  • ant runcukes
Helpful Video:


Selenium2Cucumber by time2test

Friday, 27 April 2012

Example - Running selenium2 scripts from the Hudson dashboard

Aim: Hudson with selenium2

Difficulty Level: High

Pr-requisites:
  • JDK and Ant should be configured
  • Hudson should be installed
Steps:
  • Download the project from the link
  • You will get a war file, place it in C drive
  • Open command prompt and go to C drive
  • Run the command "java -jar hudson.war". (By default it will run on port 8080, if this port is busy then run command on other port i.e. "java -jar hudson.war --httpPort=8082")
  • Launch the  firefox and open the hudson dashboard using URL "http://localhost:8080"
  • Create a new job
  • Enter the job name
  • Select the Build Type ANT into the dropdown
  • Enter the target name from build.xml file into Targets field
  • Click on Advanced button
  • Enter the path of build.xml file into the Build of the field
  • Click Save button
  • Start selenium server.
  • Click Build Now link at hudson interface to build the project
  • Script runs and launches the browser
  • Open the build link
  • See the result from console output

Helpful Video:

sel2hudson by time2test


Thursday, 26 April 2012

iPhone using Selenium2 Webdriver API on MAC OS/ XCode environment

Aim: How to test a web application into an iPhone using Selenium2 Webdriver API on MAC OS/ XCode environment.

Difficulty Level: Hard


Pre-Requisites:
  • Selenium2 API responsible for iphone Webdriver
  • Installed xcode on MAC machine
  • Launching selenium/iphone/iWebDriver.xcodeproj in installed xcode
Steps to implement:
  • Go to the MAC PC
  • Download xcode4.2 and install
  • Launch the xcode once it is installed, popup opens
  • Select iWebdriver project option
  • Do Build and Run
  • Simulator starts
  • Download the Selenium 2 API using URL more specific to iphone testing:http://code.google.com/p/selenium/downloads/list
  • Create a selenium project directory using testNG, ant integrated
  • Open command terminal
  • Run the target using ant in same terminal
  • Check your script would run into the iphone simulator
  • Find the report into the test-output folder
Video Captures below points:
  • Open Xcode
  • Launching iphone simulator using iWebdriver
  • Running ant target defined into the build.xml file into the selenium2 project directory
  • Running of script into the iphone simulator
  • generated report from the test-output folder

Helpful Video:


IphoneVideo by time2test

Wednesday, 21 March 2012

Example:Using CSSLocator with Selenium2 Webdriver API

Aim:To use CSS locators in place of Element locator and run with using Selenium 2 webdriver API.
Difficulty Level:Medium
Prerequisites:
  • Firefox and Selenium IDE installed
  • Firebug installed in Firefox.
  • Eclipse IDE
  • Selenium 2 API
Commands used in example:
  • Click
  • ClickAndWait
  • type
Example Steps:
  1. Open any already created script into Selenium IDE.
  2. Follow the video.
Expanded Steps:
  1. Open up Selenium IDE
  2. open up the sleenium script
  3. Run the selenium script in the IDE
  4. Notice that the selenium script ran successfully.
  5. Now aim is to replace the element locators with CSS Locators.
  6. Goto Selenium IDE and click on the third command "type, id=user_login", admin
  7. click on the input field next to Target and then press Find button
  8. Notice the button will blink yellow for two seconds
  9. now right click on the admin input field and click on "inspect element"
  10. the id=user_login >> becomes >> css=input#user_login
  11. copy the text and place it back into the selenium IDE script
  12. notice that teh selenium IDE script shows green to indiaccate that the css selector works
  13. Repeat this for the id=user_pass
  14. Repeat this for id=wp-submit >> becomes >> css=input[class='button-primary']
  15. Now Run the modified Selenium IDE script with the css selectors.
  16. Save the modified selenium IDE script 
  17. Now we want to run the modified script using Selenium Webdriver 2 api
  18. Click on "Export Test Case As" - > JUNIT 4 (Webdriver) and save/export
  19. now close down Selenium IDE
  20. Open up the saved exported java file in notepad ++
  21. Now Launch Eclipse IDE
  22. click on New-> Java Project and give name "CSSLocatorProject" and click Next and Finish
  23. Right click on SRC and select "package"
  24. give name "com.example.tests" and click Finish
  25. Right click package and create new class
  26. give name: CSSLocator and finish
  27. Copy the exported java file into this class file
  28. Now add the build path for Selenium Jar
  29. Right Click the project and select Build Path->configure build path
  30. click on Add External jars and  select the selenium jar file that you download from seleniumHQ ( selenium-server-standalone-2.24.1.jar)
  31. Notice the red errors disappear to indicate that the api has been loaded
  32. Notice that the code shows cssSelectors as a way to identify elements on the page
  33. Now Run the project - right click the class and select Run As Junit test
  34. the green indicates that the css selector script has successfully rin on Webdriver 2

Script:Save the file as Script.html


<span style="font-weight: bold;"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://foundation.time2test.co.uk/" />
<title>Script</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">Script</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>http://foundation.time2test.co.uk/</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Log in</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=user_login</td>
<td>admin</td>
</tr>
<tr>
<td>type</td>
<td>id=user_pass</td>
<td>time4test</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>id=wp-submit</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Posts</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Add New</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=title</td>
<td>MyFirstPost</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>id=publish</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Log Out</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
</span>


Save the file as CSSLocator.html
<span style="font-weight: bold;"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://foundation.time2test.co.uk/" />
<title>Script</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">Script</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>http://foundation.time2test.co.uk/</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Log in</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>css=input#user_login</td>
<td>admin</td>
</tr>
<tr>
<td>type</td>
<td>css=input[id='user_pass'][type='password']</td>
<td>time4test</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>css=input[class='button-primary']</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Posts</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Add New</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=title</td>
<td>MyFirstPost</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>id=publish</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>css=[title='Log Out']</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
</span>

Save the file as CSSLocator.java

package com.example.tests;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class CSSLocator {
private WebDriver driver;
private String baseUrl="";
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void testCSSLocator() throws Exception {
driver.get("http://foundation.time2test.co.uk/");
driver.findElement(By.linkText("Log in")).click();
driver.findElement(By.cssSelector("input#user_login")).clear();
driver.findElement(By.cssSelector("input#user_login")).sendKeys("admin");
driver.findElement(By.cssSelector("input[id='user_pass'][type='password']")).clear();
driver.findElement(By.cssSelector("input[id='user_pass'][type='password']")).sendKeys("time4test");
driver.findElement(By.cssSelector("input[class='button-primary']")).click();
driver.findElement(By.linkText("Posts")).click();
driver.findElement(By.linkText("Add New")).click();
driver.findElement(By.id("title")).clear();
driver.findElement(By.id("title")).sendKeys("MyFirstPost");
driver.findElement(By.id("publish")).click();
driver.findElement(By.cssSelector("[title='Log Out']")).click();
}

@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
 fail(verificationErrorString);
}
}

private boolean isElementPresent(By by) {
try {
 driver.findElement(by);
 return true;
} catch (NoSuchElementException e) {
 return false;
}
}
}
Helpful Video:

Tuesday, 20 March 2012

Example: Integration of Selenium 2 with Maven

Aim:

Difficult Level: Medium

Prerequisits:
Steps to Implementation:
  1. Create the project directory "MavenProject".
  2. Create subdirectory "src".
  3. Create two subdirectory "testng" and "script" into "src" directory.
  4. Save the all below files to corresponding directory.
  5. Run the script use command: mvn install
Scripts:
  • Create file "pom.xml" under "MavenProject" directory.

<?xml version="1.0" encoding="UTF-8"?>
<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>

<groupId>org.time2test</groupId>
<artifactId>Time2Text</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<name>Selenium Functional Tests</name>
<url>http://www.time2test.com/</url>


 <repositories>
<repository>
<id>openqa</id>
<name>OpenQA Repository</name>
<url>http://nexus.openqa.org/content/repositories/releases/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>

<dependencies>

<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.4</version>        
</dependency>

 <dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.6.0</version>
</dependency>

   <dependency>
     <groupId>org.openqa.selenium.server</groupId>
     <artifactId>selenium-server</artifactId>
     <version>0.9.0</version>
   </dependency>

   <dependency>
     <groupId>org.seleniumhq.selenium.client-drivers</groupId>
     <artifactId>selenium-java-client-driver</artifactId>
     <version>1.0.2</version>
     <scope>test</scope>
   </dependency>

   <dependency>
     <groupId>org.testng</groupId>
     <artifactId>testng</artifactId>
     <version>5.7</version>
     <scope>test</scope>
     <classifier>jdk15</classifier>
   </dependency>
 </dependencies>

  <build>
     <testSourceDirectory>src/script</testSourceDirectory>
     <plugins>
       <!-- Compiler Plugin (support for JDK.5)-->
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>2.3.2</version>
    <executions>
           <execution>
             <goals>
               <goal>testCompile</goal>
             </goals>
           </execution>
         </executions>
         <configuration>
           <source>1.5</source>
           <target>1.5</target>
         </configuration>
       </plugin>

       <!-- Selenium Maven Plugin -->
       <plugin>
           <groupId>org.codehaus.mojo</groupId>
           <artifactId>selenium-maven-plugin</artifactId>
           <version>1.1</version>
           <configuration>
               <port>1247</port>
               <trustAllSSLCertificates>true</trustAllSSLCertificates>

           </configuration>
           <executions>
               <execution>
                   <phase>pre-integration-test</phase>
                   <goals>
                       <goal>start-server</goal>
                   </goals>
                   <configuration>
                       <background>true</background>
                   </configuration>
               </execution>
           </executions>
       </plugin>


       <!-- Surefire plugin -->
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12</version>
         <executions>
           <execution>
             <phase>integration-test</phase>
             <goals>
               <goal>test</goal>
             </goals>
             <configuration>
               <skip>false</skip>
             </configuration>
           </execution>
         </executions>
         <configuration>
           <suiteXmlFiles>
             <suiteXmlFile>
               src/testng/testng.xml
             </suiteXmlFile>
           </suiteXmlFiles> 
           </configuration>
       </plugin>        
  
  </plugins>
</build>

</project>
  • Create file "testng.xml" file under "testng" directory.

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="SeleniumWebdriverTests" parallel="tests">
<test name="WebdriverScriptWithMaven">
<classes>
<class name="com.example.tests.MavenExample" /> 
</classes>
</test>
</suite>
  • Create "MavenExample.java" file under "src/com/example/tests" directory.


package com.example.tests;

import com.thoughtworks.selenium.*;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import java.util.regex.Pattern;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.junit.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MavenExample  {
private WebDriver driver;
private String baseUrl="http://foundation.time2test.co.uk/wp-login.php";
private StringBuffer verificationErrors = new StringBuffer();
@BeforeMethod
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void test() throws Exception {
driver.get(baseUrl);
driver.findElement(By.id("user_login")).clear();
driver.findElement(By.id("user_login")).sendKeys("admin");
driver.findElement(By.id("user_pass")).clear();
driver.findElement(By.id("user_pass")).sendKeys("time4test");
driver.findElement(By.id("wp-submit")).click();

// Creating a new user in Word press
driver.findElement(By.linkText("Users")).click();
driver.findElement(By.cssSelector("a.button.add-new-h2")).click();
driver.findElement(By.id("user_login")).clear();
int a=new Random().nextInt(123456789);
String User_name= "testuser"+a;
driver.findElement(By.id("user_login")).sendKeys(User_name);
driver.findElement(By.id("email")).clear();
String Email_address= "testemail"+a+"@gmail.com";
driver.findElement(By.id("email")).sendKeys(Email_address);
driver.findElement(By.id("first_name")).clear();
driver.findElement(By.id("first_name")).sendKeys("Word");
driver.findElement(By.id("last_name")).clear();
driver.findElement(By.id("last_name")).sendKeys("Press");
driver.findElement(By.id("url")).clear();
driver.findElement(By.id("url")).sendKeys("http://www.test.com");
driver.findElement(By.id("pass1")).clear();
driver.findElement(By.id("pass1")).sendKeys("123-asd");
driver.findElement(By.id("pass2")).clear();
driver.findElement(By.id("pass2")).sendKeys("123-asd");
driver.findElement(By.id("addusersub")).click();
driver.findElement(By.cssSelector("input.button")).click();

}

@AfterMethod
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}

private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}
Helpful Video: