selenium introduction by sandeep sharda

25
Selenium Introduction Prepared By: Er. Sandeep Sharda Sr. Member Technical Staff, OSB Oracle

Upload: er-sndp-srda

Post on 12-Apr-2017

81 views

Category:

Documents


3 download

TRANSCRIPT

Selenium Introduction

Prepared By:

Er. Sandeep Sharda

Sr. Member Technical Staff, OSB

Oracle

• Selenium IDE (SIDE)

• Selenium 1.0 (Remote Control)

• Selenium 2.0 (WebDriver)

• Selenium Grid

Selenium - Suite

• It is implemented as a Firefox extension, and allow us to record, edit, and replay the test in Firefox

• We can save tests as HTML, Java, C# or any other format by supported/available code formatter ext.

• Give facility to add assertions to verify results

• Allow to add selenese commands as and when required

• Selenium commands, often called selenese like: clicking button, entering text, marking check box, selection from list etc.

Selenium IDE

• IDE recorded test cases can run only in Firefox

• No Programming logic (like loops, conditional statements) can be applied

• Selenium IDE can only execute scripts created in Selenes

• It is difficult to use Selenium IDE for checking complex test cases involving dynamic contents

Limitations of Selenium IDE

• It is a API and Library of Selenium

• A server, written in Java so can work in cross platforms

• A solution to cross browser testing

• Acts as a proxy to send web requests by launching browser

• Client libraries for many popular languages, to get support we need to configure first

• We need to create the selenium object by giving server and browser details to before running test cases:

DefaultSelenium selenium=new DefaultSelenium(“System address”, ”Port no of selenium”, “Browser to launch”, “url”);

• This selenium object provide us interface to perform keyboard and mouse action on keyboard

Selenium 1.0 (RC)

Selenium 2.0

WebDriver

What’s new

• Selenium 2.0 also called Selenium Web Driver

• Web Drivers are interfaces with language bindings

• WebDrivers are browser specific implementations

• Native keyboard and mouse interactions are supported

• Better support for handling popups and dialogs

• Supports running tests in mobile devices

• No need to start Selenium server unlike Selenium 1.0/RC

• WebDrivers available for language bindings – C#, Java,

Python, Perl, Ruby, PHP

Expr Desc Example

/ Select from the root node html/body/form/div[1]/center/table/tbody/tr/td[1]/input

// Select nodes form the current node //table/tbody/tr/td[1]/input

@ Select attribute //input[@name=‘Login’]

Locating elements in SeleniumThrough the HTML.. by

1. Tag name – a, input, select, span, div2. Attribute – Name, Value, Id, type3. Text - <title>Title of the document</title>

By Xpath

Example Desc

//input[@id='firstname’] Select element with tag input and id=firstname

//input[contains(text(),’Gmo ')] Select element with text containing Gmo

//input[starts-with(text(),’Enter’)] Select element with text starting with Enter

//input[contains(@value, “GMO")] identify element containing ‘GMO’ in value attribute

//input[contains(@id, "searchInput")and contains(@text,“google")]

look at two attributes in input node

//input[starts-with(@type, “s")] find input node with attribute type and its value is starting with 's'

//*[@accesskey=‘alpha'] Can use wild cards

//input[text()='First Name:'] Select element with tag input and text=firstname

//td/a/strong[contains(text(),'Socks')] Find all elements containing ‘Socks’

Examples: Locating elements by Xpath

More: http://www.w3schools.com/xpath/xpath_syntax.asp

Selector Sample Desc

.Class .Button Selects all elements with class=“Button"

#Id #myForm Selects the element with id="myForm"

Element Select Selects all <select> elements

element, element Select , option elects all <select> and all <option> elements

element element Select option Selects all <select> elements inside <option> elements

[attribute=value] [size='22'] Selects all elements with size=“22”

Element:first-child Select:first-child Select every <Select> element that is the firstchild of its parent

Element:nth-child(n) Select:nth-child(2) Selects every <Select> element that is the second child of its parent

Element:last-child Select:last-child Selects every <Select> element that is the lastchild of its parent

Element:checked input:checked

Examples: Locating elements by Css Selector

More: http://www.w3schools.com/cssref/css_selectors.asp

• Firefox

ff=new FirefoxDriver();

• IE

System.setProperty("webdriver.ie.driver", “D:\\Selenium Projects\\BrowserDrivers\\IEDriverServer.exe");

ie=new InternetExplorerDriver();

//ensure protected mode is turned off/on for all zones under security tab

//set zoom level to 100%

• Chrome

System.setProperty("webdriver.chrome.driver", "D:\\Selenium

Projects\\BrowserDrivers\\chromedriver.exe");

chrome=new ChromeDriver();

//ensure auto update is turned off

Working with Browsers

Method Desc.get(String url) Navigate to url

.navigate().to(String url) Navigate to url

.navigate().back() Navigate to the previous page in the cache

.navigate().forward() Navigate to the next page in the cache

.getTitle() Page title

.close() Close the current instance of the browser

.quit() Close all instances of the browser

.findElement(By.xpath(xp)) Locate element by xpath

.findElement(By.name(name)) Locate element by name attribute

.findElement(By.id(id)) Locate element by id attribute

.findElement(By.className(cls)) Locate element by class

.findElement(By.cssSelector(selector)) Locate element by css selector

.findElements(By.tagName(tagname)) Locate all elements having tag tagname

Commonly used WebDriver methods

Method Desc

element.getText() Retrieves the text of the given element

element.clear() Clears the value from input element

element.sendKeys(chars) Input value into element

.manage().window().maximize(); Maximize window

.manage().timeouts().pageLoadTimeout(10,TimeUnit.SECONDS);

Page load time

element.isDisplayed() Check if element is displayed – returns true/false

element.isEnabled() Check if element is enabled– returns true/false

Commonly used WebDriver methods

• Input field

WebElement field = driver.findElement(By.name("QTY_TENTS"));

field.clear(); field.sendKeys(value);

• Drop Down box

Select selection = new Select(browserDriver.findElement(By.xpath("//select[@name='CardType']“));

List<WebElement> options = selection.getOptions(); elementSize=options.size();

selection.selectByIndex(1); / selection.selectByVisibleText(“visa”);

• Radio

driver.findElement(By.xpath("//input[@value='oneway']")).click();

• Check box

isChecked=driver.findElement(By.name("shipSameAsBill")).isSelected(); driver.findElement(By.name("shipSameAsBill")).click();

• Handle popups

driver.switchTo().alert().accept(); driver.switchTo().alert().getText();

WebDriver Snippets

• Auto-suggest Drop down (google.co.in)

driver.findElement(By.cssSelector(“. gbqfqw").sendKeys(value); driver.findElement(By.cssSelector(“#gbqfqw").sendKeys(Keys.DOWN); driver.findElement(By.cssSelector(“div#gbqfqw”).sendKeys(Keys.UP);

• List out the options in the selection box

WebElement select = driver.findElement(By.name('CardType'));

List <WebElement> options = select.findElements(By.tagName("option"));

for (WebElement option : options) {

String name = option.getAttribute("value"); System.out.println("value:"+name); }

• Switch to frame

driver.switchTo().frame( "frameName" ); driver.switchTo().defaultContent();

• Handling Windows

Set<String> handles = driver.getWindowHandles(); nextWindowHandle=handles().iterator().next(); driver.switchTo().window(nextWindowHandle);

WebDriver Snippets

• Capture screen shot

File scrFile = ((TakesScreenshot) browserDriver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(scrFile, new File(“c:\\.filename.jpg"));

• Wait for an element – Explicit wait

WebDriverWait wait = new WebDriverWait(browserDriver, 10); //seconds

WebElement ele = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath ("//a[contains(text(),'Java training')]")));

• Implicit Wait – applies to all elements

browserDriver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);

• Simulate mouse actions

Actions mouseAction= new Actions(driver);

WebElement menu = wd.findElement(By.xpath("//a/span[text()= 'Books & Media']"));

mouseAction.moveToElement(menu).perform();

WebDriver Snippets

WebDriver Snippets

• Execute Java Script

((JavascriptExecutor) driver).executeScript(<any valid javascript>);

• Co-ordinates of WebElement

WebElement techEval=driver.findElement(By.xpath("//a[text()='Technical topics']"));

Method 1

Locatable hoverItem = (Locatable) techEval;

Coordinates cor= hoverItem.getCoordinates(); System.out.println(cor);

Method 2

System.out.println(techEval.getLocation().getX() +”,“ +techEval.getLocation().getY());

Firefox profile

• A profile in Firefox is a collection of bookmarks, browser settings, extensions, passwords, and history; all of personal settings.

• Why use profile when executing selenium tests?

• Webdriver always creates an anonymous profile with default settings,

so sometimes tests may behave differently at times

• Tests may require some proxy settings which doesnot come with default settings which webdriver creates.

• SSL certificates or some browser plugins may be required to successfully execute the tests.

• Procedure:

• Create a new profile and use in the test

• Create firefox profile through script

• Create a new profile and use in the test

• From windows start/run : firefox.exe -P

• Create a new profile. Select the profile, start firefox, apply settings.

• In selenium script, code the following and examine new firefox browser is opened with applied settings.

ProfilesIni pi = new ProfilesIni(); FirefoxProfile fp = pi.getProfile("SelTests");

browserDriver=new FirefoxDriver(fp);

• Create firefox profile through script with proxy settings

FirefoxProfile fp = new FirefoxProfile(); fp.setEnableNativeEvents(true); fp.setPreference("network.proxy.type", 1); // manual proxy setting

fp.setPreference("network.proxy.http", "localhost"); // specify ip (or localhost) fp.setPreference("network.proxy.http_port", 8080); // specify port

browserDriver=new FirefoxDriver(fp);

Get these properties by typing “about:config” in Firefox browser

Firefox profile

Exceptions Desc

ElementNotVisibleException Thrown when although an element is present on the DOM, it is not visible, and so is not able to be interacted with.

NoAlertPresentException Thrown when switching to alert which is not present.

NoSuchElementException Thrown when element could not be found.

TimeoutException Thrown when a command does not complete in enough time.

UnexpectedAlertPresentException

Thrown when an unexpected alert is appeared.

StaleElementReferenceException Thrown when a reference to an element no longer appears on the DOM

ElementNotFoundException page not loading fast enough or element not yet loaded

Selenium Exceptions

Grid 2.0

• Run tests in parallel

• Run tests in multiple machines – Physical/Virtual

• Consists of hub and one or more nodes

• Hub

• provides the configurations or capabilities to the Selenium WebDriver tests

• receive the entire test request and distribute it to the right nodes

• Nodes

• connects to hub for parallel execution

Grid Configuration

• Hub m/c

Standalone jar run as hub

Listens to configured nodes on port 4444 (default and can bechanged)

java –jar selenium-server-standalone-2.xx.x.jar –role hub [-port xxxx]

• Nodes m/c

Standalone jar run as node with browser, OS configuration with any open port

• Execute

Run the test code from eclipse/IntelliJ or supported IDE

Node Configuration

• IE

java -jar selenium-server-standalone-2.xx.x.jar -role webdriver -port 5555

-Dwebdriver.ie.driver=C:\BrowserDrivers\IEDriverServer.exe

-browser “browserName=iexplore,version=8,maxinstance=1,platform=WINDOWS"

-hub http://hub_IP_or_Name:4444/grid/register

• Chrome

java -jar selenium-server-standalone-2.xx.x.jar -role webdriver -port 5555

-Dwebdriver.chrome.driver=C:\BrowserDrivers\chromedriver.exe

-browser "browserName=chrome,version=28,maxinstance=1,platform=WINDOWS"

-hub http://hub_IP_or_Name:4444/grid/register

• With Firefox

java -jar selenium-server-standalone-2.xx.x.jar -role webdriver –port 5555

-browser "browserName=firefox, version=22,maxinstance=2,platform=ANY"

-hub http://hub_IP_or_Name:4444/grid/register

• From IntelliJ

• Add TestNg jar file to libraries

• Create TestNg test class and create test code methods with relevant TestNg annotations

• Run the test code using TestNg test

• Using Testng.xml

• Create testng.xml – manual

• Create testng.xml - Eclipse-TestNg needs to configured in eclipse

• Run the xml file

‒ From command line

‒ From Ant – download/configure Ant from within eclipse

‒ From Maven – download/configure Maven from within eclipse

Grid - Test Execution via TestNG

Thank you