views:

36

answers:

3

Say I have the class

class myClass(object):
   pname = ""

   def __getName(self):
      return pname

   def __setName(self, newname):
      if not isalpha(newname):
         raise ValueError("Error")
      elif
         self.pname = newname

   name = property(fget=__getName,fset=__setName)

Seeing as these methods are private, and I am accessing pname through name, how do I test with AssertRaises when AssertRaises only accepts a callable for its test?

A: 

Make your own callable.

class TestMyClass(unittest.TestCase):
    def test_should_raise(self):
        x = myClass()
        def assign_bad_name():
            x.name = "7"
        self.assertRaises(ValueError, assign_bad_name)
lacker
A: 

Define your own function?

class TestRaises(unittest.TestCase):
    def test_setter(self):
        def run_test():
            c = myClass()
            c.name = 12

        self.assertRaises(ValueError, run_test)
Chris B.
+2  A: 

First. Please don't waste time on "private" methods with __names.

Second. Do this.

class TestMyClass( unittest.TestCase ):
    def setUp( self ):
        self.myclass= MyClass()
    def test_setName_should_fail( self ):
        try:
            self.myclass.name = 232
            self.fail( "Should have raised an exception" )
        except ValueError, e:
            self.assertEquals( "Error", e.msg )
S.Lott
+1 for comment on "private" methods.
PreludeAndFugue