Python 2.7 Unittest检查是否记录了警告[重复]

问题描述 投票:2回答:1

这个问题在这里已有答案:

我正在尝试为我的模块编写单元测试,该模块是用Python 2.7编写的,我现在无法迁移到3.x.我想要的是这个测试做的是检查我的模块是否生成警告日志,如果它然后捕获它。我在搜索网页和堆栈溢出时找不到Python 2.7的答案。我已经包含了一个简单的可测试代码,您可以使用它来尝试或更好地理解我的问题。

更新:只是为了澄清我愿意改变我的测试用例,即test_warning_2能够捕获log.warn当前实现该方法只是一个占位符。

import logging
import warnings
from unittest import TestCase

def generate_warning_2():
    logging.warn("this is a warning")


def generate_warning_1():
    warnings.warn("this is a warning")


class TestWarning(TestCase):

    def test_warning_1(self):
        warnings.simplefilter("always")
        with warnings.catch_warnings(record=True) as w:
            generate_warning_1()
            self.assertEquals(len(w), 1)

    def test_warning_2(self):
        # Below code is just a place holder, i need some code to replace this so that i can catch `log.warn`
        warnings.simplefilter("always")
        with warnings.catch_warnings(record=True) as w:
            generate_warning_2()
            self.assertEquals(len(w), 1)

在这里,如果您看到函数generate_warning_2,您会注意到我正在使用我的测试用例未捕获的传统python日志记录警告。我知道原因是因为它不使用warnings模块。我只是想表明我想要它做什么。

另一个函数generate_warning_1我使用warnings模块捕获警告日志,这是我当前的实现工作正常。

我希望能够抓住log.warn,而不是必须使用warning来实现这一目标。这在Python 2.7中是否可行?请不要提供Python 3.x的答案,因为我已经知道它可能在那里。

希望我的问题很清楚,请随时向我提问或在适当的时候进行编辑。任何帮助在这里表示赞赏。

python python-2.7 python-unittest python-logging
1个回答
0
投票

这可以使用记录器处理程序来解决。不幸的是,似乎无法在根记录器上设置处理程序,但仅限于getLogger返回的实例。如果你可以忍受,这应该工作:

import logging
import warnings
import unittest


class WarningsHandler(logging.Handler):
    def handle(self, record):
        if record.levelno == logging.WARN:
          warnings.warn(record.getMessage())
        return record

log = logging.getLogger()
log.addHandler(WarningsHandler())

def generate_warning_2():
    log.warn("this is a warning")


def generate_warning_1():
    warnings.warn("this is a warning")


class TestWarning(unittest.TestCase):

    def test_warning_1(self):
        warnings.simplefilter("always")
        with warnings.catch_warnings(record=True) as w:
            generate_warning_1()
            self.assertEquals(len(w), 1)

    def test_warning_2(self):
        warnings.simplefilter("always")
        with warnings.catch_warnings(record=True) as w:
            generate_warning_2()
            self.assertEquals(len(w), 1)

if __name__ == "__main__":
    unittest.main()

$ python2 so.py
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

为了防止最终的双重打印,您可能希望使处理程序仅有条件地返回LogRecord。

© www.soinside.com 2019 - 2024. All rights reserved.