Unmesh Gundecha Learning Selenium Ing Tools With Python A Practical Guide On Automated Web I

Unmesh%20Gundecha%20Learning%20Selenium%20ing%20Tools%20with%20Python%20A%20practical%20guide%20on%20automated%20web%20i

Unmesh%20Gundecha-Learning%20Selenium%20ing%20Tools%20with%20Python_%20A%20practical%20guide%20on%20automated%20web%20in

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 216

DownloadUnmesh Gundecha Learning Selenium Ing Tools With Python A Practical Guide On Automated Web I
Open PDF In BrowserView PDF
www.it-ebooks.info

Learning Selenium Testing
Tools with Python

A practical guide on automated web testing with
Selenium using Python

Unmesh Gundecha

BIRMINGHAM - MUMBAI

www.it-ebooks.info

Learning Selenium Testing Tools with Python
Copyright © 2014 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: December 2014

Production reference: 1231214

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-350-6
www.packtpub.com

www.it-ebooks.info

Credits
Author

Project Coordinator

Unmesh Gundecha

Harshal Ved

Reviewers

Proofreaders

Adil Imroz

Ameesha Green

Dr. Philip Polstra

Chris Smith

Walt Stoneburner
Indexer

Yuri Weinstein

Monica Ajmera Mehta

Commissioning Editor
Usha Iyer

Production Coordinator
Nilesh R. Mohite

Acquisition Editor

Cover Work

Neha Nagwekar

Nilesh R. Mohite

Content Development Editor
Athira Laji
Technical Editor
Mrunmayee Patil
Copy Editor
Laxmi Subramanian

www.it-ebooks.info

About the Author
Unmesh Gundecha has a Master's degree in Software Engineering and over 12

years of experience in software development and testing. Unmesh has architected
functional test automation solutions using industry standards, in-house and custom
test automation frameworks along with leading commercial and open source test
automation tools.
He has development experience in Microsoft technologies and Java. He is presently
working as a test solution architect with a multinational company in Pune, India.
His experience includes support to Ruby, Java, iOS, Android, and PHP projects as an
automated tester and software developer.
He authored Selenium Testing Tools Cookbook, Packt Publishing in November 2012.
I would like to thank Neha Nagwekar, acquisition editor, for
giving me an opportunity to write this book; Athira Laji, content
development editor; Harshal Ved, project coordinator, for constantly
supporting and encouraging me in completing this book; and the
entire team at Packt Publishing.
This book has benefited a lot from a great team of technical
reviewers. I'd like to thank each of them for volunteering their time
reviewing the drafts of this book and providing valuable feedback.
I would also like to thank my mentor and friend, Yuri Weinstein, for
his support and help during this project. Thanks to my friends and
colleagues at work for their constant encouragement and support in
writing this book.

www.it-ebooks.info

About the Reviewers
Adil Imroz is a Python enthusiast who loves the simplicity of this beautiful language.
He is a software developer in testing by profession and a mobile automation expert.
He likes playing around with open source software and believes in being agile. When
not working, he can be found biking, reading a book, or sleeping. He believes that
there is a lot of scope around; all you have to do is hit the right chords. You can get in
touch with him via e-mail at alam.adil12@gmail.com. You can also follow him on
Twitter at @adilimroz.

Dr. Philip Polstra (known to his friends as Dr. Phil) is an internationally

recognized hardware hacker. His work has been presented at numerous conferences
around the globe, including repeat performances at DEFCON, Black Hat, 44CON,
Maker Faire, and other top conferences. Dr. Polstra is a well-known expert on USB
forensics and has published several articles on this topic.
Recently, Dr. Polstra has developed a penetration testing Linux distribution, known
as The Deck, for the BeagleBone and BeagleBoard family of small computer boards.
He has also developed a new way of performing penetration testing with multiple
low-power devices, including an aerial hacking drone. This work is described in his
book Hacking and Penetration Testing with Low Power Devices, Syngress Media (2014).
Dr. Polstra has also been a technical reviewer on several books, including BeagleBone
Home Automation by Juha Lumme and BeagleBone for Secret Agents by Josh Datko, both
published in 2014 by Packt Publishing.
Dr. Polstra is an Associate Professor at Bloomsburg University of Pennsylvania
(http://bloomu.edu/digital_forensics), where he teaches digital forensics
among other topics. In addition to teaching, he provides training and performs
penetration tests on a consulting basis. When not working, he is known to fly, build
aircraft, and tinker with electronics. His latest happenings can be found on his blog
at http://philpolstra.com. You can also follow him on Twitter at @ppolstra.

www.it-ebooks.info

Walt Stoneburner is a software architect with over 25 years of commercial

application development and consulting experience. His fringe passions involve
quality assurance, configuration management, and security. If cornered, he may
actually admit to liking statistics and authoring documentation as well.
He's easily amused by programming language design, collaborative applications, big
data, knowledge management, data visualization, and ASCII art. A self-proclaimed
closet geek, Walt also evaluates software products and consumer electronics, draws
cartoons, runs a freelance photography studio specializing in portraits and art
(http://charismaticmoments.com/), writes humor pieces, performs sleight of
hand, enjoys game designing, and can occasionally be found on ham radio.
Walt can be reached directly via e-mail at wls@wwco.com or Walt.Stoneburner@
gmail.com. He publishes a tech and humor blog called Walt-O-Matic at
https://www.wwco.com/~wls/blog/.
His other book reviews and contributions include the following:
•

AntiPatterns and Patterns in Software Configuration Management, John Wiley &
Sons (ISBN 978-0471329299, p. xi)

•

Exploiting Software: How to Break Code, Pearson Education (ISBN 978-0-20178695-8, p. xxxiii)

•

Ruby on Rails Web Mashup Projects, Packt Publishing (ISBN 978-1847193933)

•

Building Dynamic Web 2.0 Websites with Ruby on Rails, Packt Publishing (ISBN
978-1-847193-41-4)

•

Instant Sinatra Starter, Packt Publishing (ISBN 978-1782168218)

•

C++ Multithreading Cookbook, Packt Publishing (ISBN 978-1-78328-979-0)

•

Trapped in Whittier (A Trent Walker Thriller Book 1), Amazon Digital South Asia
Services, Inc. (ASIN B00GTD1RBS)

•

South Mouth: Hillbilly Wisdom, Redneck Observations & Good Ol' Boy Logic,
CreateSpace Independent Publishing Platform (ISBN 978-1-482340-99-0)

Yuri Weinstein lives in San Francisco, CA with his family. He has spent over two
decades working for top technology companies in the Silicon Valley, focusing on
software testing with a special passion for test automation techniques. He currently
works at Red Hat, ensuring the quality of the Ceph open source storage project.

www.it-ebooks.info

www.PacktPub.com
Support files, eBooks, discount offers, and
more

For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and
as a print book customer, you are entitled to a discount on the eBook copy. Get in touch
with us at service@packtpub.com for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up
for a range of free newsletters and receive exclusive discounts and offers on Packt books
and eBooks.
TM

https://www.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
•
•
•

Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view 9 entirely free books. Simply use your login credentials for
immediate access.

www.it-ebooks.info

www.it-ebooks.info

Table of Contents
Preface
Chapter 1: Getting Started with Selenium WebDriver and Python

1
7

Preparing your machine
Installing Python
Installing the Selenium package
Browsing the Selenium WebDriver Python documentation
Selecting an IDE

8
8
8
9
10

Setting up PyCharm
Taking your first steps with Selenium and Python
Cross-browser support
Setting up Internet Explorer
Setting up Google Chrome
Summary

15
18
23
23
26
27

PyCharm
The PyDev Eclipse plugin
PyScripter

Chapter 2: Writing Tests Using unittest
The unittest library
The TestCase class
The setUp() method
Writing tests
Cleaning up the code
Running the test
Adding another test

Class-level setUp() and tearDown() methods
Assertions
Test suites
Generating the HTML test report
Summary

www.it-ebooks.info

10
12
13

29
29
31

32
32
33
34
36

37
38
40
43
44

Table of Contents

Chapter 3: Finding Elements

Using developer tools to find locators
Inspecting pages and elements with Firefox using the Firebug add-in
Inspecting pages and elements with Google Chrome
Inspecting pages and elements with Internet Explorer
Finding elements with Selenium WebDriver
Using the find methods
Finding elements using the ID attribute
Finding elements using the name attribute
Finding elements using the class name
Finding elements using the tag name
Finding elements using XPath
Finding elements using CSS selectors
Finding links
Finding links with partial text

Putting all the tests together using find methods
Summary

Chapter 4: Using the Selenium Python API for Element
Interaction

Elements of HTML forms
Understanding the WebDriver class
Properties of the WebDriver class
Methods of the WebDriver class
Understanding the WebElement class
Properties of the WebElement class
Methods of the WebElement class
Working with forms, textboxes, checkboxes, and radio buttons
Checking whether the element is displayed and enabled
Finding the element attribute value
Using the is_selected() method
Using the clear() and send_keys() methods
Working with dropdowns and lists
Understanding the Select class
Properties of the Select class
Methods of the Select class
Working with alerts and pop-up windows
Understanding the Alert class
Properties of the Alert class
Methods of the Alert class
Automating browser navigation
Summary
[ ii ]

www.it-ebooks.info

45
47
47
49
50
51
52

54
55
56
57
58
60
61
62

63
66

67
68
68
69
69
71
72
72
73
74
75
76
76
79
80
81
81
84
84
84
84
87
89

Table of Contents

Chapter 5: Synchronizing Tests

Using implicit wait
Using explicit wait
The expected condition class
Waiting for an element to be enabled
Waiting for alerts
Implementing custom wait conditions
Summary

Chapter 6: Cross-browser Testing

The Selenium standalone server
Downloading the Selenium standalone server
Launching the Selenium standalone server
Running a test on the Selenium standalone server
Adding support for Internet Explorer
Adding support for Chrome
Selenium Grid
Launching Selenium server as a hub
Adding nodes
Adding an IE node
Adding a Firefox node
Adding a Chrome node

Mac OS X with Safari
Running tests in Grid
Running tests in a cloud
Using Sauce Labs
Summary

91

91
93
94
97
98
99
100

101

102
103
103
105
108
108
108
109
111
111
112
113

113
114
116
117
120

Chapter 7: Testing on Mobile

121

Introducing Appium
Prerequisites for Appium

Setting up Xcode for iOS
Setting up Android SDK
Setting up the Appium Python client package

Installing Appium
Appium Inspector
Testing on iOS
Writing a test for iOS
Testing on Android
Writing a test for Android
Using Sauce Labs
Summary

[ iii ]

www.it-ebooks.info

121
122

123
124
125

125
128
128
129
131
132
135
137

Table of Contents

Chapter 8: Page Objects and Data-driven Testing

139

Chapter 9: Advanced Techniques of Selenium WebDriver

157

Data-driven testing
Using ddt for data-driven tests
Installing ddt
Creating a simple data-driven test with ddt in unittest
Using external data sources for data-driven tests
Reading values from CSV
Reading values from Excel
The page objects pattern
Organizing tests
The BasePage object
Implementing page objects
Creating a test with page objects
Summary

Methods for performing keyboard and mouse actions
Keyboard actions
The mouse movement
The double_click method
The drag_and_drop method

Executing JavaScript
Capturing screenshots of failures
Recording a video of the test run
Handling pop-up windows
Managing cookies
Summary

Chapter 10: Integration with Other Tools and Frameworks
Behavior-Driven Development
Installing Behave
Writing the first feature in Behave

Implementing a step definition file for the feature
Creating environment configurations
Running features
Using a scenario outline

CI with Jenkins
Preparing for Jenkins
Setting up Jenkins
Summary

Index

140
140
141
141
143
143
145
148
149
150
151
155
156
157
160
162

163
164

164
167
169
171
174
176

177

178
178
178

179
181
181
182

184
184
185
192

193

[ iv ]

www.it-ebooks.info

Preface
Selenium is a set of tools for automating browsers. It is largely used for testing
applications, but its usages are not limited only to testing. It can also be used for
screen scraping and automating repetitive tasks in a browser window. Selenium
supports automation on all the major browsers including Firefox, Internet Explorer,
Google Chrome, Safari, and Opera. Selenium WebDriver is now a part of W3C
standards and is supported by major browser vendors.
Selenium offers the following set of tools for automating interaction with browsers:
•

Selenium IDE: This is a Firefox add-in used to record and play back the
Selenium scripts with Firefox. It provides a graphical user interface to
record user actions using Firefox. It is a great tool to start learning and
using Selenium, but it can only be used with Firefox and other browsers are
not supported. However, it can convert the recorded scripts into various
programming languages supported by Selenium WebDriver, which supports
running scripts on browsers other than Firefox.

•

Selenium WebDriver: This is a programming interface for developing
advanced Selenium scripts using programming languages. We can also
run tests on multiple browsers that are supported by Selenium on multiple
operating systems, including Linux, Windows, and Mac OS X. This makes
Selenium a true cross-browser testing tool. Selenium WebDriver offers client
libraries in various languages, including Java, C#, Python, Ruby, PHP, and
JavaScript, and are more into writing test scripts.

•

Selenium standalone server: This is also known as Selenium Grid and
allows remote and distributed execution of Selenium scripts created with
WebDriver. We can also use the grid feature of the standalone server to run
tests in parallel, including tests on mobile platforms such as Android or
Apple iOS for iPhone and iPad.

www.it-ebooks.info

Preface

As the title suggests, this book will introduce you to the Selenium WebDriver client
library for Python. You will learn how to use Selenium WebDriver in Python to
automate browsers for testing web applications. This book contains lessons right
from setting up Selenium to using the basic and advanced features of Selenium to
create and run automated scripts for testing web applications. This book assumes
you have a basic idea of programming using Python.

What this book covers

Chapter 1, Getting Started with Selenium WebDriver and Python, starts with installing
Python and the Selenium WebDriver client library. We will select a Python editor
or IDE for Selenium script development. We will then create our first automation
script for a simple search workflow from the application under test. At the end of this
chapter, we will run the Selenium script on various browsers supported by Selenium.
Chapter 2, Writing Tests Using unittest, shows you how to use Selenium and the
unittest library to test web applications. We will convert the script into a unittest test
case. We will create few more tests using Selenium and unittest. We will create a
TestSuite for a group of tests. We will run these tests and analyze the results. At the
end of this chapter, you will learn how to produce test reports in the HTML format
that you can distribute to various stakeholders of the project.
Chapter 3, Finding Elements, introduces you to locators that are the keys to automate
different types of User Interface (UI) elements displayed on the web pages in the
browser window. Selenium uses locators to find elements on a page and then
performs actions or retrieves their properties for testing. You will learn various
methods to locate elements, including XPath and CSS. We will show you how to
use these methods with examples on the application under test.
Chapter 4, Using the Selenium Python API for Element Interaction, shows you how to use
the Selenium WebDriver client library to interact with different types of elements,
JavaScript alerts, frames, and windows in Python. You will learn how to perform
actions such as sending values to elements, performing clicks, and selecting
options from dropdowns. You will also see how to handle frames, different types
of JavaScript alerts, and switch between child browser windows.
Chapter 5, Synchronizing Tests, introduces you to various wait methods provided by
Selenium to synchronize tests for reliable and robust execution. You will learn how
to use the implicit and explicit wait to implement synchronization in Selenium tests.
You will learn various methods to implement explicit wait in our test scripts.

[2]

www.it-ebooks.info

Preface

Chapter 6, Cross-browser Testing, dives into using RemoteWebDriver to run
cross-browser tests on remote machines or through the Selenium Grid. You
will learn how to use RemoteWebDriver to run tests on remote machines.
We will also set up a Selenium Grid to run tests on various combinations of
browsers and operating systems. You will also see how to execute tests on headless
browsers such as PhantomJS. At the end of the chapter, we will see how to use
cloud testing tools such as Sauce Labs and BrowserStack to run tests in cloud using
RemoteWebDriver.
Chapter 7, Testing on Mobile, shows you how to test applications on mobile devices
using Selenium WebDriver and Appium. We will set up Appium to test our sample
application on iOS and on an Android emulator and device. You will also learn how
to run native mobile applications using Appium.
Chapter 8, Page Objects and Data-driven Testing, introduces you to two important
design patterns to implement a maintainable and efficient testing framework. You
will learn how to use page objects to hide the technical details of locators, and divide
operations on pages into separate classes and create test cases that are more readable
and easy to maintain. You will then learn how to create data-driven tests using the
unittest library.
Chapter 9, Advanced Techniques of Selenium WebDriver, dives into some of the
advanced techniques of using Selenium for automating browsers for testing. You
will learn how to use various action methods for simulating complex mouse and
keyboard operations using Selenium. You will see how to handle session cookies,
capture screenshots during a test run, and create a movie of the entire test run.
Chapter 10, Integration with Other Tools and Frameworks, shows you how to use
Selenium WebDriver with automated acceptance testing frameworks such as Behave
and Continuous Integration tools. You will first learn how to integrate Selenium with
Behave to create automated acceptance tests. We will implement a sample feature
and acceptance tests on UI using the Selenium WebDriver. At end of the chapter, we
will set up running the tests that we created as part of Continuous Integration using
Jenkins. We will set up a schedule to run the tests on a daily frequency.
By the end of this book, you will have learned all the essential features of Selenium
WebDriver to create your own web testing framework in Python.

[3]

www.it-ebooks.info

Preface

What you need for this book

To get started with this book, you will need basic programming skills in Python as well
as knowledge of web technologies such as HTML, JavaScript, CSS, and XML. If you are
able to write a simple Python script, use loops and conditions, define classes, then you
should be able to keep up with every example in this book. We will take the time to
explain every line of code written in this book so that you are able to create the desired
outcome in any situation you find yourself in. There are some software prerequisites
that are needed, which are explained in the first chapter. You will need to have access
to the command-line interface terminal, Python interpreter, and web browsers such
as Firefox and Google Chrome on your machine. You can download and install
Firefox from https://www.mozilla.org/en-US/firefox/ and Google Chrome
from https://www.google.com/chrome/. If you're a Windows user, you might be
interested in testing Internet Explorer, which is installed by default with Windows.

Who this book is for

If you are a quality assurance/testing professional, software developer, or web
application developer using Python and want to learn Selenium WebDriver to
automate browsers for testing your web applications, this is the perfect guide for you
to get started! As a prerequisite, this book expects you to have a basic understanding
of the Python programming language, although any previous knowledge of
Selenium WebDriver is not needed. By the end of this book, you will have acquired
a comprehensive knowledge of Selenium WebDriver, which will help you in writing
your automation tests.

Conventions

In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"The pip tool will download the latest version of the Selenium package and install
it on your machine."
A block of code is set as follows:
# create a new Firefox session
driver = webdriver.Firefox()
driver.implicitly_wait(30)
driver.maximize_window()
[4]

www.it-ebooks.info

Preface

When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
# run the suite
xmlrunner.XMLTestRunner(verbosity=2, output='test-reports').
run(smoke_tests)

Any command-line input or output is written as follows:
pip install -U selenium

New terms and important words are shown in bold. Words that you see on
the screen, in menus or dialog boxes for example, appear in the text like this:
"Choose Internet Options from the Tools menu."
Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or disliked. Reader feedback is important for us as it helps
us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail feedback@packtpub.com, and mention
the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

[5]

www.it-ebooks.info

Preface

Downloading the example code

You can download the example code files from your account at http://www.
packtpub.com for all the Packt Publishing books you have purchased. If you
purchased this book elsewhere, you can visit http://www.packtpub.com/support
and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books—maybe a mistake in the text or
the code—we would be grateful if you could report this to us. By doing so, you can
save other readers from frustration and help us improve subsequent versions of this
book. If you find any errata, please report them by visiting http://www.packtpub.
com/submit-errata, selecting your book, clicking on the Errata Submission Form
link, and entering the details of your errata. Once your errata are verified, your
submission will be accepted and the errata will be uploaded to our website or added
to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/
content/support and enter the name of the book in the search field. The required
information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all
media. At Packt, we take the protection of our copyright and licenses very seriously.
If you come across any illegal copies of our works in any form on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.
Please contact us at copyright@packtpub.com with a link to the suspected
pirated material.
We appreciate your help in protecting our authors and our ability to bring
you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at
questions@packtpub.com, and we will do our best to address the problem.

[6]

www.it-ebooks.info

Getting Started with Selenium
WebDriver and Python
Selenium automates browsers. It automates the interaction we do in a browser
window such as navigating to a website, clicking on links, filling out forms, submitting
forms, navigating through pages, and so on. It works on every major browser available
out there.
In order to use Selenium WebDriver, we need a programing language to write
automation scripts. The language that we select should also have a Selenium client
library available.
In this book, we will use Python along with the Selenium WebDriver client library
to create automated scripts. Python is a widely used general-purpose, high-level
programming language. It's easy and its syntax allows us to express concepts in
fewer lines of code. It emphasizes code readability and provides constructs that
enable us to write programs on both the small and large scale. It also provides a
number of in-built and user-written libraries to achieve complex tasks quite easily.
The Selenium WebDriver client library for Python provides access to all the Selenium
WebDriver features and Selenium standalone server for remote and distributed
testing of browser-based applications. Selenium Python language bindings are
developed and maintained by David Burns, Adam Goucher, Maik Röder, Jason
Huggins, Luke Semerau, Miki Tebeka, and Eric Allenin.
The Selenium WebDriver client library is supported on Python Version 2.6, 2.7, 3.2,
and 3.3.
This chapter will introduce you to the Selenium WebDriver client library for Python
by demonstrating its installation, basic features, and overall structure.

www.it-ebooks.info

Getting Started with Selenium WebDriver and Python

In this chapter, we will cover the following topics:
•

Installing Python and Selenium package

•

Selecting and setting up a Python editor

•

Implementing a sample script using the Selenium WebDriver Python
client library

•

Implementing cross-browser support with Internet Explorer and
Google Chrome

Preparing your machine

As a first step of using Selenium with Python, we'll need to install it on our computer
with the minimum requirements possible. Let's set up the basic environment with
the steps explained in the following sections.

Installing Python

You will find Python installed by default on most Linux distributions, Mac OS X, and
other Unix machines. On Windows, you will need to install it separately. Installers
for different platforms can be found at http://python.org/download/.
All the examples in this book are written and
tested on Python 2.7 and Python 3.0 on Windows 8
operating systems.

Installing the Selenium package

The Selenium WebDriver Python client library is available in the Selenium package.
To install the Selenium package in a simple way, use the pip installer tool available
at https://pip.pypa.io/en/latest/.
With pip, you can simply install or upgrade the Selenium package using the
following command:
pip install -U selenium

This is a fairly simple process. This command will set up the Selenium WebDriver
client library on your machine with all modules and classes that we will need to
create automated scripts using Python. The pip tool will download the latest version
of the Selenium package and install it on your machine. The optional –U flag will
upgrade the existing version of the installed package to the latest version.
[8]

www.it-ebooks.info

Chapter 1

You can also download the latest version of the Selenium package source from
https://pypi.python.org/pypi/selenium. Just click on the Download button on
the upper-right-hand side of the page, unarchive the downloaded file, and install it
with following command:
python setup.py install

Browsing the Selenium WebDriver Python
documentation
The Selenium WebDriver Python client library documentation is available at
http://selenium.googlecode.com/git/docs/api/py/api.html as shown
in the following screenshot:

[9]

www.it-ebooks.info

Getting Started with Selenium WebDriver and Python

It offers detailed information on all core classes and functions of Selenium
WebDriver. Also note the following links for Selenium documentation:
•

The official documentation at http://docs.seleniumhq.org/docs/
offers documentation for all the Selenium components with examples in
supported languages

•

Selenium Wiki at https://code.google.com/p/selenium/w/list lists
some useful topics that we will explore later in this book

Selecting an IDE

Now that we have Python and Selenium WebDriver set up, we will need an editor
or an Integrated Development Environment (IDE) to write automation scripts.
A good editor or IDE increases the productivity and helps in doing a lot of other
things that make the coding experience simple and easy. While we can write Python
code in simple editors such as Emacs, Vim, or Notepad, using an IDE will make life
a lot easier. There are many IDEs to choose from. Generally, an IDE provides the
following features to accelerate your development and coding time:
•

A graphical code editor with code completion and IntelliSense

•

A code explorer for functions and classes

•

Syntax highlighting

•

Project management

•

Code templates

•

Tools for unit testing and debugging

•

Source control support

If you're new to Python, or you're a tester working for the first time in Python, your
development team will help you to set up the right IDE.
However, if you're starting with Python for the first time and don't know which IDE
to select, here are a few choices that you might want to consider.

PyCharm

PyCharm is developed by JetBrains, a leading vendor of professional development
tools and IDEs such as IntelliJ IDEA, RubyMine, PhpStorm, and TeamCity.
PyCharm is a polished, powerful, and versatile IDE that works pretty well. It brings
best of the JetBrains experience in building powerful IDEs with lots of other features
for a highly productive experience.
[ 10 ]

www.it-ebooks.info

Chapter 1

PyCharm is supported on Windows, Linux, and Mac. To know more about PyCharm
and its features visit http://www.jetbrains.com/pycharm/.
PyCharm comes in two versions—a community edition and a professional edition.
The community edition is free, whereas you have to pay for the professional edition.
Here is the PyCharm community edition running a sample Selenium script in the
following screenshot:

[ 11 ]

www.it-ebooks.info

Getting Started with Selenium WebDriver and Python

The community edition is great for building and running Selenium scripts with its
fantastic debugging support. We will use PyCharm in the rest of this book. Later in
this chapter, we will set up PyCharm and create our first Selenium script.
All the examples in this book are built using PyCharm; however,
you can easily use these examples in your choice of editor or IDE.

The PyDev Eclipse plugin

The PyDev Eclipse plugin is another widely used editor among Python developers.
Eclipse is a famous open source IDE primarily built for Java; however, it also offers
support to various other programming languages and tools through its powerful
plugin architecture.
Eclipse is a cross-platform IDE supported on Windows, Linux, and Mac. You can get
the latest edition of Eclipse at http://www.eclipse.org/downloads/.
You need to install the PyDev plugin separately after setting up Eclipse. Use the
tutorial from Lars Vogel to install PyDev at http://www.vogella.com/tutorials/
Python/article.html to install PyDev. Installation instructions are also available
at http://pydev.org/.

[ 12 ]

www.it-ebooks.info

Chapter 1

Here's the Eclipse PyDev plugin running a sample Selenium script as shown in the
following screenshot:

PyScripter

For the Windows users, PyScripter can also be a great choice. It is open source,
lightweight, and provides all the features that modern IDEs offer such as IntelliSense
and code completion, testing, and debugging support. You can find more about
PyScripter along with its download information at https://code.google.com/p/
pyscripter/.

[ 13 ]

www.it-ebooks.info

Getting Started with Selenium WebDriver and Python

Here's PyScripter running a sample Selenium script as shown in the following
screenshot:

[ 14 ]

www.it-ebooks.info

Chapter 1

Setting up PyCharm

Now that we have seen IDE choices, let's set up PyCharm. All examples in this book
are created with PyCharm. However, you can set up any other IDE of your choice
and use examples as they are. We will set up PyCharm with following steps to get
started with Selenium Python:
1. Download and install the PyCharm Community Edition from JetBrains site
http://www.jetbrains.com/pycharm/download/index.html.
2. Launch the PyCharm Community Edition. Click on the Create New Project
option on the PyCharm Community Edition dialog box as shown in the
following screenshot:

[ 15 ]

www.it-ebooks.info

Getting Started with Selenium WebDriver and Python

3. On the Create New Project dialog box, as shown in next screenshot, specify
the name of your project in the Project name field. In this example, setests
is used as the project name. We need to configure the interpreter for the
first time. Click on the
button to set up the interpreter, as shown in the
following screenshot:

4. On the Python Interpreter dialog box, click on the plus icon. PyCharm will
suggest the installed interpreter similar to the following screenshot. Select the
interpreter from Select Interpreter Path.

[ 16 ]

www.it-ebooks.info

Chapter 1

5. PyCharm will configure the selected interpreter as shown in the following
screenshot. It will show a list of packages that are installed along with
Python. Click on the Apply button and then on the OK button:

6. On the Create New Project dialog box, click on the OK button to create
the project:

[ 17 ]

www.it-ebooks.info

Getting Started with Selenium WebDriver and Python

Taking your first steps with Selenium and
Python
We are now ready to start with creating and running automated scripts in Python.
Let's begin with Selenium WebDriver and create a Python script that uses Selenium
WebDriver classes and functions to automate browser interaction.
We will use a sample web application for most of the examples in this book. This
sample application is built on a famous e-commerce framework—Magento. You
can find the application at http://demo.magentocommerce.com/.
Downloading the example code
You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books
you have purchased. If you purchased this book elsewhere, you
can visit http://www.packtpub.com/support and register
to have the files e-mailed directly to you.
The example code is also hosted at https://github.com/
upgundecha/learnsewithpython.

In this sample script, we will navigate to the demo version of the application, search
for products, and list the names of products from the search result page with the
following steps:
1. Let's use the project that we created earlier while setting up PyCharm. Create
a simple Python script that will use the Selenium WebDriver client library. In
Project Explorer, right-click on setests and navigate to New | Python File
from the pop-up menu:

[ 18 ]

www.it-ebooks.info

Chapter 1

2. On the New Python file dialog box, enter searchproducts in the Name field
and click on the OK button:

3. PyCharm will add a new tab searchproducts.py in the code editor area.
Copy the following code in the searchproduct.py tab:
from selenium import webdriver
# create a new Firefox session
driver = webdriver.Firefox()
driver.implicitly_wait(30)
driver.maximize_window()
# navigate to the application home page
driver.get("http://demo.magentocommerce.com/")
# get the search textbox
search_field = driver.find_element_by_name("q")
search_field.clear()
# enter search keyword and submit
search_field.send_keys("phones")
search_field.submit()
# get all the anchor elements which have product names displayed
# currently on result page using find_elements_by_xpath method
products = driver.find_elements_by_xpath("//h2[@class='productname']/a")
# get the number of anchor elements found
print "Found " + str(len(products)) + " products:"
# iterate through each anchor element and print the text that is
# name of the product
for product in products:
print product.text
# close the browser window
driver.quit()
[ 19 ]

www.it-ebooks.info

Getting Started with Selenium WebDriver and Python

If you're using any other IDE or editor of your choice, create
a new file, copy the code to the new file, and save the file as
searchproducts.py.

4. To run the script, press the Ctrl + Shift + F10 combination in the PyCharm
code window or select Run 'searchproducts' from the Run menu. This will
start the execution and you will see a new Firefox window navigating to
the demo site and the Selenium commands getting executed in the Firefox
window. If all goes well, at the end, the script will close the Firefox window.
The script will print the list of products in the PyCharm console as shown in
the following screenshot:

[ 20 ]

www.it-ebooks.info

Chapter 1

We can also run this script through the command line with the
following command. Open the command line, then open the
setests directory, and run following command:
python searchproducts.py

We will use command line as the preferred method in the rest
of the book to execute the tests.

We'll spend some time looking into the script that we created just now. We will go
through each statement and understand Selenium WebDriver in brief. There is a lot
to go through in the rest of the book.
The selenium.webdriver module implements the browser driver classes that are
supported by Selenium, including Firefox, Chrome, Internet Explorer, Safari, and
various other browsers, and RemoteWebDriver to test on browsers that are hosted
on remote machines.
We need to import webdriver from the Selenium package to use the Selenium
WebDriver methods:
from selenium import webdriver

Next, we need an instance of a browser that we want to use. This will provide a
programmatic interface to interact with the browser using the Selenium commands.
In this example, we are using Firefox. We can create
an instance of Firefox as shown in following code:
driver = webdriver.Firefox()

During the run, this will launch a new Firefox window. We also set a few options on
the driver:
driver.implicitly_wait(30)
driver.maximize_window()

We configured a timeout for Selenium to execute steps using an implicit wait of 30
seconds for the driver and maximized the Firefox window through the Selenium
API. We will learn more about implicit wait in Chapter 5, Synchronizing Tests.
Next, we will navigate to the demo version of the application using its URL by
calling the driver.get() method. After the get() method is called, WebDriver
waits until the page is fully loaded in the Firefox window and returns the control
to the script.

[ 21 ]

www.it-ebooks.info

Getting Started with Selenium WebDriver and Python

After loading the page, Selenium will interact with various elements on the page,
like a human user. For example, on the Home page of the application, we need to
enter a search term in a textbox and click on the Search button. These elements are
implemented as HTML input elements and Selenium needs to find these elements to
simulate the user action. Selenium WebDriver provides a number of methods to find
these elements and interact with them to perform operations such as sending values,
clicking buttons, selecting items in dropdowns, and so on. We will see more about
this in Chapter 3, Finding Elements.
In this example, we are finding the Search textbox using the find_element_by_name
method. This will return the first element matching the name attribute specified in
the find method. The HTML elements are defined with tag and attributes. We can
use this information to find an element, by following the given steps:
1. In this example, the Search textbox has the name attribute defined as q and
we can use this attribute as shown in the following code example:
search_field = driver.find_element_by_name("q")

2. Once the Search textbox is found, we will interact with this element by
clearing the previous value (if entered) using the clear() method and
enter the specified new value using the send_keys() method. Next, we
will submit the search request by calling the submit() method:
search_field.clear()
search_field.send_keys("phones")
search_field.submit()

3. After submission of the search request, Firefox will load the result page
returned by the application. The result page has a list of products that
match the search term, which is phones. We can read the list of results and
specifically the names of all the products that are rendered in the anchor
 element using the find_elements_by_xpath() method. This will return
more than one matching element as a list:
products =
driver.find_elements_by_xpath("//h2[@class=
'product-name']/a")

4. Next, we will print the number of products (that is the number of anchor 
elements) that are found on the page and the names of the products using the
.text property of all the anchor  elements:
print "Found " + str(len(products)) + " products:"
for product in products:
print product.text

[ 22 ]

www.it-ebooks.info

Chapter 1

5. At end of the script, we will close the Firefox browser using the driver.
quit() method:
driver.quit()

This example script gives us a concise example of using Selenium WebDriver and
Python together to create a simple automation script. We are not testing anything in
this script yet. Later in the book, we will extend this simple script into a set of tests
and use various other libraries and features of Python.

Cross-browser support

So far we have built and run our script with Firefox. Selenium has extensive support
for cross-browser testing where you can automate on all the major browsers
including Internet Explorer, Google Chrome, Safari, Opera, and headless browsers
such as PhantomJS. In this section, we will set up and run the script that we created
in the previous section with Internet Explorer and Google Chrome to see the
cross-browser capabilities of Selenium WebDriver.

Setting up Internet Explorer

There is a little more to run scripts on Internet Explorer. To run tests on Internet
Explorer, we need to download and set up the InternetExplorerDriver server.
The InternetExplorerDriver server is a standalone server executable that
implements WebDriver's wire protocol to work as glue between the test script and
Internet Explorer. It supports major IE versions on Windows XP, Vista, Windows 7,
and Windows 8 operating systems. Let's set up the InternetExplorerDriver server
with the following steps:
1. Download the InternetExplorerDriver server from http://www.
seleniumhq.org/download/. You can download 32- or 64-bit versions
based on the system configuration that you are using.
2. After downloading the InternetExplorerDriver server, unzip and copy
the file to the same directory where scripts are stored.
3. On IE 7 or higher, the Protected Mode settings for each zone must have the
same value. Protected Mode can either be on or off, as long as it is for all the
zones. To set the Protected Mode settings:
1. Choose Internet Options from the Tools menu.
2. On the Internet Options dialog box, click on the Security tab.

[ 23 ]

www.it-ebooks.info

Getting Started with Selenium WebDriver and Python

3. Select each zone listed in Select a zone to view or change security
settings and make sure Enable Protected Mode (requires restarting
Internet Explorer) is either checked or unchecked for all the
zones. All the zones should have the same settings as shown in
the following screenshot:

While using the InternetExplorerDriver server, it is
also important to keep the browser zoom level set to 100
percent so that the native mouse events can be set to the
correct coordinates.

4. Finally, modify the script to use Internet Explorer. Instead of creating an
instance of the Firefox class, we will use the IE class in the following way:
import os
from selenium import webdriver
[ 24 ]

www.it-ebooks.info

Chapter 1
# get the path of IEDriverServer
dir = os.path.dirname(__file__)
ie_driver_path = dir + "\IEDriverServer.exe"
# create a new Internet Explorer session
driver = webdriver.Ie(ie_driver_path)
driver.implicitly_wait(30)
driver.maximize_window()
# navigate to the application home page
driver.get("http://demo.magentocommerce.com/")
# get the search textbox
search_field = driver.find_element_by_name("q")
search_field.clear()
# enter search keyword and submit
search_field.send_keys("phones")
search_field.submit()
# get all the anchor elements which have product names displayed
# currently on result page using find_elements_by_xpath method
products = driver.find_elements_by_xpath("//h2[@class='productname']/a")
# get the number of anchor elements found
print "Found " + str(len(products)) + " products:"
# iterate through each anchor element and print the text that is
# name of the product
for product in products:
print product.text
# close the browser window
driver.quit()

In this script, we passed the path of the InternetExplorerDriver server
while creating the instance of an IE browser class.
5. Run the script and Selenium will first launch the InternetExplorerDriver
server, which launches the browser, and execute the steps.
The InternetExplorerDriver server acts as an intermediary between the
Selenium script and the browser. Execution of the actual steps is very similar
to what we observed with Firefox.
[ 25 ]

www.it-ebooks.info

Getting Started with Selenium WebDriver and Python

Read more about the important configuration options for
Internet Explorer at https://code.google.com/p/
selenium/wiki/InternetExplorerDriver and the
DesiredCapabilities article at https://code.google.com/p/
selenium/wiki/DesiredCapabilities.

Setting up Google Chrome

Setting up and running Selenium scripts on Google Chrome is similar to
Internet Explorer. We need to download the ChromeDriver server similar to
InternetExplorerDriver. The ChromeDriver server is a standalone server
developed and maintained by the Chromium team. It implements WebDriver's wire
protocol for automating Google Chrome. It is supported on Windows, Linux, and
Mac operating systems. Set up the ChromeDriver server using the following steps:
1. Download the ChromeDriver server from http://chromedriver.storage.
googleapis.com/index.html.
2. After downloading the ChromeDriver server, unzip and copy the file to the
same directory where the scripts are stored.
3. Finally, modify the sample script to use Chrome. Instead of creating an
instance of the Firefox class, we will use the Chrome class in the following way:
import os
from selenium import webdriver
# get the path of chromedriver
dir = os.path.dirname(__file__)
chrome_driver_path = dir + "\chromedriver.exe"
#remove the .exe extension on linux or mac platform
# create a new Chrome session
driver = webdriver.Chrome(chrome_driver_path)
driver.implicitly_wait(30)
driver.maximize_window()
# navigate to the application home page
driver.get("http://demo.magentocommerce.com/")
# get the search textbox
search_field = driver.find_element_by_name("q")
search_field.clear()
# enter search keyword and submit
[ 26 ]

www.it-ebooks.info

Chapter 1
search_field.send_keys("phones")
search_field.submit()
# get all the anchor elements which have product names displayed
# currently on result page using find_elements_by_xpath method
products = driver.find_elements_by_xpath("//h2[@class='productname']/a")
# get the number of anchor elements found
print "Found " + str(len(products)) + " products:"
# iterate through each anchor element and print the text that is
# name of the product
for product in products:
print product.text
# close the browser window
driver.quit()

In this script, we passed the path of the ChromeDriver server while creating
an instance of the Chrome browser class.
4. Run the script. Selenium will first launch the Chromedriver server, which
launches the Chrome browser, and execute the steps. Execution of the actual
steps is very similar to what we observed with Firefox.
Read more about ChromeDriver at https://code.
google.com/p/selenium/wiki/ChromeDriver and
https://sites.google.com/a/chromium.org/
chromedriver/home.

Summary

In this chapter, we introduced you to Selenium and its components. We installed the
selenium package using the pip tool. Then we looked at various Editors and IDEs
to ease our coding experience with Selenium and Python and set up PyCharm. Then
we built a simple script on a sample application covering some of the high-level
concepts of Selenium WebDriver Python client library using Firefox. We ran the script
and analyzed the outcome. Finally, we explored the cross-browser testing support of
Selenium WebDriver by configuring and running the script with Internet Explorer and
Google Chrome.
In next chapter, we will learn how to use the unittest library to create automated
tests using Selenium WebDriver. We will also learn how to create a suite of tests and
run tests in groups.
[ 27 ]

www.it-ebooks.info

www.it-ebooks.info

Writing Tests Using unittest
Selenium WebDriver is a browser automation API. It provides features to automate
browser interaction, and this API is mainly used to test web applications. We cannot
set up test preconditions and post conditions, check the expected and actual output,
check the state of the application, report test results, create data-driven tests, and so on
with Selenium WebDriver. We can use a unit testing framework or test runners used
for unit testing along with Selenium to create a testing framework. In this chapter,
we will learn how to use the unittest library to create Selenium WebDriver tests in
Python.
In this chapter, we will cover the following topics:
•

What unittest is?

•

Using the unittest library to write Selenium WebDriver tests

•

Implementing a test using the TestCase class

•

Understanding various types of assert methods provided by the
unittest library

•

Creating a TestSuite for a group of tests

•

Generating test reports in HTML format using the unittest extension

The unittest library

The unittest library (originally named as PyUnit) is inspired by the JUnit library
widely used in Java application development. We can use unittest to create a
comprehensive suite of tests for any project. The unittest module is used within
the Python project to test various standard library modules including unittest
itself. You can find the unittest documentation at http://docs.python.org/2/
library/unittest.html.

www.it-ebooks.info

Writing Tests Using unittest

The unittest library provides us with the ability to create test cases, test suites,
and test fixtures. Let's understand each of these components as shown in
following diagram:

•

Test Fixture: By using a test fixture, we can define the preparation needed to
perform one or more tests and any associated clean-up actions.

•

Test Case: A test case is the smallest unit of testing in unittest. It checks
for a specific response to a particular set of actions and inputs using various
assert methods provided by the unittest library. The unittest library
provides a base class called TestCase that may be used to create
new test cases.

•

Test Suite: A test suite is a collection of multiple tests or test cases to
create groups of tests representing specific functionality or modules of the
application under test, which will be executed together.

•

Test Runner: The test runner orchestrates execution of tests and provides
results to the user. The runner may use a graphical interface, a textual interface,
or return a special value to indicate the results of executing the tests.

•

Test Report: A test report displays a summary of test results showing the
pass or fail status of executed test cases, expected versus actual results for
failed steps, and summary of overall run and timing information.

A test created with the xUnit framework such as unittest is divided into three
parts also known as the 3 A's, as follows:
•

Arrange: This part sets up the preconditions for tests including the object(s)
that need to be tested, related configuration, and dependencies
[ 30 ]

www.it-ebooks.info

Chapter 2

•

Act: This part exercises the functionality

•

Assert: This part checks the outcome with the expected results

We will use this approach to create tests with the unittest library in rest of
the chapter.
We will use the unittest library in rest of the book to create and
run Selenium WebDriver tests. However, there are other testing
frameworks available in Python with additional features, as follows:
•

•

Nose: The nose framework extends the unittest library
and provides ability to search and run tests automatically.
It also provides various plugins to create more advanced
tests. You can find more about nose at https://nose.
readthedocs.org/en/latest/.
Pytest: The pytest framework is another testing framework
that offers a number of advanced features to write and run
unit tests in Python. You can find out more about pytest at
http://pytest.org/latest/.

The TestCase class

We can create a test, or group of tests, by inheriting the TestCase class and adding
each test as a method to this class. To make a test, we need to either use assert or
one of the many variations on assert that are part of the TestCase class. The most
important task of each test is a call to assertEqual() to check for an expected result,
assertTrue() to verify a condition, or assertRaises() to verify that an expected
exception gets raised.
In addition to adding tests, we can add test fixtures: that is the setUp() and
tearDown() methods to handle creation and disposition of any objects or conditions
that are needed for a test.
Let's start using the unittest library, first writing a simple test by inheriting the
TestCase class and then adding a test method for the sample script that we created
in Chapter 1, Getting Started with Selenium WebDriver and Python.
We need to import the unittest module and define a class that inherits the
TestCase class, as shown here:
import unittest
from selenium import webdriver
class SearchTest(unittest.TestCase):

[ 31 ]

www.it-ebooks.info

Writing Tests Using unittest

The setUp() method

The starting point for test cases is the setUp() method, which we can use to perform
some tasks at the start of each test or all the tests that will be defined in the class.
These can be test preparation tasks such as creating an instance of a browser driver,
navigating to the base URL, loading test data, opening logfiles, and so on.
This method takes no arguments and doesn't return anything. When a setUp()
method is defined, the test runner will run that method prior to each test method.
In our example, we will use the setUp() method to create an instance of Firefox, set
up the properties, and navigate to the main page of the application before a test is
executed as shown in the following example:
import unittest
from selenium import webdriver
class SearchTests(unittest.TestCase):
def setUp(self):
# create a new Firefox session
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.driver.maximize_window()
# navigate to the application home page
self.driver.get("http://demo.magentocommerce.com/")

Writing tests

With a setup method in place, we can now write some tests to verify the application's
functionality that we want to test. In this example, we will search for a product and
check if the result returns a number of items. Similar to the setUp() method, test
methods are implemented in the TestCase class. It is important that we name these
methods beginning with the word test. This naming convention informs the test
runner about which methods represent a test.
For each test method that the test runner finds, it executes the setUp() method
before executing the test method. This helps ensure that each test method can
depend on a consistent environment, regardless of how many tests are defined in the
class. We will use a simple assertEqual() method to check that the expected results
for the given search term match with the results returned by the application. We will
discuss more about assertions later in the chapter.

[ 32 ]

www.it-ebooks.info

Chapter 2

Add a new test method, test_search_by_category(), which searches for products
by category and checks for the number of products returned by the search, as shown
in following example:
import unittest
from selenium import webdriver
class SearchTests(unittest.TestCase):
def setUp(self):
# create a new Firefox session
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.driver.maximize_window()
# navigate to the application home page
self.driver.get("http://demo.magentocommerce.com/")
def test_search_by_category(self):
# get the search textbox
self.search_field = self.driver.find_element_by_name("q")
self.search_field.clear()
# enter search keyword and submit
self.search_field.send_keys("phones")
self.search_field.submit()
# get all the anchor elements which have product names
# displayed currently on result page using
# find_elements_by_xpath method
products = self.driver.find_elements_by_xpath
("//h2[@class='product-name']/a")
self.assertEqual(2, len(products))

Cleaning up the code

Similar to the setUp() method that is called before each test method, the TestCase
class also calls a tearDown() method to clean up any initialized values after the test
is executed. Once a test is executed, the values defined in the setUp() method are
no longer required; so, it is good practice to clean up the values initialized by the
setUp() method after a test is completed. In our example, after a test is executed,
we no longer need the instance of Firefox. We will close the Firefox instance that
was created for the test in the tearDown() method, as shown in the following code:
import unittest
from selenium import webdriver
class SearchTests(unittest.TestCase):
[ 33 ]

www.it-ebooks.info

Writing Tests Using unittest
def setUp(self):
# create a new Firefox session
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.driver.maximize_window()
# navigate to the application home page
self.driver.get("http://demo.magentocommerce.com/")
def test_search_by_category(self):
# get the search textbox
self.search_field = self.driver.find_element_by_name("q")
self.search_field.clear()
# enter search keyword and submit
self.search_field.send_keys("phones")
self.search_field.submit()
# get all the anchor elements which have product names
# displayed currently on result page using
# find_elements_by_xpath method
products = self.driver.find_elements_by_xpath
("//h2[@class='product-name']/a")
self.assertEqual(2, len(products))
def tearDown(self):
# close the browser window
self.driver.quit()

Running the test

To run the test from command line, we can add a call to the main method of the test
case. We will pass the verbosity argument that is used to display the amount of test
result details on the console:
if __name__ == '__main__':
unittest.main(verbosity=2)

We can store the tests as a normal Python script. For this example, save the sample
test as searchtests.py. After saving the file, we can execute it through command
line by using the following command:
python searchtests.py

[ 34 ]

www.it-ebooks.info

Chapter 2

After running the tests, unittest shows the results on the console along with the
summary of tests as shown in the following screenshot:

In addition to the results summary, when a test case fails, for each failure, summary
will produce a block of text to describe what went wrong. Look at the following
screenshot to see what happens when we change the expected value to something else:

As you can see, it shows exactly which test method generated the failure, with
trace-back information to track down the code flow that led to the failure. In
addition, the failure itself is shown as AssertionError, with a mismatch of the
expected output with the actual output.

[ 35 ]

www.it-ebooks.info

Writing Tests Using unittest

Adding another test

We can group a number of tests as part of one test class. This helps in creating logical
groups of tests that belong to a specific functionality. Let's add another test to the
test class. The rule is simple; name the new method starting with the word test, as
shown in the following code:
def test_search_by_name(self):
# get the search textbox
self.search_field = self.driver.find_element_by_name("q")
self.search_field.clear()
# enter search keyword and submit
self.search_field.send_keys("salt shaker")
self.search_field.submit()
# get all the anchor elements which have
# product names displayed
# currently on result page using
# find_elements_by_xpath method
products = self.driver.find_elements_by_xpath
("//h2[@class='product-name']/a")
self.assertEqual(1, len(products))

Run the test and you will see two instances of Firefox opening and closing. This is
how the setUp() and tearDown() methods work for each test method. You will see
the result as shown in the following screenshot:

[ 36 ]

www.it-ebooks.info

Chapter 2

Class-level setUp() and tearDown() methods

In the previous example, we created a new instance of Firefox using the setUp()
method before the execution of each test method and closed that instance after the
execution of the test method. How about sharing a single Firefox instance between
the methods instead of creating a new instance every time? This can be done by
using the setUpClass() and tearDownClass() methods and using the
@classmethod decorator. These methods allow us to initialize values at the class
level instead of the method level and then share these values between the test
methods. In the following example, the code is modified to call the setUpClass()
and tearDownClass() methods with the @classmethod decorator:
import unittest
from selenium import webdriver
class SearchTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
# create a new Firefox session
cls.driver = webdriver.Firefox()
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
# navigate to the application home page
cls.driver.get("http://demo.magentocommerce.com/")
cls.driver.title
def test_search_by_category(self):
# get the search textbox
self.search_field = self.driver.find_element_by_name("q")
self.search_field.clear()
# enter search keyword and submit
self.search_field.send_keys("phones")
self.search_field.submit()
# get all the anchor elements which have product names
# displayed currently on result page using
# find_elements_by_xpath method
products = self.driver.find_elements_by_xpath
("//h2[@class='product-name']/a")
self.assertEqual(2, len(products))

[ 37 ]

www.it-ebooks.info

Writing Tests Using unittest
def test_search_by_name(self):
# get the search textbox
self.search_field = self.driver.find_element_by_name("q")
self.search_field.clear()
# enter search keyword and submit
self.search_field.send_keys("salt shaker")
self.search_field.submit()
# get all the anchor elements which have product names
# displayed currently on result page using
# find_elements_by_xpath method
products = self.driver.find_elements_by_xpath
("//h2[@class='product-name']/a")
self.assertEqual(1, len(products))
@classmethod
def tearDownClass(cls):
# close the browser window
cls.driver.quit()
if __name__ == '__main__':
unittest.main()

Run the test and you will see a single Firefox instance created; both the tests will use
this instance.
For more information on the @classmethod decorator,
refer to https://docs.python.org/2/library/
functions.html#classmethod.

Assertions

The TestCase class of the unittest library offers a number of utility methods
to check the expected values against actual values returned by the application.
These methods are implemented in such a way that they represent a condition that
must be true in order to continue the execution of the test. There are broadly three
types of such methods, each covering a specific type of condition such as checking
equivalence, logical comparison, and exceptions. If the given assertion passes, the
test will continue to the next line of code; otherwise, the test halts immediately and
a failure message will be generated.

[ 38 ]

www.it-ebooks.info

Chapter 2

The unittest library provides all the standard xUnit asserts methods. The
following table lists some of the important methods that we will be using in the
rest of the book:
Method

Condition
that is
checked

Example uses

assertEqual(a, b [,msg])

a == b

assertNotEqual(a,
b[,msg])

a != b

These methods check whether or not a
and b are equal to each other. The msg
object is a message explaining the failure
(if any).
This is useful to check values of elements,
attributes, and so on. For example:
assertEqual(element.text,"10")

assertTrue(x[,msg]))

bool(x) is
True

These methods check whether the given
expression evaluates to True or False.

assertFalse(x[,msg]))

bool(x) is
False

assertIsNot(a, b[,msg]))

a is not b

For example, to check whether the
element is displayed on a page, we can
use the following method:
assertTrue(element.is_
dispalyed())

assertRaises(exc, fun,
*args, **kwds)

fun(*args,
**kwds)
raises exc

assertRaisesRegexp(exc,
r, fun, *args, **kwds)

fun(*args,
**kwds)
raises exc
and the
message
matches
regex r

assertAlmostEqual(a, b)

round(a-b,
7) == 0

assertNotAlmostEqual(a,
b)

round(a-b,
7) != 0

assertGreater(a, b)

a>b

assertGreaterEqual(a, b)

a >= b

assertLess(a, b)

a



Each element such as the search textbox and search button is implemented using an
 tag inside a 
tag and labels are implemented using the

Navigation menu