pytest-project/
├── tests/
│ ├── test_example.py
│ └── test_login.py
├── conftest.py
├── pytest.ini
└── requirements.txt
Addopts for default options in PyTest - Framework Patterns
- Tests: Located in
tests/folder, contains test scripts liketest_example.py. - Fixtures & Hooks: Defined in
conftest.pyfor setup and teardown logic shared across tests. - Configuration:
pytest.inifile holds default options usingaddoptsto customize pytest runs. - Dependencies:
requirements.txtlists Python packages needed for testing.
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.
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.
- Use
addoptsinpytest.inito set common options like verbosity and failure limits. - Keep
pytest.iniin the project root for easy discovery by pytest. - Include reporting options in
addoptsfor automated test reports in CI/CD. - Avoid putting sensitive info in
addopts; use environment variables orconftest.pyfixtures for secrets. - Document the purpose of each option in comments inside
pytest.inifor team clarity.
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.