我是python的新手。我想测试我的代码是否抛出异常。我从这里得到了代码:How do you test that a Python function throws an exception?
import mymod
import unittest
class MyTestCase(unittest.TestCase):
def test1(self):
self.assertRaises(SomeCoolException, mymod.myfunc, compulsory_argument)
现在,如果没有抛出异常,我还想显示一条消息。我怎么做 ? python文档没有清楚地提到它。我在“compulsory_argument”之后添加了消息,但它失败了。
编辑:我尝试了修改的第一个答案并获得了例外。这里我的错误是什么?
import unittest
def sayHelloTo(name):
print("Hello " + name)
class MyTestCase(unittest.TestCase):
def test1(self):
person = "John"
with self.assertRaises(Exception, "My insightful message"):
sayHelloTo(person)
错误:
Error
Traceback (most recent call last):
File "C:\tests\tester.py", line 9, in test1
with self.assertRaises(Exception, "My insightful message"):
AttributeError: __exit__
答案 0 :(得分:4)
从python 3.3开始,assertRaises可以用作带有消息的上下文管理器:
import unittest
def sayHelloTo(name):
print("Hello " + name)
class MyTestCase(unittest.TestCase):
def test1(self):
person = "John"
with self.assertRaises(Exception, msg="My insightful message"):
sayHelloTo(person)
if __name__ == "__main__":
unittest.main()
结果
Hello John
F
======================================================================
FAIL: test1 (__main__.MyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "r.py", line 10, in test1
sayHelloTo(person)
AssertionError: Exception not raised : My insightful message
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=1)
答案 1 :(得分:1)
现在,如果没有抛出异常,我还想显示一条消息。我该怎么做?
unittest 的一般理念是让测试在成功时保持沉默,只有在失败时才会变得冗长。因此,API提供了一个" msg"不成功案例的关键字参数,但不提供成功案例的替代方案。
那就是说,哲学的另一部分对你有利。通常,测试用例在测试用例失败时会在内部引发异常。这意味着如果要在成功时显示消息,只需在测试后添加另一个语句:
with self.assertRaises(TypeError, msg='Oh no, I did not get a TypeError')
somecode()
logging.info('Yippee, we got a TypeError!') # Runs after a successful test