开发者

AssertRaises non-callable

开发者 https://www.devze.com 2023-01-03 19:48 出处:网络
Say I have the class class myClass(object): pname = \"\" def __getName(self): return pname def __setName(self, newname):

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?


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)


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 )


In Python 3 (and 2.7) you can use a with construction:

class TestMyClass(unittest.TestCase):
    def test_should_raise(self):
        x = myClass()
        with self.assertRaises(ValueError):
            x.name = "7"

This is were code starts getting beautiful...


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

精彩评论

暂无评论...
验证码 换一张
取 消