Selenium Python BDD
- Home
- Selenium Python BDD
Using Selenium with Python and BDD is a great choice for building human-readable and maintainable test automation suites. The most common approach is to use:
Tech Stack
Tool | Purpose |
---|---|
Selenium | Browser automation |
Behave | BDD framework using Gherkin |
Python | Language for writing test logic |
ChromeDriver | WebDriver for Chrome |
1. Installation
Install the required packages via pip:
pip install selenium behave
Download and place the appropriate chromedriver
in your system path or working directory.
2. Project Structure
selenium_bdd_project/
│
├── features/
│ ├── login.feature
│ ├── steps/
│ │ └── login_steps.py
│ └── environment.py # Optional setup/teardown hooks
└── drivers/
└── chromedriver.exe
3. Feature File (features/login.feature
)
Feature: Login functionality
Scenario: Successful login
Given I open the login page
When I enter valid credentials
And I press the login button
Then I should be redirected to the homepage
4. Step Definitions (features/steps/login_steps.py
)
from selenium import webdriver
from behave import given, when, then
from selenium.webdriver.common.by import By
@given(‘I open the login page’)
def step_impl(context):
context.driver = webdriver.Chrome()
context.driver.get(“https://example.com/login”)
@when(‘I enter valid credentials’)
def step_impl(context):
context.driver.find_element(By.ID, “username”).send_keys(“testuser”)
context.driver.find_element(By.ID, “password”).send_keys(“testpass”)
@when(‘I press the login button’)
def step_impl(context):
context.driver.find_element(By.ID, “login”).click()
@then(‘I should be redirected to the homepage’)
def step_impl(context):
assert context.driver.find_element(By.ID, “logout”).is_displayed()
context.driver.quit()
5. Running the Tests
From the project root:
behave
Reporting (Optional)
Use
behave-html-formatter
orallure-behave
for HTML reports.Example:
pip install allure-behave
behave -f allure_behave.formatter:AllureFormatter -o reports/ features/