unit testing properties

Mark McEahern mark at mceahern.com
Thu Jan 17 21:01:28 EST 2002


I'm trying to unit test the setter for a property:

class Foo(object):

	def getBar(self):
		return "bar"

	bar = property(getBar, None, None, "Bar.")

Notice that there is no setter (second arg to property is None).  This code
should raise AttributeError:

	f = Foo()
	f.bar = "somethin' innarestin"

However, suppose I wanted to unit test this:

	import unittest

	class testFoo(unittest.TestCase):
		def testSetter(self):
			f = Foo()
			self.assertRaises(AttributeError, f.bar...

That's where I get stopped.  The second param to assertRaises is supposed to
be a callable object--but I want to test a setter.  Hmm, any ideas?  Here
are mine:

1.  Why am I testing property(whatever, None)--that's like testing whether
addition works.  I'm not really doing anything beyond what Python's supposed
to do, so why do I think I need to test Python and not my specific stuff.

2.  If I'm perverse enough to want to test this, wrap the call to f.bar =
"whatever" in a function and pass THAT to assertRaises--fer instance, I
suppose I could use a lambda.

Cheers,

// mark





More information about the Python-list mailing list