How to enable the programs under test logging during pytest run #10672
-
Hello! DescriptionI have a script, which is performing some stuff and logs the results into a log file using the If I run the test function with python, then it works. I have searched the documentation and forums for a switch to enable logging, but I couldn't find one. I hope someone here can help. Here is a code snippet to reproduces the issue: # log_example.py
import logging
import unittest
from collections import deque
global LOG_PATH
LOG_PATH = 'my_log.log'
logging.basicConfig(filename=LOG_PATH, level=logging.DEBUG)
logger = logging.getLogger('my_logger')
def my_function():
logger.info('Hello World')
class test_my_example(unittest.TestCase):
def test_my_function(self):
my_function()
with open(LOG_PATH, 'r') as f:
lines = deque(f, 1)
self.assertEqual(lines[0], 'INFO:my_logger:Hello World\n')
if __name__ == '__main__':
unittest.main() To reproduce the error run the following command: python.exe .\log_example.py; del my_log.log; pytest.exe .\log_example.py The first command will print QuestionWhich command line argument of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Ok, I solved it myself. 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__ == '__main__':
unittest.main() Run file: python.exe .\log_example.py; del my_log.log; pytest.exe .\log_example.py You can call the function like above. The fun thing is, that the pytest call will succeed, without even creating a log file 😆 |
Beta Was this translation helpful? Give feedback.
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 😄