Bird
Raised Fist0
Selenium Pythontesting~8 mins

Base page class in Selenium Python - Framework Patterns

Choose your learning style10 modes available
Framework Mode - Base page class
Folder Structure
selenium-python-project/
├── pages/
│   ├── base_page.py       # Base page class with common methods
│   ├── login_page.py      # Login page object
│   └── dashboard_page.py  # Dashboard page object
├── tests/
│   ├── test_login.py      # Tests for login functionality
│   └── test_dashboard.py  # Tests for dashboard
├── utils/
│   └── helpers.py         # Utility functions
├── config/
│   └── config.yaml        # Environment and browser settings
├── conftest.py            # Pytest fixtures for setup/teardown
└── requirements.txt       # Dependencies
    
Test Framework Layers
  • Driver Layer: Manages browser setup and teardown using Selenium WebDriver.
  • Page Objects Layer: Contains page classes representing web pages. BasePage class holds common methods like click, input text, wait, and is inherited by specific page classes.
  • Tests Layer: Contains test scripts using pytest that call page object methods to perform actions and assertions.
  • Utilities Layer: Helper functions for common tasks like reading config, logging, or waiting.
  • Configuration Layer: Holds environment variables, browser options, and credentials in config files.
Configuration Patterns

Use a config.yaml file to store environment URLs, browser types, and user credentials. Load this config in conftest.py to provide fixtures that initialize WebDriver with desired browser and navigate to the correct URL.

Example config.yaml snippet:

environments:
  dev:
    url: "https://dev.example.com"
  prod:
    url: "https://example.com"
browser: chrome
credentials:
  username: "testuser"
  password: "password123"
    

In conftest.py, read this config and create a fixture that sets up the driver accordingly.

Test Reporting and CI/CD Integration
  • Use pytest with plugins like pytest-html or allure-pytest to generate readable HTML or Allure reports after test runs.
  • Integrate tests into CI/CD pipelines (e.g., GitHub Actions, Jenkins) to run tests automatically on code push.
  • Configure reports to be archived or published as build artifacts for easy access.
  • Use pytest markers to categorize tests (smoke, regression) for selective runs.
Best Practices for Base Page Class Framework
  1. Single Responsibility: BasePage should only have common reusable methods like click, input, wait, and navigation helpers.
  2. Inheritance: Specific page classes inherit from BasePage to avoid code duplication and keep tests clean.
  3. Explicit Waits: Use Selenium explicit waits in BasePage methods to handle dynamic page elements reliably.
  4. Locator Encapsulation: Keep locators private in page classes and expose only meaningful actions to tests.
  5. Readable Methods: Name methods clearly to describe user actions, improving test readability.
Self Check

Where in this folder structure would you add a new page object class for the "Profile" page?

Key Result
Use a BasePage class to hold common Selenium actions, inherited by specific page classes for clean, reusable test code.

Practice

(1/5)
1. What is the main purpose of a BasePage class in Selenium Python testing?
easy
A. To group common web page actions and locators for reuse
B. To store test data for different test cases
C. To define the browser settings and capabilities
D. To generate test reports automatically

Solution

  1. Step 1: Understand the role of BasePage

    The BasePage class is designed to hold common actions and locators shared by multiple page classes.
  2. Step 2: Compare with other options

    Storing test data, browser settings, or generating reports are not responsibilities of BasePage.
  3. Final Answer:

    To group common web page actions and locators for reuse -> Option A
  4. Quick Check:

    BasePage groups common actions [OK]
Hint: BasePage holds shared page methods and locators [OK]
Common Mistakes:
  • Confusing BasePage with test data storage
  • Thinking BasePage manages browser setup
  • Assuming BasePage creates reports
2. Which of the following is the correct way to define a locator tuple in a BasePage class?
easy
A. submit_button = (By.ID, 'submit')
B. submit_button = ['id', 'submit']
C. submit_button = {'id': 'submit'}
D. submit_button = By.ID('submit')

Solution

  1. Step 1: Recall locator tuple syntax

    Locator tuples use the format (By.<METHOD>, 'value'), e.g., (By.ID, 'submit').
  2. Step 2: Check each option

    submit_button = (By.ID, 'submit') matches the tuple format. The other options use wrong data structures or invalid syntax.
  3. Final Answer:

    submit_button = (By.ID, 'submit') -> Option A
  4. Quick Check:

    Locator tuple = (By.METHOD, 'value') [OK]
Hint: Locator tuples always use parentheses and By constants [OK]
Common Mistakes:
  • Using lists or dicts instead of tuples for locators
  • Calling By.ID as a function
  • Missing parentheses around locator tuple
3. Given this BasePage method, what will page.get_title() return if the browser's current page title is "Welcome Page"?
class BasePage:
    def __init__(self, driver):
        self.driver = driver

    def get_title(self):
        return self.driver.title

page = BasePage(driver)
medium
A. An error because get_title has no return
B. self.driver
C. None
D. "Welcome Page"

Solution

  1. Step 1: Understand get_title method

    The method returns self.driver.title, which is the current page title string.
  2. Step 2: Check given title

    The browser's current page title is "Welcome Page", so the method returns that string.
  3. Final Answer:

    "Welcome Page" -> Option D
  4. Quick Check:

    get_title returns driver.title = "Welcome Page" [OK]
Hint: get_title returns driver.title string [OK]
Common Mistakes:
  • Thinking it returns the driver object
  • Assuming no return means None
  • Confusing method with attribute
4. Identify the error in this BasePage method and how to fix it:
class BasePage:
    def __init__(self, driver):
        self.driver = driver

    def click_element(locator):
        element = self.driver.find_element(*locator)
        element.click()
medium
A. Using find_element instead of find_elements
B. Missing 'self' parameter in click_element method
C. Locator should be a string, not a tuple
D. element.click() should be element.click

Solution

  1. Step 1: Check method parameters

    Instance methods must have 'self' as the first parameter. Here, click_element lacks 'self'.
  2. Step 2: Understand impact

    Without 'self', calling click_element will cause a TypeError because 'self.driver' is undefined.
  3. Final Answer:

    Missing 'self' parameter in click_element method -> Option B
  4. Quick Check:

    Instance methods need 'self' first [OK]
Hint: Always include 'self' as first method parameter [OK]
Common Mistakes:
  • Forgetting 'self' in instance methods
  • Confusing find_element with find_elements
  • Misunderstanding locator types
  • Using method call without parentheses
5. You want to create a BasePage method is_element_visible that returns True if an element is visible and False if not, without raising exceptions. Which is the best way to implement it?
hard
A. Use driver.page_source to search for element HTML string
B. Call find_element and return True without exception handling
C. Use try-except to catch NoSuchElementException and return False if caught
D. Use find_elements and check if list length is greater than zero

Solution

  1. Step 1: Understand element visibility check

    Using find_element raises NoSuchElementException if element not found, so we must handle it.
  2. Step 2: Use try-except for safe check

    Try to find element and check is_displayed(). If exception occurs, return False safely.
  3. Final Answer:

    Use try-except to catch NoSuchElementException and return False if caught -> Option C
  4. Quick Check:

    Try-except handles missing element safely [OK]
Hint: Wrap find_element in try-except to avoid exceptions [OK]
Common Mistakes:
  • Not handling exceptions causing test failure
  • Assuming find_elements always returns visible elements
  • Searching page_source is unreliable and slow
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard