Need py.test to log assert errors in log file from python logging module

后端 未结 1 1212
猫巷女王i
猫巷女王i 2021-01-16 12:53

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 stat

1条回答
  •  心在旅途
    2021-01-16 13:22

    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.

    0 讨论(0)
提交回复
热议问题