Beruflich Dokumente
Kultur Dokumente
DZone
brought to you by...
#125
Get More Refcardz! Visit refcardz.com
Selenium 2.0:
CONTENTS INCLUDE:
n
What is Selenium 2.0?
n
Architecture
n
Installation
n
Driver Implementations Using the Webdriver API to Create Robust User Acceptance Tests
n
Page Interaction Model
n
Mobile Device Support and more... By Matt Stine
ARCHITECTURE
Selenium 2.0
or
pip install selenium
HtmlUnit
The HtmlUnit driver is the fastest and most lightweight of the
C# group. It is the only pure Java implementation, so it is the
Download selenium-dotnet-2.0a6.zip and add references to only solution that will run anywhere the JVM is available.
WebDriver.Common.dll and WebDriver.Firefox.dll (or your Because it utilizes HtmlUnit to interact with your application
browser of choice) to your Visual Studio project. instead of driving an actual browser, it carries along the
associated baggage:
DRIVER IMPLEMENTATIONS •Y
ou cannot visually inspect what’s going on during
your test.
There are currently four official driver implementations for •H
tmlUnit uses Rhino as its JavaScript+DOM
desktop browsers: implementation. No major browser does this, and it is
Firefox disabled by default.
The Firefox driver is the most mature of the browser-based • If you do enable JavaScript, the HtmlUnit Driver will
drivers. emulate the behavior of Internet Explorer.
selenium.open(“http://downforeveryoneorjustme.com/”);
From Python: selenium.type(“domain_input”, “google.com”);
selenium.click(“//div[@id=’container’]/form/a”);
from selenium.ie.webdriver import WebDriver
driver = WebDriver() assertTrue(selenium.isTextPresent(“It’s just you”));
On the downside, you may notice some inconsistencies in greatly simplify interaction with select elements and their
behavior since the entire Selenium API is not implemented (eg., association options:
keyPressNative is unsupported) and Selenium Core is emulated.
Method Purpose
You may also experience slower performance in some cases.
selectByIndex(int index)/ Selects/deselects the option at the given index.
deselectByIndex(int index)
PAGE INTERACTION MODEL
selectByValue(String value)/ Selects/deselects the option(s) that has a value matching
deselectByValue(String value) the argument.
After navigating to a page… selectByVisibleText(String text)/ Selects/deselects the option(s) that displays text matching
deselectByVisibleTest(String text) the argument.
driver.get(“http://www.google.com”)
deselectAll() Deselects all options.
…WebDriver offers a plethora of means for interacting with getAllSelectedOptions() Returns a List<WebElement> of all selected options.
the elements on that page via its findElement methods. getFirstSelectedOption() Returns a WebElement representing the first selected
These methods accept an argument of type By, which defines option.
several static methods implementing different means of getOptions() Returns a List<WebElement> of all options.
element location: isMultiple() Returns true if this is a multi-select list; false otherwise.
XPATH By.xpath(“//input[@id=’myElementId’]”)
If the element does not represent a select element, this
Class name By.className(“even-table-row”)
constructor will throw an UnexpectedTagNameException.
CSS Selector By.cssSelector(“h1[title]”)
Method Purpose
RenderedWebElement Methods
clear() Clears all of the contents if the element is a text entity.
Method Purpose
click() Simulates a mouse click on the element.
dragAndDropBy(int moveRightBy, Drags and drops the element moveRightBy pixels to
getAttribute(String name) Returns the value associated with the provided attribute name int moveDownBy) the right and moveDownBy pixels down. Pass negative
(if present) or null (if not present). arguments to move left and up.
getTagName() Returns the tag name for this element. dragAndDropOn(RenderedWeb Drags and drops the element on the supplied element.
getText() Returns the visible text contained within this element (including Element element)
subelements) if not hidden via CSS. getLocation() Returns a java.awt.Point representing the top left-hand
getValue() Gets the value of the element’s “value” attribute. corner of the element.
isEnabled() Returns true for input elements that are currently enabled; getSize() Returns a java.awt.Dimension representing the width and
otherwise false. height of the element.
isSelected() Returns true if the element (radio buttons, options within a getValueOfCssProperty(String Returns the value of the provided property.
select, and checkboxes) is currently selected; otherwise false. propertyName)
sendKeys(CharSequence… Simulates typing into an element. hover() Simulates a mouse hover event over the element.
keysToSend) isDisplayed() Returns true if the element is currently displayed;
setSelected() Select an element (radio buttons, options within a select, and otherwise false.
checkboxes).
submit() Submits the same block if the element if the element is a form
PAGE OBJECT PATTERN
(or contained within a form). Blocks until new page is loaded.
findElements(By by) Finds all elements located by the provided method. Consider the Google home page. The user is able to
enter search terms and perform two possible actions: to
WebDriver provides a support class named Select to conduct the search or to automatically navigate to the
top hit (“I’m Feeling Lucky). We could model this with the a WebDriver instance or when the default no-argument
following Page Object (Java): constructor is present.
public class GoogleHomePage { AnotherPageObject page = AnotherPageObject(“testing”, 1, 2, 3, driver);
private final WebDriver driver; PageFactory.initElements(driver, page);
the system property “firefox.browser.profile” to the public UnknownTopHitPage imFeelingLucky(String searchTerms) {
searchBox.sendKeys(searchTerms);
name of your custom profile. imFeelingLuckyButton.submit();
return new UnknownTopHitPage(driver);
To learn more about the Page Object pattern, visit: }
}
http://code.google.com/p/selenium/wiki/PageObjects
WebDriver provides excellent support for implementing Page The @FindBy annotation supports the same location methods
Object’s via its PageFactory. The PageFactory supports a supported by the programmatic API (except for CSS selectors):
“convention over configuration” approach to the Page Object @FindBy Annotation Location Methods
pattern. By utilizing its initElements method, the driver element Locator Examples
location code can be removed from the previous Page Object: id attribute @FindBy(how = How.ID, using = “myElementId”)
@FindBy(id = “myElementId)
public class GoogleHomePage {
private final WebDriver driver; name attribute @FindBy(how = How.NAME, using = “myElementName”)
private WebElement q; @FindBy(name = “myElementName”)
private WebElement btnG;
private WebElement btnI;
id or name @FindBy(how = How.ID_OR_NAME, using = “myElement”)
attribute
public GoogleHomePage(WebDriver driver) {
this.driver = driver; XPATH @FindBy(how = How.XPATH, using = “//input[@id=’myElementId’]”)
@FindBy(xpath = “//input[@id=’myElementId’]”)
//Check that we’re actually on the Google Home Page.
if (!”Google”.equals(driver.getTitle())) { Class name @FindBy(how = How.CLASS_NAME, using=”even-table-row”)
throw new IllegalStateException(“This isn’t Google’s Home Page!”); @FindBy(className = “even-table-row”)
}
} Link Text @FindBy(how = How.LINK_TEXT, using=”Click Me!”)
@FindBy(linkText = “Click Me!”)
public GoogleResultsPage search(String searchTerms) {
q.sendKeys(searchTerms); Partial Link Text @FindBy(how = How.PARTIAL_LINK_TEXT, using=”ck M”)
btnG.submit(); @FindBy(partialLinkText = “ck M”)
return new GoogleResultsPage(driver); Tag Name @FindBy(how = How.TAG_NAME, using=”td”)
}
@FindBy(tagName = “td”)
public UnknownTopHitPage imFeelingLucky(String searchTerms) {
q.sendKeys(searchTerms);
btnI.submit(); XPATH SUPPORT
return new UnknownTopHitPage(driver);
}
} WebDriver makes every effort to use a browser’s native XPath
capabilities wherever possible. For those browsers that do
A fully initialized version of this object can then be created and
not have native XPath support, WebDriver provides its own
used as in the following code snippet:
implementation. If you’re not familiar with the behavior of the
WebDriver driver = new HtmlUnitDriver(); //or your choice of driver various engines, this can lead to surprising results.
driver.get(“http://www.google.com”);
GoogleHomePage page = PageFactory.initElements(driver, GoogleHomePage.
class); Driver Tag/Attribute Attribute Values Native XPath
page.search(“WebDriver”); Names Support
Consider the following example: The constructor for RemoteWebDriver accepts two arguments:
<input type=”text” name=”pizza”/> 1) The URL for the remote server instance.
<INPUT type=”text” name=”pie”/>
2)A Capabilities object, which specifies the target
The following behavior will result: platform and/or browser. DesiredCapabilities provides
XPath Number of Matches static factory methods for the commonly used choices
Expression (e.g., DesiredCapabilities.firefox()).
HtmlUnitDriver InternetExplorerDriver FirefoxDriver
//input 1 2 1
MOBILE DEVICE SUPPORT
//INPUT 0 2 0
import java.net.URL;
package com.deepsouthsoftware.seworkshop;
import org.openqa.selenium.*;
import org.junit.*;
import java.net.URL;
import org.openqa.selenium.remote.*;
import org.openqa.selenium.*;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.remote.*;
public class IphoneWebDriverTest {
import static org.junit.Assert.*;
private WebDriver driver;
public class RemoteWebDriverTest {
@Before
private WebDriver driver;
public void setUp() throws Exception {
driver = new RemoteWebDriver(new URL(“http://localhost:3001/hub”),
@Before
DesiredCapabilities.iphone());
public void setUp() throws Exception {
}
driver = new RemoteWebDriver(new URL(“http://127.0.0.1:4444/wd/hub”),
DesiredCapabilities.firefox());
@Test
}
public void testCheese() throws Exception {
driver.get(“http://www.google.com”);
@Test
WebElement element = driver.findElement(By.name(“q”));
public void testCheese() throws Exception {
element.sendKeys(“Cheese!”);
driver.get(“http://www.google.com”);
element.submit();
WebElement element = driver.findElement(By.name(“q”));
assertEquals(“Cheese! - Google Search”, driver.getTitle());
element.sendKeys(“Cheese!”);
}
Thread.sleep(1000); //Deal with Google Instant
element = driver.findElement(By.name(“btnG”));
@After
element.click();
public void tearDown() throws Exception {
Thread.sleep(1000); //Deal with Google Instant
driver.quit();
assertEquals(“cheese! - Google Search”, driver.getTitle());
}
}
}
@After
public void tearDown() throws Exception {
driver.quit();
}
}
import java.net.URL;
import org.openqa.selenium.*;
import org.junit.*;
import org.openqa.selenium.android.AndroidDriver;
#82
CONTENTS INCLUDE:
■
■
About Cloud Computing
Usage Scenarios Getting Started with
Aldon Cloud#64Computing
■
Underlying Concepts
Cost
by...
■
Upcoming Refcardz
youTechnologies ®
■
Data
t toTier
brough Comply.
borate.
Platform Management and more...
■
Chan
ge. Colla By Daniel Rubio
on:
dz. com
grati s
also minimizes the need to make design changes to support
CON
ABOUT CLOUD COMPUTING one time events. TEN TS
INC
s Inte -Patternvall
■
HTML LUD E:
Basics
Automated growthHTM
ref car
Windows Phone 7
Usef
ContiPatterns an
■
However, the demands and technology used on such servers faced by web applications.Structure Tools
Core
Key ■
Structur Elem
E: has changed substantially in recent years, especially with al Elem ents
INC LUD gration the entrance of service providers like Amazon, Google and Large scale growth scenarios involvingents
specialized
NTS and mor equipment
rdz !
HTML
CO NTE Microsoft. es e... away by
(e.g. load balancers and clusters) are all but abstracted
Continu at Every e chang
About ns to isolat
relying on a cloud computing platform’s technology.
Software i-patter
space
CSS3
■
n
Re fca
e Work
Build
riptio
and Ant These companies Desc have a Privat
are in long deployed trol repos
itory
webmana applications
ge HTM
L BAS
■
Build
re
Repo
This Refcard active
will introduce are within
to you to cloud riente computing, with an
ION d units etc. Some platforms ram support large grapRDBMS deployments.
■
The src
dy Ha
softw
EGRAT e ine loping task-o it and Java s written in hical on of
all attribute
softwar emphasis onDeve es by
Mainl
INT these ines providers, so youComm can better understand
also rece JavaScri user interfac web develop and the rris
Vis it
OUS
WebDriver
codel chang desc
ding e code Task Level as the
www.dzone.com
REST
reposit -patter particu s cies Pay only what you consume
tagge or Amazon’s cloud
the curr you cho platform
computing becisome
heavily based moron very little fine. b></ ed insid
lained ) and anti x” the are solution duce
nden For each (e.g. WAR es t
ent stan ose to writ more e imp a></ e
not lega each othe
b> is
be exp text to “fi
al Depeapplication deployment
Web ge until
nden a few years
t librari agonmen
t enviro was similar that will software
industry standard and virtualization apparen ortant, the
e HTM technology.
tterns to pro Minim packa
dard
Mo re
CI can ticular con used can rity all depe that all
targe
simp s will L t. HTM l, but r. Tags
es i-pa tend but to most phone services:
y Integ alize plans with late alloted resources,
file
ts with an and XHT lify all help or XHTML, Reg ardless L VS XH <a><
in a par hes som
etim s. Ant , they ctices,
Binar Centr temp your you prov TML b></
proces in the end bad pra enting
nt nmen
incurred cost
geme whether e a single based on
Creatsuchareresources were consumed
t enviro orthenot. Virtualization
muchallows MLaare physical othe
piece ofr hardware to be understand of HTML
approac ed with the cial, but, rily implem nden
cy Mana rties nt targe es to of the actually web cod ide a solid ing has
essa d to Depe prope into differe chang
utilized by multiple operating
function systems.simplerThis allows ing.resourcesfoundati job adm been arou
efi nec itting
associat to be ben
er
pare
Ge t
te builds commo
are not Fortuna
late Verifi e comm than on
ality be allocated nd for
n com Cloud computing asRun it’sremo
known etoday has changed this. expecte irably, that
befor
They they
etc.
(e.g. bandwidth, elem CPU) tohas
nmemory, exclusively totely
Temp
job has some time
Build
lts whe
ually,
appear effects. rm a
Privat y, contin nt team Every mov
entsinstances. ed to CSS
used
to be, HTML d. Earl
ed resu gration
The various resourcesPerfo consumed by webperio applications
dicall (e.g.
opme page system
individual operating bec Brow y exp . Whi
adverse unintend d Builds sitory Build r to devel common (HTM . ause ser HTM anded le it
ous Inte web dev manufacture L had very far mor has done
Stage Repo
e bandwidth, memory, CPU) areIntegtallied
ration on a per-unit CI serve basis L or XHT
produc Continu Refcard
e Build rm an ack from extensio .) All are
e.com
DZone, Inc.
the to the to rate devel
While s efer of CI
ion
Gene
Cloud Computing
the not
s on
expand
ISBN-13: 978-1-936502-03-5
140 Preston Executive Dr. ISBN-10: 1-936502-03-8
Suite 100
50795
Cary, NC 27513