pytest: How to show messages from logging.debug in the function under test

11,312

Solution 1

The way to do it -- in pytest.ini add:

   [pytest]
   log_cli = true  

Then run pytest with

   pytest --log-cli-level=10 func.py

Solution 2

I found this thread when I wondered how to expand the "warning summary" section on my PyTest run. Playing around with the environment variable PYTHONWARNINGS can help with that https://docs.python.org/3/using/cmdline.html#envvar-PYTHONWARNINGS. If you do export PYTHONWARNINGS=error, you'll see the full stack trace for the warning. However, the run will stop if you are running a test suite.

Share:
11,312
mikey
Author by

mikey

Updated on July 22, 2022

Comments

  • mikey
    mikey almost 2 years
    ''' func.py '''
    import logging
    
    def func():
        ''' func '''
        logging.basicConfig(
            format="\t %(filename)s"
            " %(funcName)s"
            "-ln%(lineno)d"
            " %(levelname)s \n%(message)s",
            level=logging.DEBUG,
            # stream=sys.stdout,
        )
        logger = logging.getLogger()
        logger.info(" >>> logger func info")
        logger.warning(" >>> logger func warning")
        print(" >>> print func info")
    
    
    def test_func():
        ''' test func '''
        # caplog.set_level(logging.DEBUG)
        func()
    
    
    if __name__ == "__main__":
        test_func()
    

    Suppose I save the code above as func.py. When I run

    pytest -s func.py
    

    I obtain

    " >>> print func info".
    

    How can I obtain

    " >>> logger func info" 
    

    and

    " >>> logger func warning"

    when I run

    pytest -s func.py
    

    I wish I can do this for the following reason. I normally insert logging.debug/info etc in the my codes. Sometimes, I want to see messages emitted by logging.debug/info when I run pytest. I searched the net for quite a while but cant find a way. Thanks in advance for any help.

  • mijiturka
    mijiturka almost 3 years
    If you're not using a pytest.ini, it's not required; you could also just go with the command-line parameter.