0
0
PyTesttesting~5 mins

caplog for log messages in PyTest - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of caplog in pytest?

caplog is used to capture log messages during test execution. It helps verify that the expected logs are generated by the code under test.

Click to reveal answer
beginner
How do you access captured log messages using caplog?

You can access captured logs via caplog.records for log records or caplog.text for the full log output as a string.

Click to reveal answer
intermediate
How can you set the log level when using caplog in a test?

Use caplog.set_level("LEVEL") to set the minimum log level to capture, for example caplog.set_level("INFO").

Click to reveal answer
beginner
Write a simple pytest test snippet using caplog to check if a warning log message was emitted.
def test_warning_log(caplog):
    import logging
    logger = logging.getLogger()
    with caplog.at_level(logging.WARNING):
        logger.warning("This is a warning")
    assert "This is a warning" in caplog.text
Click to reveal answer
beginner
Why is capturing logs useful in automated tests?

Capturing logs helps confirm that the code behaves as expected internally, especially for warnings, errors, or important info messages, improving test coverage and debugging.

Click to reveal answer
What does caplog.records provide in pytest?
AThe current log level setting
BThe full log output as a single string
CA list of log record objects captured during the test
DThe number of log messages emitted
How do you change the log level to capture only warnings and above with caplog?
Acaplog.set_level("INFO")
Bcaplog.set_level("WARNING")
Ccaplog.set_level("DEBUG")
Dcaplog.set_level("ERROR")
Which pytest fixture is used to capture log messages?
Acaplog
Blogcapture
Clogfixture
Dcapturelog
What is the best way to check if a specific log message was emitted in a test?
AAssert the message is in <code>caplog.text</code>
BPrint logs and check manually
CUse <code>print()</code> statements
DCheck the console output after test
What does caplog.at_level(logging.WARNING) do?
AFilters out WARNING messages
BDisables log capturing
CSets the global log level to WARNING permanently
DTemporarily sets the log capture level to WARNING within the block
Explain how to use caplog in pytest to verify that a specific log message was generated.
Think about capturing logs and checking their content.
You got /5 concepts.
    Describe why capturing logs with caplog is helpful in automated testing.
    Logs tell us what happened inside the code.
    You got /4 concepts.