Python logger 7.Assert测试单元抛出

2024-10-01 13:36:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图为一段python代码编写一个单元测试,在某些情况下,该代码通过logger.warn('...')发出警告。如何断言已记录此警告?我注意到,assertLogged至少在Python3.4之前是不可用的,不幸的是我在2.7中。在


Tags: 代码警告记录情况断言单元测试loggerwarn
2条回答

python3.4为unittest添加了这个特性。见TestCase.assertLogs。API非常易于使用:

with self.assertLogs('foo', level='INFO') as cm:
   logging.getLogger('foo').info('first message')
   logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
                             'ERROR:foo.bar:second message'])

现在,这个问题被标记为python2.7,但是当搜索python + unittest + logging的类似标题时,它会出现。很容易将该功能移植到Python2.7中,因此如下所示:

^{pr2}$

现在,在单元测试模块中,可以使用该类:

#test_my_module
from logger_test import LogTestCase

class TestMyModule(LogTestCase):

    def test_some_feature(self):
        with self.assertLogs('foo', level='INFO') as cm:
            logging.getLogger('foo').info('first message')
            logging.getLogger('foo.bar').error('second message')
        self.assertEqual(cm.output, ['INFO:foo:first message',
                         'ERROR:foo.bar:second message'])

在单元测试设置中,添加一个缓冲记录的日志处理程序,并在拆卸期间将其删除。您可以将a couple of utility classes, ^{} and ^{}用作基础,它是Python测试基础设施的一部分。(链接指向Python的默认分支,但是这些类应该可以在其他Python版本中使用)。有关如何使用这些类的信息,请参见this post。在

相关问题 更多 >