Skip to content

How to enable the programs under test logging during pytest run #10672

Answered by schorschie
schorschie asked this question in Q&A
Discussion options

You must be logged in to vote

Ok, I solved it myself.
The trick is to call the function, which creates the log entry within the assertLogs context manager of the unittest framework.

Here is a working code example, which even looks cleaner 😄

# log_example.py
 
import logging
import unittest

def my_function():
    logging.basicConfig(filename='my_log.log', level=logging.DEBUG)
    logger = logging.getLogger('my_logger')

    logger.info('Hello World')
    
class test_my_example(unittest.TestCase):
    
    def test_my_function(self):
        with self.assertLogs('my_logger', level=logging.DEBUG) as cm:
            my_function()
            self.assertEqual(cm.output, ['INFO:my_logger:Hello World'])

if __name__ == '__m…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by schorschie
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant