How do I unit-test a specific case of a home-rolled exception ?
Ken Starks
straton at lampsacos.demon.co.uk
Fri Jun 27 08:23:51 EDT 2008
Peter Otten wrote:
> Ken Starks wrote:
>
>> I have an exception class, and I want to check that
>> a particular instance of it has been raised; or
>> more accurately that one is raised that is equal to
>> an instance I specify.
>>
>> In the example below, I can check that a
>> 'LongRationalError' is raised, but I want
>> to check that it is specifically a
>> 'LongrationalError('1') or a 'LongRationalError('2')
>>
>> How do I do that?
>
> (all untested)
>
> try:
> LongRational(1, "7")
> except LongRationalError, e:
> self.assertEquals(e.code, "2")
> else:
> self.fail()
>
> Alternatively you can subclass LongRationalError...
>
> class LongRationalError(Exception):
> pass
>
> class LongRationalDenominatorError(LongRationalError):
> pass
>
> class LongRationalNumeratorError(LongRationalError):
> pass
>
> ...and then check for the specialized exception:
>
> self.assertRaises(LongRationalDenominatorError, LongRational, 1, "7")
>
> Personally, I'd probably throw a plain old TypeError for incompatible types
> of both numerator and denominator.
>
> Peter
Thanks Peter, that answers my question nicely. I rather thought
I would need a try .. except structure in my unit-test itself.
More information about the Python-list
mailing list