How can I see log messages when unit testing in PyCharm?

后端 未结 6 1283
忘掉有多难
忘掉有多难 2021-02-05 06:35

I\'m sure this is a simple fix, but I\'d like to view log messages in the PyCharm console while running a unit test. The modules I\'m testing have their own loggers, an

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 07:15

    Add a stream handler, pointing to sys.stdout if doctest or pytest is running:

        import logging
        import sys
        logger = logging.getLogger()
    
        def setup_doctest_logger(log_level:int=logging.DEBUG):
            """
    
            :param log_level:
            :return:
    
            >>> logger.info('test')     # there is no output in pycharm by default
            >>> setup_doctest_logger()
            >>> logger.info('test')     # now we have the output we want
            test
    
            """
            if is_pycharm_running():
                logger_add_streamhandler_to_sys_stdout()
            logger.setLevel(log_level)
    
        def is_pycharm_running()->bool:
            if ('docrunner.py' in sys.argv[0]) or ('pytest_runner.py' in sys.argv[0]):
                return True
            else:
                return False
    
        def logger_add_streamhandler_to_sys_stdout():
            stream_handler=logging.StreamHandler(stream=sys.stdout)
            logger.addHandler(stream_handler)
    

提交回复
热议问题