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

4

1 回答 1

1

您的调用没有捕获该异常,assertRaises因为它是在上一行引发的。如果您仔细查看回溯,您会看到该类的方法checkListItem调用了,而当您尝试在测试中创建时又调用了该方法。FilterList__init__self.flObj

于 2013-10-06T09:55:25.247 回答