简体   繁体   中英

How to assert logging error which is followed by a sys.exit()

I am using Python's logging module to generate an ERROR message in specific cases, followed by a sys.exit().

if platform is None:  
    logging.error(f'No platform provided!')
    sys.exit()

Continue do other stuff

Now I am using pytest to unit test the specific error message. However the sys.exit() statement causes pytest to detect an error because of a SystemExit event, even if the error message passes the test.

And mocking the sys.exit makes that the rest of the code is being run ('Continue do other stuff') which then causes other problems.

I have tried the following:

LOGGER = logging.getLogger(__name__)

platform = None
data.set_platform(platform, logging=LOGGER)
assert "No platform provided!" in caplog.text

This question is a similar: How to assert both UserWarning and SystemExit in pytest , but it raises the error in a different way.

How do I make pytest ignore the SystemExit?

Here is one approach.

In your test module you could write the following test, where your_module is the name of the module where your actual code is defined, and function() is the function that is doing the logging and calling sys.exit() .

import logging
from unittest import mock
from your_module import function

def test_function(caplog):
    with pytest.raises(SystemExit):
        function()

    log_record = caplog.records[0]
    assert log_record.levelno == logging.ERROR
    assert log_record.message == "No platform provided!"
    assert log_record.lineno == 8   # Replace with the line no. in which log is actually called in the main code.

(If you want to shorten this a little bit, you can use record_tuples instead of records .)

EDIT: Using caplog instead of mocking the log module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM