Outputting data from unit test in Python

前端 未结 14 2455
孤城傲影
孤城傲影 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条回答
  •  春和景丽
    2020-12-02 06:10

    We use the logging module for this.

    For example:

    import logging
    class SomeTest( unittest.TestCase ):
        def testSomething( self ):
            log= logging.getLogger( "SomeTest.testSomething" )
            log.debug( "this= %r", self.this )
            log.debug( "that= %r", self.that )
            # etc.
            self.assertEquals( 3.14, pi )
    
    if __name__ == "__main__":
        logging.basicConfig( stream=sys.stderr )
        logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG )
        unittest.main()
    

    That allows us to turn on debugging for specific tests which we know are failing and for which we want additional debugging information.

    My preferred method, however, isn't to spend a lot of time on debugging, but spend it writing more fine-grained tests to expose the problem.

提交回复
热议问题