关于python:’with’ +’assertRaises’做什么?

What does 'with' + 'assertRaises' do?

本问题已经有最佳答案,请猛点这里访问。

我在做python koans(关于python 2),在about_classes部分有点丢失。

这就是我不知道该怎么做/发生了什么的代码:

1
2
3
4
5
6
7
8
9
10
class Dog5(object):
    def __init__(self, initial_name):
        self._name = initial_name

    @property
    def name(self):
        return self._name

def test_args_must_match_init(self):
    self.assertRaises(___, self.Dog5)  # Evaluates self.Dog5()

我理解为什么我会在这里得到一个错误,因为类需要一个参数(并且给出零),但是在这里不能得到预期的响应。

因此,在寻找解决方案时,我发现了以下代码:

1
2
3
def test_args_must_match_init(self):
    with self.assertRaises(TypeError):
            self.Dog5()

但我不明白。

现在的问题是:最后一段代码在做什么?

with assertRaises(TypeError): Dog5()在做什么?


它断言,不带参数地调用Dog5()将产生一个TypeError,它将成功,因此没有AssertionError

关于assertRaises()的文件是非常直接的:

assertRaises(exception, msg=None)

Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception.

(强调矿山)

当将exception作为TypeError和可选msg传递时,创建一个上下文管理器,而不是进一步记录的函数:

If only the exception and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function.

这比看起来更简单。


来自文档:

assertRaises(exception, callable, *args, **kwds)

assertRaises(exception)

Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception.

因此,with assertRaises(TypeError): Dog5()主张self.Dog5()增加TypeError

python 2.7引入了使用assertRaises作为上下文管理器(因此使用with)的可能性,而在以前的python版本中,您将称为self.assertRaises(TypeError, self.Dog5)