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

my above test test_checkListItem() fails , for the below filterList.py module

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)

why does the test fail with the error:

E['Boy']
.
======================================================================
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)

also, is the approach of the filterList.py module correct ?

The test fails before the assertRaises is reached, because the FilterList ctor (method __init__()) calls checkListItem(), which means that you cannot even make a test list with invalid types.

As for your approach, it is difficult to answer since we don't know what you want to do with this.

cool, that helped. I was trying to test using mox in order to learn it, so I slightly changed the test as well as the module to be tested.

import sys
import ast

class ItemNotString(Exception):
    pass


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

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

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

    def filterList(self, lst):
        lst = self.stringListItems(lst)
        filteredList = []
        for eachItem in 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(filterby)
    print flObj.filterList(ast.literal_eval(sys.argv[1]))

and the test module:

import unittest
import filterList
import mox

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

    def setUp(self):
        self._filterby = 'B'
        self.flObj = filterList.FilterList(self._filterby)
        self.mox = mox.Mox()

    def tearDown(self):
        self.mox.UnsetStubs()


    def test_stringListItems(self):
        self.assertRaises(filterList.ItemNotString, self.flObj.stringListItems, ['hello', 'Boy', 1])

    def test_stringListItems_True(self):
        self.assertTrue(self.flObj.stringListItems(['Boy','Bar','Home']))
        self.assertEquals(['Boy','Bar','Home'], 
            self.flObj.stringListItems(['Boy','Bar','Home']))

    def test_filterList(self):
        self.assertEquals(['Boy', 'Bar'], self.flObj.filterList(['Home', 'Boy','Bar','Home']))

    def test_usingMox(self):
        self.mox.StubOutWithMock(self.flObj,'stringListItems')
        mockLst = self.flObj.stringListItems().AndReturn(['Boy','Bar','Home'])
        self.mox.ReplayAll()
        filteredList = self.flObj.filterList(mockLst)
        self.assertEquals(['Bar'], filteredList)
        self.mox.VerifyAll()

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

but the test_usingMox that is supposed to test the method filterList method gives error:

======================================================================
FAIL: test_usingMox (__main__.TestFilterList)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_filterList.py", line 33, in test_usingMox
    filteredList = self.flObj.filterList(mockLst)
  File "/Users/sanjeevkumar/Development/python/filterList.py", line 26, in filterList
    lst = self.stringListItems(lst)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mox.py", line 983, in __call__
    expected_method = self._VerifyMethodCall()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mox.py", line 1041, in _VerifyMethodCall
    raise UnexpectedMethodCallError(self, expected)
UnexpectedMethodCallError: Unexpected method call.  unexpected:-  expected:+
- Stub for <bound method FilterList.stringListItems of <filterList.FilterList object at 0x106fd2150>>.__call__(['Boy', 'Bar', 'Home']) -> None
?                                                                                                                                    ---------

+ Stub for <bound method FilterList.stringListItems of <filterList.FilterList object at 0x106fd2150>>.__call__() -> ['Boy', 'Bar', 'Home']
?                                                                                                              +++++

please help me with testing using mox ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.