How to test that an exception is raised ?
Dan Perl
danperl at rogers.com
Fri Jan 28 08:22:57 EST 2005
"StepH" <stephane.bronsart at bea.be> wrote in message
news:41fa0da9$0$2018$6c56d894 at feed0.news.be.easynet.net...
> But i've prob with the 1st test : test_badFile.
> When I run the test, unittest say that no error is Raised.
> But when I run the mps2xml module with a bad file as arg., the exception
> is
> well Raised.
I assume you don't actually see the exception (you don't see the stack
traceback printed as an output) but you just see your own message
"FileError". That means that the exception was raised and caught by your
try-except statement.
> What i'm doing wrong ?
>
> It is because the exception in catched in the mps2xml module ?
With the above mentioned assumption, that must be it. Once the exception is
caught, it is caught and no other code invoking mps2xml.mps2xml (including
the assertRaises in your test) will see the exception.
Your mps2xml.mps2xml function should return a value indicating success or
failure or should re-raise the exception. You need a mechanism to let
invoking code know that it was successful or it failed. With a return code,
you should test that and not the exception. The assert you use should work
if you re-raise the exception.
And BTW, it is a bad idea to use a generic "except" statement like you do.
That catches ALL the exceptions and you will never know if a different
exception than IOError was raised. You should catch only IOError
specifically or any other exception that you may expect. You can add then
an extra "except" statement catching all the other exceptions, but only if
it is essential for your application to handle all exceptions gracefully
instead of just exiting with a stack traceback.
> Thanks for your helps.
>
> StepH.
>
>
More information about the Python-list
mailing list