如何将unitest textrunner日志与日志记录结合

时间:2018-11-15 14:23:37

标签: python unit-testing

如何将调试或信息注释记录到python单元测试生成的日志文件中

import unittest
import logging

class Arming(unittest.TestCase):
    def testCase1(self):
        logging.info('I told you so')
        actual = 3
        expected = 3
        self.assertEqual(actual,expected)

    def testCase2(self):
        actual = 3
        expected = 4
        testcase = "Test Case 2"
        self.assertEqual(actual,expected)

if __name__ == '__main__':
   log_file = 'Arming_Command.log'
   f = open(log_file, "w")
   runner = unittest.TextTestRunner(f,verbosity=2)
   unittest.main(testRunner=runner)
   f.close()

获取日志文件

testCase1 (__main__.Arming) ... ok
testCase2 (__main__.Arming) ... FAIL

======================================================================
FAIL: testCase2 (__main__.Arming)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:/Users/hariom.singh/PycharmProjects/Connect_Pversion/venv/Python_Logging.py", line 15, in testCase2
    self.assertEqual(actual,expected)
AssertionError: 3 != 4

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=1)

logging.info(“我告诉过你”) 在日志文件中丢失

1 个答案:

答案 0 :(得分:2)

您未能将日志记录模块配置为使用指定的文件。您可以使用basicConfig。代码可能变成:

if __name__ == '__main__':
   log_file = 'Arming_Command.log'
   f = open(log_file, "w")
   logging.basicConfig(stream=f, level=logging.INFO)  # use the opened file for logging
   runner = unittest.TextTestRunner(f,verbosity=2)
   unittest.main(testRunner=runner)
   f.close()