How do I unit-test a specific case of a home-rolled exception ?
Peter Otten
__peter__ at web.de
Fri Jun 27 07:33:32 EDT 2008
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
More information about the Python-list
mailing list