0
0
PyTesttesting~8 mins

Conftest.py purpose in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Conftest.py purpose
Folder Structure of a Pytest Framework
project-root/
├── tests/
│   ├── test_login.py
│   ├── test_checkout.py
│   └── conftest.py
├── src/
│   └── app_code.py
├── requirements.txt
└── pytest.ini
  
Test Framework Layers in Pytest
  • Tests: Test scripts inside tests/ folder, e.g., test_login.py.
  • Fixtures (conftest.py): Shared setup and teardown code for tests, reusable across multiple test files.
  • Application Code: The actual code under test, usually in src/ or similar.
  • Configuration: Files like pytest.ini to configure pytest behavior.
Configuration Patterns with conftest.py

conftest.py is used to define fixtures that can be shared across multiple test files without importing them explicitly. It helps manage:

  • Environment setup (e.g., database connections, test data)
  • Browser or driver setup for UI tests
  • Reusable test data or mocks

Example snippet inside conftest.py:

import pytest

@pytest.fixture(scope="session")
def browser():
    print("Setup browser")
    yield "ChromeDriver"
    print("Teardown browser")
Test Reporting and CI/CD Integration

Pytest integrates easily with reporting tools and CI/CD pipelines:

  • Use pytest --junitxml=report.xml to generate XML reports readable by CI tools.
  • Plugins like pytest-html create human-friendly HTML reports.
  • conftest.py can include hooks to customize reporting or logging.
  • CI tools (GitHub Actions, Jenkins) run pytest commands and collect reports automatically.
Best Practices for Using conftest.py
  • Keep fixtures in conftest.py to avoid repetitive code in tests.
  • Use appropriate fixture scopes (function, module, session) to optimize setup time.
  • Do not import conftest.py manually; pytest discovers it automatically.
  • Organize multiple conftest.py files in subfolders for modular fixture management.
  • Keep fixtures simple and focused on setup/teardown tasks.
Self Check Question

Where in this folder structure would you add a new fixture to initialize a database connection for all tests?

Key Result
Use conftest.py to share reusable setup and teardown code (fixtures) across pytest tests without imports.