黎刚的回答:刚才查了,它应该是nose测试框架中的一个测试用例的书写办法。如果没有文档,就看它的源代码。我刚刚下载了nose。 在1.0版本里找到这样一句话。 def raises(*exceptions): ??? """Test must raise one of expected exceptions to pass. ??? ..... ??? If you want to test many assertions about exceptions in a single test, ??? you may want to use `assert_raises` instead. ??? """ 从含义上看,应该是确保一定要发生异常。而且要用在大量使用assert语言产生异常的条件下。 下面一段更说明问题。 def?assert_raises(exception,?callable,?*args,?**kw): try: callable(*args,?**kw) except?exception,?e: return?e else: if?hasattr(exception,?'__name__'): name?=?exception.__name__ else: name?=?'?or?'.join([e.__name__?for?e?in?exception]) assert?False,?'%s()?did?not?raise?%s'?%?(callable.__name__,?name) Usage: def?test_foo(): ????e?=?assert_raises(EnvironmentError,?open,?'/tmp/notfound') ????assert?e.errno?==?errno.ENOENT?还比如这样子。 import math import py.test py.test.raises(OverflowError, math.log, 0) py.test.raises(ValueError, math.sqrt, -1) py.test.raises(ZeroDivisionError, "1 / 0") import nose.tools nose.tools.assert_raises(OverflowError, math.log, 0) nose.tools.assert_raises(ValueError, math.sqrt, -1) |