Paul Moore wrote: > I have a class with a read-only attribute, and I want to add a unit > test to ensure that it really *is* read-only. I can do this as > > def test_readonly(self): > """Value and multiplier must be readonly""" > try: > self.combat.value = 1 > self.fail("Value is not read only") > except AttributeError: > pass > > That works, but it seems a bit clumsy. Is there a better way?
By using setattr, you could refactor the above code into a function. Looks like this (untested): def test_readonly(self, instance, attribute, value=1): """Value and multiplier must be readonly""" try: setattr(instance, attribute, value) self.fail("Value is not read only") except AttributeError: pass Then the testing becomes one line: self.test_readonly(self.combat, "value") -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list