0
0
PyTesttesting~8 mins

Command-line options in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Command-line options
Folder Structure
project-root/
├── tests/
│   ├── test_example.py
│   └── test_login.py
├── conftest.py
├── pytest.ini
├── requirements.txt
└── README.md
  
Test Framework Layers
  • Tests: Located in tests/ folder, contains test files like test_example.py.
  • Fixtures & Hooks: Defined in conftest.py for setup and teardown, shared resources.
  • Configuration: pytest.ini file to set default command-line options and test discovery rules.
  • Utilities: Helper functions or modules can be added as needed for reusable code.
Configuration Patterns

Use pytest.ini to define default command-line options and customize test runs:

[pytest]
addopts = -v --maxfail=2 --tb=short
markers =
    smoke: Quick smoke tests
    regression: Full regression tests
  

Command-line options examples:

  • pytest -v: verbose output
  • pytest -k "login and not slow": run tests matching expression
  • pytest --maxfail=1: stop after first failure
  • pytest --tb=short: shorter traceback on failure

Use conftest.py to add custom command-line options with pytest_addoption hook.

# conftest.py
import pytest

def pytest_addoption(parser):
    parser.addoption(
        "--env",
        action="store",
        default="dev",
        help="Environment to run tests against: dev, staging, prod"
    )

@pytest.fixture
def env(request):
    return request.config.getoption("--env")
  
Test Reporting and CI/CD Integration
  • Use built-in pytest options like --junitxml=report.xml to generate XML reports for CI tools.
  • Integrate with CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI) by running pytest with desired command-line options.
  • Example GitHub Actions step:
- name: Run tests
  run: |
    pytest -v --junitxml=results.xml
  

This allows CI to parse test results and show pass/fail status.

Best Practices
  1. Define common command-line options in pytest.ini to keep test runs consistent.
  2. Use conftest.py to add custom options for flexibility (e.g., environment selection).
  3. Keep command-line options simple and meaningful to avoid confusion.
  4. Use markers and -k expressions to select specific tests easily.
  5. Integrate reporting options with CI/CD for automated feedback.
Self Check

Where in this framework structure would you add a new custom command-line option to select a browser type for tests?

Key Result
Use pytest.ini for default options and conftest.py to add custom command-line options for flexible test runs.