What does 'with' + 'assertRaises' do?
我在做python koans(关于python 2),在
这就是我不知道该怎么做/发生了什么的代码:
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() |
但我不明白。
现在的问题是:最后一段代码在做什么?
它断言,不带参数地调用
关于
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.
(强调矿山)
当将
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.
因此,
python 2.7引入了使用