0
0
PyTesttesting~8 mins

PyTest installation (pip install pytest) - Framework Patterns

Choose your learning style9 modes available
Framework Mode - PyTest installation (pip install pytest)
Folder Structure
project-root/
├── tests/
│   ├── test_example.py
│   └── __init__.py
├── src/
│   └── app_code.py
├── conftest.py
├── pytest.ini
└── requirements.txt
    

This is a simple PyTest project structure. tests/ holds test files. conftest.py contains shared fixtures. pytest.ini configures PyTest settings.

Test Framework Layers
  • Test Layer: Test files inside tests/ folder, e.g., test_example.py with test functions.
  • Fixtures Layer: conftest.py holds reusable setup/teardown code called fixtures.
  • Application Code Layer: Source code under src/ folder, separated from tests.
  • Configuration Layer: pytest.ini or pyproject.toml for PyTest options.
  • Dependencies Layer: requirements.txt lists packages like PyTest.
Configuration Patterns

Use pytest.ini to configure PyTest options like test paths and markers:

[pytest]
testpaths = tests
markers =
    smoke: quick smoke tests
    regression: full regression suite
    

Manage environments and credentials using environment variables or separate config files loaded in fixtures.

Example: Use os.environ in conftest.py to read sensitive data safely.

Test Reporting and CI/CD Integration
  • Use PyTest built-in options like --junitxml=report.xml to generate XML reports.
  • Integrate with CI/CD tools (GitHub Actions, Jenkins) to run tests automatically on code changes.
  • Use plugins like pytest-html for readable HTML reports.
  • Example GitHub Actions step to run tests:
    - name: Run PyTest
      run: |
        pip install -r requirements.txt
        pytest --junitxml=report.xml
            
Best Practices
  • Keep tests and source code separate for clarity and maintainability.
  • Use conftest.py for shared fixtures to avoid duplication.
  • Use pytest.ini to centralize test configuration and markers.
  • Use virtual environments to isolate dependencies and avoid conflicts.
  • Write simple, independent test functions that can run in any order.
Self Check

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

Key Result
Organize PyTest projects with separate tests, fixtures, config, and use virtual environments for clean dependency management.