0
0
PyTesttesting~8 mins

Addopts for default options in PyTest - Framework Patterns

Choose your learning style9 modes available
Framework Mode - Addopts for default options
Folder Structure
pytest-project/
├── tests/
│   ├── test_example.py
│   └── test_login.py
├── conftest.py
├── pytest.ini
└── requirements.txt
    
Test Framework Layers
  • Tests: Located in tests/ folder, contains test scripts like test_example.py.
  • Fixtures & Hooks: Defined in conftest.py for setup and teardown logic shared across tests.
  • Configuration: pytest.ini file holds default options using addopts to customize pytest runs.
  • Dependencies: requirements.txt lists Python packages needed for testing.
Configuration Patterns

The pytest.ini file uses the addopts setting to specify default command-line options for pytest runs. This helps avoid typing options every time.

[pytest]
addopts = -v --maxfail=2 --tb=short

# Explanation:
# -v : verbose output
# --maxfail=2 : stop after 2 failures
# --tb=short : shorter traceback for failures
    

Use environment variables or separate config files for different environments if needed, but addopts is the main place for default pytest options.

Test Reporting and CI/CD Integration

Default options in addopts can include plugins for reporting, like --junitxml=reports/junit-report.xml to generate XML reports for CI tools.

[pytest]
addopts = -v --maxfail=2 --tb=short --junitxml=reports/junit-report.xml
    

CI/CD pipelines can run pytest without extra flags, relying on pytest.ini defaults. This keeps pipeline scripts simple and consistent.

Best Practices
  • Use addopts in pytest.ini to set common options like verbosity and failure limits.
  • Keep pytest.ini in the project root for easy discovery by pytest.
  • Include reporting options in addopts for automated test reports in CI/CD.
  • Avoid putting sensitive info in addopts; use environment variables or conftest.py fixtures for secrets.
  • Document the purpose of each option in comments inside pytest.ini for team clarity.
Self Check

Question: Where would you add a default option to generate an HTML report automatically after tests run?

Answer: Add the option --html=report.html inside the addopts setting in the pytest.ini file at the project root.

Key Result
Use pytest.ini's addopts to set default command-line options for consistent and simple test runs.