Unittest - testing properties (read-only attributes)

Duncan Booth duncan.booth at invalid.invalid
Mon Feb 21 12:38:43 EST 2005


Paul Rubin wrote:

> Peter Hansen <peter at engcorp.com> writes:
>> > You want something like
>> > self.assertRaises(AttributeError, lambda: self.combat.value = 1)
>> 
>> Or, combining the two responses and avoiding the lambda:
>> 
>>   self.assertRaises(AttributeError, setattr, self.combat, 'value', 1)
>> 
>> Hmm... this might be a case where the lambda form is actually the
>> more readable one...
> 
> Yes, assignment expressions could make code more readable, if Python
> supported them.
> 

An assignment expression, if such a thing existed wouldn't help here.

The point being that the expression must be evaluated inside the exception 
handler in assertRaises, so you either need to delay the evaluation with a 
lambda, or by passing the function and arguments in separately. If you had 
an assignment expression it would be roughly equivalent to:

   self.assertRaises(AttributeError, setattr(self.combat, 'value', 1))

which will throw the AttributeError instead of passing the test.




More information about the Python-list mailing list