我正在尝试在 Python 中对我的“添加”函数运行测试,但它给出了一个错误:
7
E
======================================================================
ERROR: test_upper (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:/Users/MaZee/PycharmProjects/andela/asdasd.py", line 22, in test_upper
self.assertEqual("Input should be a string:", cm.exception.message , "Input is not a string:")
AttributeError: '_AssertRaisesContext' object has no attribute 'exception'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import unittest
def add(a,b):
"""
Returns the addition value of a and b.
"""
try:
out = a + b
except TypeError:
raise TypeError("Input should be a string:")
print (out)
return
class TestStringMethods(unittest.TestCase):
def test_upper(self):
with self.assertRaises(TypeError) as cm:
add(3,4)
self.assertEqual("Input should be a string:", cm.exception.message , "Input is not a string:")
if __name__ == '__main__':
unittest.main()
Run Code Online (Sandbox Code Playgroud)
正如错误消息告诉您的那样,您的assert raises对象没有属性exception。更具体地说,这个调用:
cm.exception.message
Run Code Online (Sandbox Code Playgroud)
cm在这种情况下是您的断言对象,并且因为您正在测试的代码从未真正引发过,您的cm对象将不具有exception您尝试访问的属性。
现在,为什么会发生这种情况。您正在尝试测试exception在您的add方法中引发an 时会发生什么,以便引发TypeError. 但是,如果您查看您的测试用例,您将向该add方法传递两个有效整数。您不会引发异常,因为这是一个有效的测试用例。
对于您的单元测试,您希望测试当您执行raise某些操作时会发生什么,即将无效数据插入到add方法中。再次尝试您的代码,但这次在您的单元测试中,通过以下内容:
add(5, 'this will raise')
Run Code Online (Sandbox Code Playgroud)
您现在将获得您的TypeError.
您还需要在上下文管理器之外执行断言验证:
def test_upper(self):
with self.assertRaises(TypeError) as cm:
add(3, 'this will raise')
self.assertEqual("Input should be a string:", cm.exception.message, "Input is not a string:")
Run Code Online (Sandbox Code Playgroud)
您现在将遇到另一个问题。没有message属性。你应该简单地检查一下cm.exception。此外,在您的add方法中,您的字符串是:
"Input should be a string:"
Run Code Online (Sandbox Code Playgroud)
但是,您正在检查它是否:
"Input is not a string:"
Run Code Online (Sandbox Code Playgroud)
因此,一旦您更正单元测试以使用cm.exception,您现在将面临:
AssertionError: 'Input should be a string:' != TypeError('Input should be a string:',) : Input is not a string:
Run Code Online (Sandbox Code Playgroud)
因此,您的断言应通过调用以下str内容来检查异常字符串cm.exception:
self.assertEqual("Input should be a string:", str(cm.exception), "Input should be a string:")
Run Code Online (Sandbox Code Playgroud)
所以,你的完整测试方法应该是:
def test_upper(self):
with self.assertRaises(TypeError) as cm:
add(3, 'this will raise')
self.assertEqual("Input should be a string:", str(cm.exception), "Input should be a string:")
Run Code Online (Sandbox Code Playgroud)