0
0
PyTesttesting~10 mins

Asserting log messages in PyTest - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to capture log messages using pytest.

PyTest
def test_log_capture(caplog):
    with caplog.[1](level="INFO"):
        logger = logging.getLogger()
        logger.info("Hello")
Drag options to blanks, or click blank then click option'
Acapture
Bset_level
Clog
Dat_level
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method that does not exist on caplog.
Trying to capture logs without setting the level.
2fill in blank
medium

Complete the code to assert that a log message contains the expected text.

PyTest
def test_log_message(caplog):
    with caplog.at_level("WARNING"):
        logger = logging.getLogger()
        logger.warning("Disk space low")
    assert "[1]" in caplog.text
Drag options to blanks, or click blank then click option'
Adebug
BDisk space low
Cinfo
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for a log level name instead of the message.
Using a wrong string that does not appear in logs.
3fill in blank
hard

Fix the error in the assertion to check the first captured log record's message.

PyTest
def test_first_log_message(caplog):
    with caplog.at_level("ERROR"):
        logger = logging.getLogger()
        logger.error("Failure occurred")
    assert caplog.records[0].[1] == "Failure occurred"
Drag options to blanks, or click blank then click option'
Amsg
Bmessage
Ctext
Dlog
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'message' instead of 'msg' attribute.
Trying to access a non-existent attribute.
4fill in blank
hard

Fill both blanks to assert that the log level of the first record is ERROR and the message contains 'critical'.

PyTest
def test_log_level_and_message(caplog):
    with caplog.at_level("ERROR"):
        logger = logging.getLogger()
        logger.error("A critical failure happened")
    assert caplog.records[0].[1] == logging.[2]
    assert "critical" in caplog.records[0].msg
Drag options to blanks, or click blank then click option'
Alevelno
Blevelname
CERROR
DCRITICAL
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'levelname' which is a string, not numeric.
Using 'CRITICAL' constant instead of 'ERROR'.
5fill in blank
hard

Fill all three blanks to capture logs at INFO level, log an info message, and assert the message is captured.

PyTest
def test_info_log_capture(caplog):
    with caplog.[1]("INFO"):
        logger = logging.getLogger()
        logger.[2]("Process started")
    assert "[3]" in caplog.text
Drag options to blanks, or click blank then click option'
Aat_level
Binfo
CProcess started
Dwarning
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong log level or method names.
Checking for a message not logged.