SlideShare a Scribd company logo
Writing automated tests
Python + Selenium
Letícia Rostirola
Before Automating: BDD
● Encouraging conversation between all involved
● Writing down examples to make things clearer
● Reduce ambiguity
“Automating the scenarios resulting from the conversations is an optional next step.”
Julien Biezemans
Creator of Cucumber.js
Gherkin: a natural language style
“Gherkin is designed to be easy to learn by non-
programmers, yet structured enough to allow
concise description of examples to illustrate
business rules in most real-world domains”.
Why Test Automation?
● Saves you time, money and people
● Consistency of tests
● Continuous Integration
● Avoid boredom
Cucumber
Cucumber can be used to implement automated tests based
on scenarios described in your Gherkin feature files.
In the example given in step definitions:
When she eats 3 cucumbers
Cucumber extracts the text 3 from the step, converts it to an
int and passes it as an argument to the method.
Cucumber vs Behave vs Godog
Cucumber: Java, JS, Ruby.
Behave: Cucumber Python style.
Godog: Cucumber for golang.
Web browser automation
Selenium
“Selenium automates browsers. That's it! What you do with
that power is entirely up to you”.
Web browser automation
Selenium vs Splinter
Project Organization
Page Objects design pattern
“Despite the term "page" object, these objects shouldn't usually be built for each page, but rather for
the significant elements on a page. So a page showing multiple albums would have an album list
page object containing several album page objects. There would probably also be a header page
object and a footer page object.”
Martin Fowler
Software Developer
Page Objects: Benefits
● Create reusable code that can be shared
across multiple test cases
● Reduce the amount of duplicated code
● If the user interface changes, the fix needs
changes in only one place
Page Objects: Example
from lib.pages.basepage import BasePage
from selenium.webdriver.common.by import By
class LogoutPage(BasePage):
def __init__(self, context):
BasePage.__init__(self, context.browser, base_url='http://twitter.com/logout')
locator_dictionary = {
"submit" : (By.CSS_SELECTOR, 'button[type="submit"]'),
}
Page Objects: BasePage
class BasePage(object):
base_url = 'http://twitter.com/'
def __init__(self, driver):
self.driver = driver
def find(self, selector):
return self.driver.find_element_by_css_selector(selector)
def contains_content(self, text, timeout):
try:
elem = WebDriverWait(self.driver, timeout).until(
EC.text_to_be_present_in_element((By.TAG_NAME, 'body'), text))
return elem
except TimeoutException as ex:
return False
Creating the project
Tree
https://github.com/ladylovelace/automation-behave-pageobjects
.
├── features
│ ├── config.py
│ ├── config.py.dist
│ ├── environment.py
│ ├── lib
│ │ ├── chromedriver
│ │ └── pages
│ │ ├── basepage.py
│ │ ├── homepage.py
│ │ └── loginpage.py
│ ├── login_twitter.feature
│ ├── steps
│ │ ├── home.py
│ │ └── login.py
│ └── tweet.feature
├── README.md
├── requirements.txt
├── screenshot
Features
Feature: Tweet
Allow valid users
Post 280 characters limit per tweet
To have a better day
@rainy
Scenario: Tweet like a crazy teenager > 280 chars
Given the valid user is logged in on the homepage
When user post invalid tweet
Then the tweet button should be disabled
@sunny @sanity
Scenario: Tweet properly <= 280 chars
Given the valid user is logged in on the homepage
When user post valid tweet
Then the tweet button should be enabled
And the user should be able to tweet
environment.py
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from lib.pages.basepage import BasePage
def before_all(context):
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
context.browser = BasePage(driver)
def after_scenario(context, scenario):
context.browser.screenshot(str(scenario))
def after_all(context):
print("===== That's all folks =====")
context.browser.close()
steps/page.py
from features.lib.pages.loginpage import LoginPage
from behave import given, when, then
from config import USER
@when(u'the "{user_type}" user logs in')
def login(context, user_type):
username_field = context.browser.find(
LoginPage.locator_dictionary['email'])
password_field = context.browser.find(
LoginPage.locator_dictionary['password'])
username_field.send_keys(USER[user_type]['email'])
password_field.send_keys(USER[user_type]['pass'])
submit_button = context.browser.find(
LoginPage.locator_dictionary['submit'])
submit_button.click()
Scenario: Valid login
Given "valid" user navigates to page "landing"
When the "valid" user logs in
Then the user should be redirected to homepage
feature/steps/login.py feature/steps/login.py
config.py (optional)
USER = {
'valid': {
'email': 'YOUR_EMAIL',
'pass': 'YOUR_PASS',
'username': 'YOUR_USERNAME',
},
'invalid': {
'email': 'spy@spy.com.br',
'pass': 'mudar123',
},
}
Running
https://github.com/PyLadiesSanca/little-monkey
$ pip install selenium
$ pip install behave
$ behave
Test Recording
Tips
● Be aware of Chromedriver/chrome version
○ Chrome headless requires chromedriver 2.3+
● Use Selenium explicit/implicit wait instead of python time.sleep function
○ Better, faster and stronger
● Use find_by_id (or similar) instead of find_by_xpath
○ IE provides no native XPath-over-HTML solution
Best Practices
● "Tag" parts of your feature file
● Gherkin common mistakes
○ Using absolute values instead of configurable values
○ Describing every action instead of a functionality
○ Writing scripts in first person instead of third person
● Good relationship with Frontenders > You will need IDs
● The scenarios should run independently, without any dependencies on other scenarios
References
https://docs.cucumber.io/bdd/overview/
http://www.seleniumhq.org/
https://docs.cucumber.io
https://martinfowler.com/bliki/PageObject.html
https://selenium-python.readthedocs.io/page-objects.html
http://www.seleniumframework.com/python-frameworks/modeling-page-objects/
https://behave.readthedocs.io/en/latest/practical_tips.html
http://www.seleniumframework.com/python-frameworks/complete-the-workflow/
https://www.infoq.com/br/news/2015/07/bdd-cucumber-testing
Thanks
Ad

Recommended

Test Automation Framework with BDD and Cucumber
Test Automation Framework with BDD and Cucumber
Rhoynar Software Consulting
 
Introduction & Manual Testing
Introduction & Manual Testing
VenkateswaraRao Siddabathula
 
BDD with Cucumber
BDD with Cucumber
Knoldus Inc.
 
Software Testing 101
Software Testing 101
QA Hannah
 
Introduction to Bdd and cucumber
Introduction to Bdd and cucumber
Nibu Baby
 
What Is Cucumber?
What Is Cucumber?
QATestLab
 
Types of Software Testing | Edureka
Types of Software Testing | Edureka
Edureka!
 
Automation test framework with cucumber – BDD
Automation test framework with cucumber – BDD
123abcda
 
Automated Testing vs Manual Testing
Automated Testing vs Manual Testing
Directi Group
 
An introduction to Behavior-Driven Development (BDD)
An introduction to Behavior-Driven Development (BDD)
Suman Guha
 
Introduction to Selenium Web Driver
Introduction to Selenium Web Driver
Return on Intelligence
 
Automated testing with Cypress
Automated testing with Cypress
Yong Shean Chong
 
Apache jMeter
Apache jMeter
NexThoughts Technologies
 
Cypress - Best Practices
Cypress - Best Practices
Brian Mann
 
Performance testing jmeter
Performance testing jmeter
Bhojan Rajan
 
Presentation on Apache Jmeter
Presentation on Apache Jmeter
Sabitri Gaire
 
Test Automation
Test Automation
nikos batsios
 
Cucumber presenation
Cucumber presenation
Oussama BEN WAFI
 
Manual testing ppt
Manual testing ppt
Santosh Maranabasari
 
Unit tests & TDD
Unit tests & TDD
Dror Helper
 
Espresso testing
Espresso testing
vodqancr
 
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testing
Roman Liubun
 
How To Write A Test Case In Software Testing | Edureka
How To Write A Test Case In Software Testing | Edureka
Edureka!
 
Automated Test Framework with Cucumber
Automated Test Framework with Cucumber
Ramesh Krishnan Ganesan
 
Testing concepts ppt
Testing concepts ppt
Rathna Priya
 
Test automation - What? Why? How?
Test automation - What? Why? How?
Anand Bagmar
 
Espresso
Espresso
kanthivel
 
Softwaretesting
Softwaretesting
nazeer pasha
 
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
Ho Chi Minh City Software Testing Club
 
Ruby onrails cucumber-rspec-capybara
Ruby onrails cucumber-rspec-capybara
Bindesh Vijayan
 

More Related Content

What's hot (20)

Automated Testing vs Manual Testing
Automated Testing vs Manual Testing
Directi Group
 
An introduction to Behavior-Driven Development (BDD)
An introduction to Behavior-Driven Development (BDD)
Suman Guha
 
Introduction to Selenium Web Driver
Introduction to Selenium Web Driver
Return on Intelligence
 
Automated testing with Cypress
Automated testing with Cypress
Yong Shean Chong
 
Apache jMeter
Apache jMeter
NexThoughts Technologies
 
Cypress - Best Practices
Cypress - Best Practices
Brian Mann
 
Performance testing jmeter
Performance testing jmeter
Bhojan Rajan
 
Presentation on Apache Jmeter
Presentation on Apache Jmeter
Sabitri Gaire
 
Test Automation
Test Automation
nikos batsios
 
Cucumber presenation
Cucumber presenation
Oussama BEN WAFI
 
Manual testing ppt
Manual testing ppt
Santosh Maranabasari
 
Unit tests & TDD
Unit tests & TDD
Dror Helper
 
Espresso testing
Espresso testing
vodqancr
 
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testing
Roman Liubun
 
How To Write A Test Case In Software Testing | Edureka
How To Write A Test Case In Software Testing | Edureka
Edureka!
 
Automated Test Framework with Cucumber
Automated Test Framework with Cucumber
Ramesh Krishnan Ganesan
 
Testing concepts ppt
Testing concepts ppt
Rathna Priya
 
Test automation - What? Why? How?
Test automation - What? Why? How?
Anand Bagmar
 
Espresso
Espresso
kanthivel
 
Softwaretesting
Softwaretesting
nazeer pasha
 
Automated Testing vs Manual Testing
Automated Testing vs Manual Testing
Directi Group
 
An introduction to Behavior-Driven Development (BDD)
An introduction to Behavior-Driven Development (BDD)
Suman Guha
 
Automated testing with Cypress
Automated testing with Cypress
Yong Shean Chong
 
Cypress - Best Practices
Cypress - Best Practices
Brian Mann
 
Performance testing jmeter
Performance testing jmeter
Bhojan Rajan
 
Presentation on Apache Jmeter
Presentation on Apache Jmeter
Sabitri Gaire
 
Unit tests & TDD
Unit tests & TDD
Dror Helper
 
Espresso testing
Espresso testing
vodqancr
 
Karate - powerful and simple framework for REST API automation testing
Karate - powerful and simple framework for REST API automation testing
Roman Liubun
 
How To Write A Test Case In Software Testing | Edureka
How To Write A Test Case In Software Testing | Edureka
Edureka!
 
Testing concepts ppt
Testing concepts ppt
Rathna Priya
 
Test automation - What? Why? How?
Test automation - What? Why? How?
Anand Bagmar
 

Similar to Writing automation tests with python selenium behave pageobjects (20)

A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
Ho Chi Minh City Software Testing Club
 
Ruby onrails cucumber-rspec-capybara
Ruby onrails cucumber-rspec-capybara
Bindesh Vijayan
 
Browser-level testing
Browser-level testing
Martin Kleppmann
 
Testing Testing everywhere
Testing Testing everywhere
Antonio Robres Turon
 
Automation with Selenium Presented by Quontra Solutions
Automation with Selenium Presented by Quontra Solutions
Quontra Solutions
 
Getting Started with Test Automation: Introduction to Cucumber with Lapis Lazuli
Getting Started with Test Automation: Introduction to Cucumber with Lapis Lazuli
Rebecca Eloise Hogg
 
Selenium Tips & Tricks, presented at the Tel Aviv Selenium Meetup
Selenium Tips & Tricks, presented at the Tel Aviv Selenium Meetup
Dave Haeffner
 
Selenium WebDriver
Selenium WebDriver
Yuriy Bezgachnyuk
 
Green Lantern Framework with Selenium IDE
Green Lantern Framework with Selenium IDE
Srilu Balla
 
Automation Zaman Now
Automation Zaman Now
Ibnu Fajar Yunardi
 
Make Everyone a Tester: Natural Language Acceptance Testing
Make Everyone a Tester: Natural Language Acceptance Testing
Patrick Reagan
 
Page Object Model and Implementation in Selenium
Page Object Model and Implementation in Selenium
Zoe Gilbert
 
Automated Acceptance Testing from Scratch
Automated Acceptance Testing from Scratch
Excella
 
Selenium.pptx
Selenium.pptx
Pandiya Rajan
 
Making Watir and Cucumber an efficient tool for Web UI Automation
Making Watir and Cucumber an efficient tool for Web UI Automation
Ruslan Strazhnyk
 
One to rule them all
One to rule them all
Antonio Robres Turon
 
Scraping recalcitrant web sites with Python & Selenium
Scraping recalcitrant web sites with Python & Selenium
Roger Barnes
 
Continuous integration using thucydides(bdd) with selenium
Continuous integration using thucydides(bdd) with selenium
Khyati Sehgal
 
#42 green lantern framework
#42 green lantern framework
Srilu Balla
 
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
vodQA
 
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
A Universal Automation Framework based on BDD Cucumber and Ruby on Rails - Ph...
Ho Chi Minh City Software Testing Club
 
Ruby onrails cucumber-rspec-capybara
Ruby onrails cucumber-rspec-capybara
Bindesh Vijayan
 
Automation with Selenium Presented by Quontra Solutions
Automation with Selenium Presented by Quontra Solutions
Quontra Solutions
 
Getting Started with Test Automation: Introduction to Cucumber with Lapis Lazuli
Getting Started with Test Automation: Introduction to Cucumber with Lapis Lazuli
Rebecca Eloise Hogg
 
Selenium Tips & Tricks, presented at the Tel Aviv Selenium Meetup
Selenium Tips & Tricks, presented at the Tel Aviv Selenium Meetup
Dave Haeffner
 
Green Lantern Framework with Selenium IDE
Green Lantern Framework with Selenium IDE
Srilu Balla
 
Make Everyone a Tester: Natural Language Acceptance Testing
Make Everyone a Tester: Natural Language Acceptance Testing
Patrick Reagan
 
Page Object Model and Implementation in Selenium
Page Object Model and Implementation in Selenium
Zoe Gilbert
 
Automated Acceptance Testing from Scratch
Automated Acceptance Testing from Scratch
Excella
 
Making Watir and Cucumber an efficient tool for Web UI Automation
Making Watir and Cucumber an efficient tool for Web UI Automation
Ruslan Strazhnyk
 
Scraping recalcitrant web sites with Python & Selenium
Scraping recalcitrant web sites with Python & Selenium
Roger Barnes
 
Continuous integration using thucydides(bdd) with selenium
Continuous integration using thucydides(bdd) with selenium
Khyati Sehgal
 
#42 green lantern framework
#42 green lantern framework
Srilu Balla
 
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
Comprehensive Browser Automation Solution using Groovy, WebDriver & Obect Model
vodQA
 
Ad

Recently uploaded (20)

EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Ad

Writing automation tests with python selenium behave pageobjects

Editor's Notes

  • #5: Testes Funcionais: Resumidamente verificar se a aplicação está apta a realizar as funções na qual foi desenvolvida para fazer. Ilustrar com exemplos sobre testes repetidos, quebrar features anteriores, CI.
  • #7: Usar a linguagem que se sentir mais confortável, que o time dominar, ou que tenha uma facil rampa de aprendizado
  • #11: encapsular em cada classe os atributos e métodos, como campos e ações de cada pagina.