How to test that an exception is raised ?
stephane.bronsart at bea.be
Fri Jan 28 08:37:38 EST 2005
Thanks for you answer.
I'm new to Python (coming from C/C++).
> > 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.
Yes, when i'm run mps2xml.py with a bad filename as arg., the IOError is
launched and is correctly intercepted.
> > 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
> caught, it is caught and no other code invoking mps2xml.mps2xml (including
> the assertRaises in your test) will see the exception.
Do you say that it's not possible to test (using unittest) if an exception
is well raised if the tested code catch it ?
How to solve this paradoxe ? How to automaticaly test such code ?
> Your mps2xml.mps2xml function should return a value indicating success or
> failure or should re-raise the exception.
1./ Cheking error-return value if not a good idea for me, cause this make
the code less clear. I don't want a code where i've to test each function
2./ If I re-raise the exception, then how to not show the traceback. My
user will became crazy if they view such error msg.
> You need a mechanism to let
> invoking code know that it was successful or it failed. With a return
> you should test that and not the exception. The assert you use should
> 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.
It seems that there is 2 school here. I've read a lot on python, and somed
'guru' Python say that it's maybe better to use exception even for case you
can "predict", no ? Or i'm completly wrong ?
> > Thanks for your helps.
> > StepH.
More information about the Python-list