gpt4 book ai didi

python - 如何将unitest textrunner日志与日志记录结合起来

转载 作者:行者123 更新时间:2023-12-01 01:26:13 25 4
gpt4 key购买 nike

如何将调试或信息注释记录到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('我告诉过你了')日志文件中遗漏了

最佳答案

您未能配置日志记录模块以使用指定的文件。您可以使用 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()

关于python - 如何将unitest textrunner日志与日志记录结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53321551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com