Outputting data from unit test in Python

前端 未结 14 2494
孤城傲影
孤城傲影 2020-12-02 05:45

If I\'m writing unit tests in python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error?

14条回答
  •  旧时难觅i
    2020-12-02 06:09

    You can use logging module for that.

    So in the unit test code, use:

    import logging as log
    
    def test_foo(self):
        log.debug("Some debug message.")
        log.info("Some info message.")
        log.warning("Some warning message.")
        log.error("Some error message.")
    

    By default warnings and errors are outputted to /dev/stderr, so they should be visible on the console.

    To customize logs (such as formatting), try the following sample:

    # Set-up logger
    if args.verbose or args.debug:
        logging.basicConfig( stream=sys.stdout )
        root = logging.getLogger()
        root.setLevel(logging.INFO if args.verbose else logging.DEBUG)
        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.INFO if args.verbose else logging.DEBUG)
        ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(name)s: %(message)s'))
        root.addHandler(ch)
    else:
        logging.basicConfig(stream=sys.stderr)
    

提交回复
热议问题