0
0
PyTesttesting~8 mins

Given-When-Then pattern in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Given-When-Then pattern
Folder Structure
project-root/
├── tests/
│   ├── test_login.py
│   ├── test_checkout.py
│   └── conftest.py
├── pages/
│   ├── login_page.py
│   └── checkout_page.py
├── utils/
│   ├── helpers.py
│   └── fixtures.py
├── configs/
│   └── config.yaml
├── reports/
│   └── latest_report.html
└── pytest.ini
  
Test Framework Layers
  • Test Layer: Contains test files in tests/ using Given-When-Then style for clarity.
  • Page Objects Layer: In pages/, classes represent pages with methods for actions and verifications.
  • Utilities Layer: Helper functions and fixtures in utils/ to support tests and setup.
  • Configuration Layer: Environment and test settings in configs/ and pytest.ini.
  • Reporting Layer: Test results saved in reports/ for review and CI/CD integration.
Configuration Patterns

Use pytest.ini to set default options like markers and test paths.

Store environment-specific data (URLs, credentials) in configs/config.yaml. Load this data in fixtures.

Use conftest.py to define fixtures that provide test setup, like browser drivers or test data.

Example snippet to load config in conftest.py:

import yaml
import pytest

@pytest.fixture(scope="session")
def config():
    with open("configs/config.yaml") as f:
        return yaml.safe_load(f)
  
Test Reporting and CI/CD Integration
  • Use pytest built-in options like --junitxml=reports/report.xml to generate XML reports.
  • Integrate with CI tools (GitHub Actions, Jenkins) to run tests on code changes and publish reports.
  • Use plugins like pytest-html to create readable HTML reports saved in reports/.
  • Reports help quickly see which Given-When-Then steps passed or failed.
Framework Design Principles
  1. Clear Separation: Keep Given (setup), When (action), Then (assertion) steps distinct in tests for readability.
  2. Reusable Fixtures: Use pytest fixtures to provide common setup (Given) to avoid repetition.
  3. Page Object Model: Encapsulate page interactions to keep When steps clean and maintainable.
  4. Descriptive Assertions: Write Then steps with clear assertions that explain expected outcomes.
  5. Configurable Environments: Use config files and fixtures to run tests in different environments without code changes.
Self Check

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

Key Result
Organize pytest tests using Given-When-Then steps with clear layers: tests, page objects, utilities, configs, and reports.