How can I see log messages when unit testing in Py

2019-03-18 02:05发布

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, and normally I'd set a root logger to catch the debugging messages at a certain level, and pipe the other logs to a file. But I can't figure out how this works with unit tests.

I'm using the unittest2 module, and using PyCharm's automatic test discovery (which probably is based on nose, but I don't know).

I've tried fooling with the run configurations, but there doesn't seem to be a straightforward way to do this.

The PyCharm documentation isn't particularly helpful here either, if any of you work there.


In edit: It DOES appear that the console catches critical level log messages. I want to know if there is a way to configure this to catch debug level messages.


This post (Pycharm unit test interactive debug command line doesn't work) suggests adding the -s option to the build configuration, which does not produce the desired result.

4条回答
Lonely孤独者°
2楼-- · 2019-03-18 02:39

In Edit Configurations:

  • delete old configurations
  • go to Defaults / Python tests / NoseTests
  • add --nologcapture to "additional Arguments"

worked like a "charm" for me in pyCharm 2017.2.3

thanks bott

查看更多
Evening l夕情丶
3楼-- · 2019-03-18 02:47

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)
查看更多
一纸荒年 Trace。
4楼-- · 2019-03-18 02:49

The only solution I've found is to do the normal logging setup at the top of the file with tests in it (assuming you're just running one test or test class): logging.basicConfig(level=logging.DEBUG). Make sure you put that before most import statements or the default logging for those modules will have already been set (that was a hard one to figure out!).

查看更多
在下西门庆
5楼-- · 2019-03-18 03:00

I needed to add too the option --nologcapture to nosetests as param in pycharm 2016.3.2

Run>Edit COnfigurations > Defaults > Python Tests > Nosetests : activate the check for Prams option and add --nologcapture

查看更多
登录 后发表回答