python unittest.TestCase.assertRaises 不起作用 [英] python unittest.TestCase.assertRaises not working

查看:102
本文介绍了python unittest.TestCase.assertRaises 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Python 中对我的添加"函数运行测试,但出现错误:

I'm trying to run tests on my 'add' function in Python but it is giving an error :

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

这是我的代码:

    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()

推荐答案

正如错误消息告诉您的那样,您的 assert raises 对象没有属性 exception.更具体地说,这个调用:

As the error message is telling you, your assert raises object has no attribute exception. To be more specific, this call:

cm.exception.message

cm 在这种情况下是您的断言对象,并且因为您正在测试的代码实际上从未引发过,您的 cm 对象将不会有 exception 属性,您尝试访问.

cm is your assert object in this case, and because the code you are testing never actually raises, your cm object will not have the exception attribute you are trying to access.

现在,为什么会发生这种情况.您正在尝试测试在您的 add 方法中引发 exception 时会发生什么,以便引发 TypeError.但是,如果您查看您的测试用例,您将向 add 方法传递两个有效整数.您不会引发异常,因为这是一个有效的测试用例.

Now, on to why this is happening. You are trying to test what happens when an exception is being raised in your add method, in order to raise a TypeError. However, if you look at your test case you are passing two valid integers in to the add method. You will not raise an exception because this is a valid test case.

对于您的单元测试,您希望测试当您 raise 某些东西时会发生什么,即将无效数据插入到 add 方法中.再次尝试您的代码,但这次在您的单元测试中,通过以下内容:

For your unittest, you are looking to test what happens when you raise something, i.e. insert invalid data to the add method. Try your code again, but this time in your unittest, pass the following:

add(5, 'this will raise')

您现在将收到 TypeError.

您还需要在上下文管理器之外执行断言验证:

You will also need to perform your assertion validation outside of the context manager:

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:")

您现在将遇到另一个问题.没有 message 属性.您应该只检查 cm.exception.此外,在您的 add 方法中,您的字符串是:

You will now have another problem. There is no message attribute. You should be checking simply cm.exception. Furthermore, in your add method your string is:

"Input should be a string:"

但是,您正在检查它是否为:

However, you are checking that it is:

"Input is not a string:"

因此,一旦您更正单元测试以使用 cm.exception,您现在将面临:

So, once you correct your unittest to use cm.exception, you will now be faced with:

AssertionError: 'Input should be a string:' != TypeError('Input should be a string:',) : Input is not a string:

因此,您的断言应该通过在 cm.exception 上调用 str 来检查异常字符串:

So, your assertion should check the exception string by calling str on the cm.exception:

self.assertEqual("Input should be a string:", str(cm.exception), "Input should be a string:")

因此,您的完整测试方法应该是:

So, your full test method should be:

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:")

这篇关于python unittest.TestCase.assertRaises 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆