6

Need py.test to log assert errors in log file from python logging module. The test has python logging module set up and all logs goes there as expected. I used assert statements through out the test. But when encounter assertion errors, those messages are not logged in the python logging output but in command console.

Is there a way to get py.test to log the assertion errors in the test's logging output?

Right now the errors are in command console but it would be great if these assertion errors are also logged as part of python logging output so all the log messages are captured in one place. Also, for long running test, I cannot see the errors until the entire test finish which could be a long time to wait. It would be great if I can see the assertion error immediately so I may decide to take action.

1

2 Answers 2

9

You can achieve this by using the pytest_runtest_call hook in a conftest.py file:

import logging

def pytest_runtest_call(__multicall__):
    try:
        __multicall__.execute()
    except KeyboardInterrupt:
        raise
    except:
        logging.exception('pytest_runtest_call caught exception:')
        raise

The pytest_runtest_call hook is responsible for actually running the test functions, but is not responsible for catching exceptions and reporting them. This means it is the ideal place to catch an exception and hand it to logging.

Instead of actually changing the way a test function is called this uses __multicall__ to simply call the hook which would have been called if this hook was not there.

Note that the exception logged by hook will be much longer then the exception which would be reported by py.test normally. This is because logging does not truncate the stack to be just the test function, you could add this yourself if it is needed.

Sign up to request clarification or add additional context in comments.

1 Comment

Argument(s) {'__multicall__'} are declared in the hookimpl but can not be found in the hookspec for pytest 7.2.0
6

If you'd like to have pytest style assert error in logging, you can use the pytest_exception_interact hook in conftest.py file:

import logging

def pytest_exception_interact(report):
    logging.error(f'Test exception:\n{report.longreprtext}')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.