Migrate a Selenium 3 Suite
Why This Matters
Many teams don’t start from an empty project. They have a suite that grew over years: find_element_by_id everywhere, webdriver-manager in the fixtures, time.sleep(2) wherever a page was slow once. Selenium 4 removed the old APIs, so upgrading the selenium package breaks the suite overnight; and the sleeps make it slow and flaky even when it runs.
The migrator agent upgrades such a suite file by file, without changing what the tests check. It uses the same rule check as the generator, the same healer tools, and the same heal policy, so a migration is just a very disciplined heal.
What you will learn
- How to scan an existing suite with
selenium_rules_check - The migrator’s workflow: scan, baseline, migrate one file at a time, report
- A migration, before and after, line by line
- What the migrator must never do
- The limits of a file-by-file check
A legacy suite
Two files, typical of a suite written for Selenium 3:
# tests/conftest.py
import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
@pytest.fixture(scope="session")
def driver():
caps = DesiredCapabilities.CHROME.copy()
options = webdriver.ChromeOptions()
options.headless = True
drv = webdriver.Chrome(executable_path=ChromeDriverManager().install(), desired_capabilities=caps, options=options)
drv.implicitly_wait(10)
yield drv
drv.quit()
# tests/test_shop.py
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
SHOP = "https://practiceautomatedtesting.com/shopping"
def test_search_keyboard(driver):
driver.get(SHOP)
driver.find_element_by_css_selector('[data-testid="search-input"]').send_keys("keyboard")
time.sleep(2)
heading = driver.find_element_by_xpath("/html/body/div[1]/main/div/div[2]/div[3]/h2").text
assert "1 products" in heading
def test_add_to_cart(driver):
driver.get(SHOP)
driver.find_element_by_css_selector('[data-testid="add-to-cart-2"]').click()
WebDriverWait(driver, 10).until(
EC.text_to_be_present_in_element((By.CSS_SELECTOR, '[data-testid="cart-button"]'), "1 items"))
Step 1: scan
Check the tests in tests/ with selenium_rules_check.
The scan reads every Selenium or WebdriverIO file (Python, Java, C#, JavaScript/TypeScript, Ruby, Robot Framework) and changes nothing. Real output for these two files:
Scanned tests: 2 Selenium/WebdriverIO file(s) checked, 2 with findings: 11 error(s), 2 warning(s).
By rule:
3 × ERROR [no-desired-capabilities] No DesiredCapabilities or raw capability maps. Use the browser's Options class (ChromeOptions, FirefoxOptions, ...).
3 × ERROR [no-selenium3-api] Selenium 3 API: removed in Selenium 4. Use find_element(By.ID, ...) / findElement(By.id(...)) / FindElement(By.Id(...)) and switch_to.alert.
2 × ERROR [no-driver-manager] No third-party driver managers. Selenium Manager (built into Selenium 4.6+) finds, downloads and caches the driver.
1 × ERROR [old-headless] Old headless API. Use the Options argument "--headless=new".
1 × ERROR [no-driver-path] Don't hard-code driver paths. Selenium Manager resolves the driver.
1 × warn [no-implicit-wait] Prefer explicit waits. Never mix implicit and explicit waits in the same session.
1 × ERROR [no-sleep] No sleeping in tests. Wait explicitly for the condition the next line depends on (clickable, text present, spinner gone).
1 × warn [no-absolute-xpath] Absolute XPath is fragile. Prefer id or name, then CSS on a stable attribute such as data-testid.
By file (most errors first):
conftest.py (selenium-python-pytest): 7 error(s), 1 warning(s)
ERROR line 3 [no-driver-manager] from webdriver_manager.chrome import ChromeDriverManager
ERROR line 4 [no-desired-capabilities] from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
ERROR line 9 [no-desired-capabilities] caps = DesiredCapabilities.CHROME.copy()
ERROR line 11 [old-headless] options.headless = True
ERROR line 12 [no-driver-manager] drv = webdriver.Chrome(executable_path=ChromeDriverManager().install(), ...)
ERROR line 12 [no-driver-path] drv = webdriver.Chrome(executable_path=ChromeDriverManager().install(), ...)
ERROR line 12 [no-desired-capabilities] drv = webdriver.Chrome(executable_path=ChromeDriverManager().install(), ...)
warn line 13 [no-implicit-wait] drv.implicitly_wait(10)
test_shop.py (selenium-python-pytest): 4 error(s), 1 warning(s)
ERROR line 12 [no-selenium3-api] driver.find_element_by_css_selector('[data-testid="search-input"]').send_keys("keyboard")
ERROR line 13 [no-sleep] time.sleep(2)
ERROR line 14 [no-selenium3-api] heading = driver.find_element_by_xpath("/html/body/div[1]/main/div/div[2]/div[3]/h2").text
warn line 14 [no-absolute-xpath] heading = driver.find_element_by_xpath("/html/body/div[1]/main/div/div[2]/div[3]/h2").text
ERROR line 20 [no-selenium3-api] driver.find_element_by_css_selector('[data-testid="add-to-cart-2"]').click()
Rules: https://www.selenium.dev/documentation/ai_agents/. Fix a file with healer_fix_test, which refuses code that still breaks them.
The “by rule” part tells you how big the job is; the “by file” part, most errors first, is the work list.
One thing the scan doesn’t see
The implicit wait in conftest.py is only a warning. But test_shop.py uses WebDriverWait, so in the running session implicit and explicit waits are mixed, which is an error (lesson 13). The scan checks each file on its own, and the mix is spread over two files. You know your suite’s structure; the scan doesn’t. Fixtures and base classes are where such cross-file problems live, which is why the migrator starts there.
Step 2: baseline
Before changing anything, the migrator runs the suite with healer_run_tests and notes what passes and what already fails. The rule for the whole migration: a test that passed before must pass after; a test that failed before is reported, not hidden. With a recent selenium package installed, a Selenium 3 suite often doesn’t even start; then the baseline is “everything fails”, and the migration has to make it start.
Step 3: one file at a time
The migrator starts with shared code (fixtures, base classes, driver factories, page objects), then the tests. For each file it rewrites only the outdated patterns, keeps the steps, data, assertions and names, saves with healer_fix_test (which keeps a .bak and refuses code that still breaks a rule), and runs the file, several times for anything that waits.
The migrated fixture:
# tests/conftest.py
import pytest
from selenium import webdriver
@pytest.fixture
def driver():
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
drv = webdriver.Chrome(options=options) # Selenium Manager finds the driver
yield drv
drv.quit()
Gone: the driver manager, the driver path, DesiredCapabilities, the old headless flag and the implicit wait. Also changed: scope="session" is gone, so every test gets a fresh browser, as Selenium’s rules ask. That is a behaviour change (slower, more independent); a good migrator mentions it in its report instead of doing it silently.
The migrated tests:
# tests/test_shop.py
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
SHOP = "https://practiceautomatedtesting.com/shopping"
def test_search_keyboard(driver):
driver.get(SHOP)
driver.find_element(By.CSS_SELECTOR, '[data-testid="search-input"]').send_keys("keyboard")
WebDriverWait(driver, 10).until(
EC.text_to_be_present_in_element((By.CSS_SELECTOR, '[data-testid="results-count"]'), "1"))
heading = driver.find_element(By.XPATH, "//h2[contains(., 'Search Results')]").text
assert "1 products" in heading
def test_add_to_cart(driver):
driver.get(SHOP)
driver.find_element(By.CSS_SELECTOR, '[data-testid="add-to-cart-2"]').click()
WebDriverWait(driver, 10).until(
EC.text_to_be_present_in_element((By.CSS_SELECTOR, '[data-testid="cart-button"]'), "1 items"))
The sleep(2) became a wait for the condition the next line needs: the results count shows 1. The absolute XPath became a text-based one (checked live with browser_generate_locator or capture_page). The assertion "1 products" in heading is untouched.
Scanning again:
Scanned tests: 2 Selenium/WebdriverIO file(s) checked, 0 with findings: 0 error(s), 0 warning(s).
Everything follows the rules: nothing to migrate.
The heal policy during a migration
Every save goes through healer_fix_test, so the profile’s heal policy applies. For test_shop.py the classifier labels the changes as three locator changes (the Selenium 3 finders and the XPath), two waits (added), one import (time removed) and one other (the removed sleep). Not a single assertion: that is what a good migration looks like. Under guided it saves without asking; under strict the removed sleep line (“other code”) needs your approval.
Step 4: report
The migrator ends with a report per file: what changed (“3 × find_element_by_ → find_element(By…), sleep(2) → wait for the results count, session fixture → one browser per test”*), the result before and after, and anything left for you: a test that already failed, a real application bug it found. And a final selenium_rules_check: no errors left.
What the migrator must never do
From its own instructions:
- Never change what a test checks to make it pass. If a migrated test fails because the application is wrong, it reports it.
- Don’t hide failing tests. Tests that failed before the migration are reported as they are.
- Keep the project’s structure, naming and style. No new frameworks or dependencies, except removing driver managers.
- Check the docs first. For an API it isn’t sure of, it reads the current page with
get_selenium_docs. An API that isn’t in the current docs doesn’t exist.
Java, C# and JavaScript suites work the same way. The typical Java changes are new WebDriverWait(driver, 10) → Duration.ofSeconds(10), DesiredCapabilities.chrome() → new ChromeOptions(), and removing System.setProperty("webdriver.chrome.driver", ...) and WebDriverManager. For WebdriverIO the migrator moves to v10: no browser.pause(), no sync mode, toHaveAttribute instead of toHaveAttr.
Exercise
Take this Selenium 3 test and migrate it by hand first, then compare with the migrator:
import time
from selenium import webdriver
def test_login():
driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver")
driver.get("https://the-internet.herokuapp.com/login")
driver.find_element_by_id("username").send_keys("tomsmith")
driver.find_element_by_id("password").send_keys("SuperSecretPassword!")
driver.find_element_by_css_selector("button[type='submit']").click()
time.sleep(3)
assert "You logged into a secure area!" in driver.find_element_by_id("flash").text
driver.quit()
- Which rules does
selenium_rules_checkreport, on which lines? - Write the Selenium 4 version.
- What happens to
driver.quit()when the assertion fails, before and after your migration?
Show suggested answer
- Six errors: line 5
no-driver-path(executable_path=); lines 7, 8, 9 and 11no-selenium3-api; line 10no-sleep. (import timeitself is not flagged; the sleep call is.) - (Better still: move the driver into a fixture, as in lesson 7. The assertion is unchanged.)
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait def test_login(): driver = webdriver.Chrome() try: driver.get("https://the-internet.herokuapp.com/login") driver.find_element(By.ID, "username").send_keys("tomsmith") driver.find_element(By.ID, "password").send_keys("SuperSecretPassword!") driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click() flash = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "flash"))) assert "You logged into a secure area!" in flash.text finally: driver.quit() - Before: a failing assertion skips
driver.quit(), and a browser stays open, which piles up in CI. After:finallyalways quits.
Exam-style questions
1. What is the first step of the migrator agent?
- A. Rewrite all files at once
- B. Scan the suite with
selenium_rules_checkand show the work list - C. Delete failing tests
- D. Upgrade the selenium package
Show answer
2. A test passed before the migration and fails after it. What should the migrator do?
- A. Change the assertion so it passes
- B. Debug and fix the migration, not the assertion
- C. Skip the test
- D. Revert the whole suite
Show answer
3. conftest.py has implicitly_wait(10) and the tests use WebDriverWait. What does selenium_rules_check report for the implicit wait?
- A. An error: the waits are mixed
- B. A warning: the check is per file, and
conftest.pyitself has no explicit wait - C. Nothing
- D. An error in every test file