Python单元测试断言错误 [英] Python unittest assertraises error

查看:227
本文介绍了Python单元测试断言错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中运行单元测试时遇到了奇怪的麻烦:
我使用assertRaises,运行单元测试引发了正确的异常,但是测试仍然失败。好的,我无法真正解释它,请自己查看回溯:

I had this weird trouble running my unittest in Python: I used assertRaises, and running the unittest raised the correct exception, but the test still failed. Ok I cannot really explain it, please see the traceback for yourself:

Error
Traceback (most recent call last):
File "/Users/chianti/PycharmProjects/Programming_Project/Part1and4/Part1and4Test.py", line 32, in test_non_alpha_name
self.assertRaises(RestNameContainNonAlphaError, RestaurantName(self.non_alpha_name))
File "/Users/chianti/PycharmProjects/Programming_Project/Part1and4/InputCheck.py", line 29, in __init__
raise RestNameContainNonAlphaError('There are non alphabetic characters that I can not recognize!')
RestNameContainNonAlphaError: There are non alphabetic characters that I can not recognize!


Error
Traceback (most recent call last):
File "/Users/chianti/PycharmProjects/Programming_Project/Part1and4/Part1and4Test.py", line 24, in test_non_string_name
self.assertRaises(InputNotStringError, RestaurantName, self.non_string_name)
File "/Users/chianti/anaconda/lib/python2.7/unittest/case.py", line 473, in assertRaises
callableObj(*args, **kwargs)
File "/Users/chianti/PycharmProjects/Programming_Project/Part1and4/InputCheck.py", line 33, in __init__
raise InputNotStringError('Not String! The input is supposed to be a string type!')
InputNotStringError: Not String! The input is supposed to be a string type!

为什么??????????任何想法表示赞赏!谢谢

Why ?????????? Any ideas are appreciated !!! THANK YOU

这是我的单元测试:

class RestaurantNameTests(unittest.TestCase):

def setUp(self):

    self.non_string_name = 123
    self.valid_name = 'Italian rest '
    self.non_alpha_name = 'valid ** n'

def tearDown(self):

    self.non_string_name = None
    self.valid_name = None
    self.non_alpha_name = None

def test_non_string_name(self):

    with self.assertRaises(InputNotStringError):
        RestaurantName(self.non_string_name)

def test_valid_name(self):

    self.assertEqual(RestaurantName(self.valid_name).__str__(), 'Italian rest')

def test_non_alpha_name(self):

    self.assertRaises(RestNameContainNonAlphaError, RestaurantName(self.non_alpha_name))

如果需要查看RestaurantName的定义,则为:

If you need to see the definition of RestaurantName, here it is:

class RestaurantName():

def __init__(self, input_contents):

    self.name = input_contents

    if IsValidString(self.name):

        self.no_space_name = self.name.replace(' ', '')

        if str.isalpha(self.no_space_name):
            pass
        else:
            raise RestNameContainNonAlphaError('There are non alphabetic characters that I can not recognize!')

    else:

        raise InputNotStringError('Not String! The input is supposed to be a string type!')

def __repr__(self):

    return 'RestaurantName(%s)' % self.name.strip()  

def __str__(self):

    return self.name.strip() 

再次感谢

推荐答案

回溯与您对问题的描述不符(也与您的问题描述不符)代码FWIW)。您收到的错误是在 test_non_alpha_name()中,您没有发布该错误,但是从错误消息中可以看到:

The traceback doesn't match your description of the problem (nor your code FWIW). The error you get is in test_non_alpha_name() which you didn't post but from your error message looks like:

self.assertRaises(
    RestNameContainNonAlphaError, 
    RestaurantName(self.non_alpha_name)
    )

这不是使用 assertRaises()的正确方法。您必须将 ExpectedExceptionClass,callable,* args,** kw 传递给 assertRaises args kw 将被传递给您的可调用对象。您想要的IOW:

This is not the correct way to use assertRaises(). You must pass ExpectedExceptionClass, callable, *args, **kw to assertRaises, and args and kw will be passed to your callable. IOW you want:

self.assertRaises(
    RestNameContainNonAlphaError, 
    RestaurantName, 
    self.non_alpha_name
    )

原因很简单:您当前的调用方式,例外是在之前触发了对 assertRaises 的调用。

The reason is simple: the way you currently call it, the exception is triggered before the call to assertRaises.

作为旁注:


  • tearDown方法是无用的

  • 错误类型已经存在内置异常,其命名为 TypeError

  • 还有一个内置错误值异常,该异常名为 ValueError

  • your tearDown method is useless
  • there's already a builtin exception for wrong types, it's named TypeError
  • there's also a builtin exception for wrong values which is named ValueError

这篇关于Python单元测试断言错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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