Framework Mode - Asserting log messages
Folder Structure
tests/ ├── test_example.py # Test files ├── conftest.py # Fixtures and hooks utils/ ├── logger.py # Logger setup and helpers pytest.ini # Pytest configuration requirements.txt # Dependencies
tests/ ├── test_example.py # Test files ├── conftest.py # Fixtures and hooks utils/ ├── logger.py # Logger setup and helpers pytest.ini # Pytest configuration requirements.txt # Dependencies
[pytest] log_cli = true log_cli_level = INFO
log_cli=true.pytest-html to generate reports including captured logs.caplog fixture to capture and assert log messages in tests.Where in this framework structure would you add a new test that verifies a warning log message is generated when invalid input is given?
caplog fixture in pytest when testing log messages?caplogcaplog fixture is designed to capture log messages during pytest test runs.caplog captures logs [OK]caplog in pytest?caplog.set_level(logging.WARNING) sets the capture level to WARNING, capturing WARNING and above.import logging
def test_log_message(caplog):
with caplog.at_level(logging.ERROR):
logging.error('Error occurred')
assert 'Error occurred' in caplog.textcaplog.text, which contains all captured logs as text.caplog to assert a log message:
import logging
def test_info_log(caplog):
logging.info('Info issued')
assert 'Info issued' in caplog.textcaplog to capture INFO level logs, so no logs are captured.caplog.text is empty and the assertion fails.caplog assertion correctly verifies this?caplog.records is a list of log record objects with attributes like message and levelname.Pass the test and this pattern moves unknown