如何将调试或信息注释记录到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(“我告诉过你”) 在日志文件中丢失
答案 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()