异常ItemNotString没有被assertRaises捕获

时间:2013-10-06 09:36:34

标签: python unit-testing

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

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

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模块的方法是否正确?

1 个答案:

答案 0 :(得分:1)

您的assertRaises来电未触及异常,因为它是在上一行引发的。如果仔细查看回溯,您会看到checkListItem类的FilterList方法调用了__init__,当您尝试创建self.flObj时,该方法又会被调用在你的测试中。

相关问题