0
0
PyTesttesting~8 mins

Test functions in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Test functions
Folder Structure
tests/
├── test_login.py
├── test_shopping_cart.py
├── test_checkout.py
└── conftest.py

utils/
├── helpers.py
└── data_provider.py

pytest.ini
requirements.txt

This structure keeps all test functions inside the tests/ folder. Each test file groups related test functions. The conftest.py file holds shared fixtures.

Test Framework Layers
  • Test Functions: Simple Python functions starting with test_. Each function tests one behavior.
  • Fixtures: Setup and teardown code shared across tests, defined in conftest.py.
  • Utilities: Helper functions and data providers in utils/ to keep tests clean.
  • Configuration: pytest.ini for pytest settings and environment control.
Configuration Patterns
  • pytest.ini: Configure markers, test paths, and default options.
  • Environment Variables: Use os.environ or pytest plugins to switch environments (dev, staging, prod).
  • Fixtures with Parameters: Use parametrized fixtures to run tests with different browsers or data sets.
  • Secrets Management: Store credentials securely outside the repo, load them in fixtures.
Test Reporting and CI/CD Integration
  • pytest Output: Clear pass/fail results in console with summary.
  • JUnit XML Reports: Use --junitxml=report.xml to generate reports for CI tools.
  • HTML Reports: Plugins like pytest-html create easy-to-read reports with screenshots.
  • CI/CD Integration: Run tests automatically on push using GitHub Actions, GitLab CI, or Jenkins.
Best Practices
  1. One Assertion per Test Function: Keep tests focused and easy to debug.
  2. Descriptive Test Names: Use clear names like test_login_with_valid_credentials.
  3. Use Fixtures for Setup: Avoid repeating setup code inside test functions.
  4. Keep Tests Independent: Each test function should run alone without relying on others.
  5. Use Parametrization: Run the same test function with multiple inputs to cover more cases efficiently.
Self Check

Where would you add a new test function for verifying the user profile update feature in this framework structure?

Key Result
Organize pytest test functions in the tests/ folder with clear naming, fixtures for setup, and utilities for helpers.