assertRaises未捕获异常ItemNotString

2024-06-16 10:38:44 发布

您现在位置:Python中文网/ 问答频道 /正文

import unittest
import filterList

class TestFilterList(unittest.TestCase):
    """ docstring for TestFilterList
    """

    def setUp(self):
        self._filterby = 'B'


    def test_checkListItem(self):
        self.flObj = filterList.FilterList(['hello', 'Boy', 1], self._filterby)
        self.assertRaises(filterList.ItemNotString, self.flObj.checkListItem)


    def test_filterList(self):
        self.flObj = filterList.FilterList(['hello', 'Boy'], self._filterby)
        self.assertEquals(['Boy'], self.flObj.filterList())

if __name__ == '__main__':
    unittest.main()

对于下面的filterList模块,我上面的测试test_checkListItem()失败:

import sys
import ast

class ItemNotString(Exception):
    pass


class FilterList(object):
    """docstring for FilterList
    """

    def __init__(self, lst, filterby):
        super(FilterList, self).__init__()
        self.lst = lst
        self._filter = filterby
        self.checkListItem()

    def checkListItem(self):
        for index, item in enumerate(self.lst):
            if type(item) == str:
                continue
            else:
                raise ItemNotString("%i item '%s' is not of type string" % (index+1, item))
        print self.filterList()
        return True

    def filterList(self):
        filteredList = []
        for eachItem in self.lst:
            if eachItem.startswith(self._filter):
                filteredList.append(eachItem)
        return filteredList


if __name__ == "__main__":
    try:
        filterby = sys.argv[2]
    except IndexError:
        filterby = 'H'
    flObj = FilterList(ast.literal_eval(sys.argv[1]), filterby)
    #flObj.checkListItem()

为什么测试失败并出现错误:

======================================================================
ERROR: test_checkListItem (__main__.TestFilterList)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_filterList.py", line 13, in test_checkListItem
    self.flObj = filterList.FilterList(['hello', 'Boy', 1], self._filterby)
  File "/Users/sanjeevkumar/Development/python/filterList.py", line 16, in __init__
    self.checkListItem()
  File "/Users/sanjeevkumar/Development/python/filterList.py", line 23, in checkListItem
    raise ItemNotString("%i item '%s' is not of type string" % (index+1, item))
ItemNotString: 3 item '1' is not of type string

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (errors=1)

另外,filterList模块的方法是否正确?你知道吗


Tags: intestimportselffordefitemboy
1条回答
网友
1楼 · 发布于 2024-06-16 10:38:44

您的assertRaises调用没有捕获异常,因为它是在前一行引发的。如果仔细查看回溯,您将看到checkListItem是由FilterList类的__init__方法调用的,而在测试中尝试创建self.flObj时又调用了该方法。你知道吗

相关问题 更多 >