我的印象(但没有找到它的文档)unittest 将所有记录器的日志记录级别设置为WARNING
。我想:
- 能够从命令行(运行测试时)或从测试模块本身指定所有记录器的日志记录级别
- 避免 unittest 弄乱应用程序日志记录级别:在运行测试时,我希望获得与运行应用程序时相同的日志记录输出(相同级别)
我怎样才能做到这一点?
最佳答案
我不相信 unittest
本身对日志记录有任何作用,除非您使用它定义的 _CapturingHandler
类。这个简单的程序演示:
import logging
import unittest
logger = logging.getLogger(__name__)
class MyTestCase(unittest.TestCase):
def test_something(self):
logger.debug('logged from test_something')
if __name__ == '__main__':
# DEBUG for demonstration purposes, but you could set the level from
# cmdline args to whatever you like
logging.basicConfig(level=logging.DEBUG, format='%(name)s %(levelname)s %(message)s')
unittest.main()
运行时会打印
__main__ DEBUG logged from test_something
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
显示它在 DEBUG
级别记录事件,正如预期的那样。所以这个问题很可能与其他事情有关,例如被测代码,或其他一些更改日志配置或重定向 sys.stdout
和 sys.stderr
的测试运行程序。您可能需要提供有关您的测试环境的更多信息,或者更好的是演示问题的最小程序(如我上面的示例所示, unittest
本身不会导致您描述的问题)。
关于python - 在 unittest 中更改日志级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37315180/