473,698 Members | 2,631 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to test that an exception is raised ?

Hi,

I've this module :

from optparse import OptionParser
import re

_version = "P1"

def writeVar(f, line):
"""Output a line in .xml format in the file f."""

f.write('\t<Var >\n')
name = line.split()[0]
adr = line.split()[3]
f.write('\t\t<N ame>' + name + '</Name>\n')
f.write('\t\t<A dr>' + adr + '</Adr>\n')
f.write('\t</Var>\n')

def mps2xml(mps,ver bose):
"""Convert '.mps' to '.xml'."""

try:
f = open(mps)
f.close()

xmlfile = mps + ".xml"
f = open(xmlfile, "w+")
f.write('<?xml version="1.0" ?>\n')
f.writelines('< List>\n')

pat = re.compile(".*V ar.*g.*0x00.*")
lines = list(open(mps))
nbScan = nbFound = 0
for line in lines:
nbScan = nbScan + 1
if pat.match(line) :
writeVar(f, line)
nbFound = nbFound + 1

f.writelines('</List>\n')
f.close()

if verbose:
print "Output to file %s..." % xmlfile
print "Lines scanned:", nbScan
print "Lines found:", nbFound

except:
if verbose:
print "FileError"

if __name__ == "__main__":
usage = "usage: %prog [options] filename"
parser = OptionParser(us age)

parser.add_opti on("-v", "--verbose", action="store_t rue",
dest="verbose")
parser.add_opti on("-q", "--quiet", action="store_f alse", dest="verbose")

(options, args) = parser.parse_ar gs()

if len(args) != 1:
parser.error("i ncorrect number of arguments")
exit(1)

if options.verbose :
print "mps2xml -", _version

mps2xml(args[0],options.verbos e)

And this "unittest" module :

import mps2xml
import os
import unittest

class Tests(unittest. TestCase):

def setUp(self):
self.mps = "test.mps"

def tearDown(self):
pass

def test_badFile(se lf):
"""Check that an exception is raised if a bad filename is passed to
mps2xml"""
self.assertRais es((IOError),mp s2xml.mps2xml, "thisfiledoesnt exists",
False)

def test_writeVar_O utput(self):
"""Check the output of the 'writeVar' method"""

line = " irM1slotnoisePP tmp Var. g 0x0002F6"
file = open("testWrite Var.xml","w+")
mps2xml.writeVa r(file, line)
file.close()

outputlines = list(open("test WriteVar.xml"))
goodlines = list(open("test WriteVar.xml.go od"))
self.assertEqua ls(outputlines, goodlines, 'bad output format')

def test_mps2xml_Cr eation(self):
"""Check if test.mps.xml is created"""

mps2xml.mps2xml (self.mps, False)
self.assert_(os .path.exists(se lf.mps + ".xml"), 'test.mps.xml not
created')

if __name__ == '__main__':
unittest.main()

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.

What i'm doing wrong ?

It is because the exception in catched in the mps2xml module ?

Thanks for your helps.

StepH.
Jul 18 '05 #1
8 2719
[snipped alot of codes that doesn't mean much ]

if you want to check for exception then it goes like this

try:
<put your code here which fails on certain exception like maybe IOError>
catch IOError:
<put a code to do something when IOError is raised>

sorry i won't bother to read your code because i can't read, i think i
am tired and need to go to bed. ;-)

--
cheers,
Ishwor Gurung
Jul 18 '05 #2

"StepH" <st************ ***@bea.be> wrote in message
news:41******** **************@ feed0.news.be.e asynet.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.

Jul 18 '05 #3
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

is 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
return value...
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 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.
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.

Thanks again.
StepH.

Jul 18 '05 #4

"StepH" <st************ ***@bea.be> wrote in message
news:41******** **************@ feed0.news.be.e asynet.net...

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 ?
Then you need a side-effect in catching the exception. A return code would
be such a side-effect. Setting a state variable that can be checked by the
invoking code would be another such side-effect.
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
return value...
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.
But then how will the user know if the call did what it is supposed to do?
And if the user mis-used the function and used it for a file that does not
exist, how is he/she supposed to know what the problem was and why nothing
is coming out of calling your function?
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 ?


The IOError is an exception that you can predict and I was saying that you
should catch it, but with a "except IOError:" statement instead of the
"except:" statement that you used.
Jul 18 '05 #5
Op 2005-01-28, StepH schreef <st************ ***@bea.be>:
Thanks for you answer.
I'm new to Python (coming from C/C++).

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 ?


IMO you want something unittest are not designed for.

Unittest are supposed to test for particular results, not for particular
behaviour within. If the expected behaviour is that calling code doesn't
see an exception raised, then the test passed if no exception was seen.

You equally can't test which branch of an if statement was taken or
which parameter was given to a helper function in order to get to
the desired result.

That you internally raise an exception and catches it, is an
implementation detail, that normally is of no concern to
the tester.

--
Antoon Pardon
Jul 18 '05 #6
Antoon Pardon a écrit :
Op 2005-01-28, StepH schreef <st************ ***@bea.be>:
Thanks for you answer.
I'm new to Python (coming from C/C++).

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 ?

IMO you want something unittest are not designed for.


So why the assertRaises function in unittest ? My goal is to test if an
exception is well raised when a bad filename is passed to the mps2xml
function.

Unittest are supposed to test for particular results, not for particular
behaviour within. If the expected behaviour is that calling code doesn't
see an exception raised, then the test passed if no exception was seen.

No (unless i don't well understand you), the expected behavior is to
launch an exception if a bad filename is passed. If no exception is
raised, this is not normal.
You equally can't test which branch of an if statement was taken or
which parameter was given to a helper function in order to get to
the desired result.
I'm agree with out on this point, but not for the exception part...

That you internally raise an exception and catches it, is an
implementation detail, that normally is of no concern to
the tester.


I'll conclude this thred here... In fact, I think I've to go-back to
theory (at least about exception)...

Thanks at all fo trying to help me. I'm new to Python, and i've not
already embrass the "python way" completly.

See you later.

StepH.
Jul 18 '05 #7

"StepH" <st************ ***@teledisnet. be> wrote in message
news:41******** *************** @read.news.be.u u.net...
So why the assertRaises function in unittest ? My goal is to test if an
exception is well raised when a bad filename is passed to the mps2xml
function.


It is for functions in which the exception is raised and not caught. You
can use the exception mechanism to let the code invoking your function know
that something "exceptiona l" has happened. It means that you "throw" that
exception to the invoking code which has to catch it. Maybe the terminology
is poorly chosen, but assertRaises does not check whether an exception is
raised inside the function but only that an exception is raised (or
"thrown", as described by other languages) from inside the function to
outside. A function does not "throw" an exception if the exception is
caught inside the function. Is that clearer now?

In java for instance, functions are actually declared to "throw" an
exception if any operation inside the function may throw that exception and
the exception is not caught inside the function. If you implement a
function A that invokes another function B and B throws an exception of type
C, then you must catch the exception C in A or you have to declare A that it
"throws C".

Hope this helps.

Dan
Jul 18 '05 #8
Op 2005-01-28, StepH schreef <st************ ***@teledisnet. be>:
Antoon Pardon a écrit :
Op 2005-01-28, StepH schreef <st************ ***@bea.be>:
Thanks for you answer.
I'm new to Python (coming from C/C++).

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 ?

IMO you want something unittest are not designed for.


So why the assertRaises function in unittest?


To see if an exception is propagated to the caller.
My goal is to test if an
exception is well raised when a bad filename is passed to the mps2xml
function.

Unittest are supposed to test for particular results, not for particular
behaviour within. If the expected behaviour is that calling code doesn't
see an exception raised, then the test passed if no exception was seen.


No (unless i don't well understand you), the expected behavior is to
launch an exception if a bad filename is passed. If no exception is
raised, this is not normal.


What do you mean with launch an exception? Should the exception
propagate to the caller or not? If it should your code was wrong
to catch it.
You equally can't test which branch of an if statement was taken or
which parameter was given to a helper function in order to get to
the desired result.


I'm agree with out on this point, but not for the exception part...


Why not? Exceptions are nothing special. Either you want to propagated
them to the caller, in which case they can be seen as somekind of result
and this can be tested for with a unittest or you don't want them to
be propagted and then they are just an implementation detail of your
unit.

--
Antoon Pardon
Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3381
by: William Park | last post by:
(crossposted to comp.lang.python, because this may be of interest to them.) Python has try-block, within which you can raise exception. Once it's raised, execution breaks out of the try-block and is caught at the end of try-block. Now, Bash has similiar feature. I've added try-block and 'raise' builtin into Bash-3.0. Typical usage would go something like try
8
1675
by: Lonnie Princehouse | last post by:
In a recent post, Michele Simionato asked about resumable (or re-entrant) exceptions, the basic idea being that when raised and uncaught, these exceptions would only propagate backwards through a limited number of frames before being implicitly ignored. Alex Martelli pointed out that resumable exceptions are difficult to implement, and that the need for them isn't pressing because it's pretty easy to write a program with explicit error...
3
1723
by: MackS | last post by:
Hi I'm new to Python and would like to know if the following is possible. Say I have one lower-level object A and one user-interface object B. Suppose B.CallingMethod() calls A.CalledMethod(), the latter method stumbles upon an IO error and raises an exception. The calling method detects the exception, but needs to get input from the user before deciding whether A.CalledMethod() should continue being executed or permantently...
3
3964
by: mirandacascade | last post by:
Verion of Python: 2.4 O/S: Windows XP ElementTree resides in the c:\python24\lib\site-packages\elementtree\ folder When a string that does not contain well-formed XML is passed as an argument to the XML() method in ElementTree.py, an ExpatError exception is raised. I can trap the exception with a try/except where the except does not specify a specific exception, but I cannot figure out how to construct the except clause in a...
5
2566
by: juergen perlinger | last post by:
Hello out there. sometimes I need to have proper control of the floating point arithmetic of the C(and C++) runtime system, and using the f.p. exception handling of the C99 standard is quite handy for that purpose. The only problem when dealing with f.p. exception signals is that there is (afaik) no specification *when* the f.p. exception is raised, with one notable exception: 'feraiseexcept(int)' raises the exceptions passed in the...
3
1840
by: elziko | last post by:
I have a procedure that creates a bitmap of a certain size and then displays it in a 3rd party component. However, if the bitmap is very large then a System.OutOfMemoryException is thrown my something but my codes breaks at the difition of my class: "Public Class MainForm" ....so I'm assuming that the OutOfMemoryException occurs in the 3rd party since I have put a Try-Catch block around my bitmap creation code and I am
2
24515
by: Abubakar | last post by:
Hi all, I'm writing an app in vc++ 2k5 (all native/unmanaged). This application does a lot of multithreading and socket programming. Its been months since I'm developing this application, at this point a lot of it is working just fine, my app running fine, threads r being made and destroyed, memory is being dynamically allocated at God knows how many places and ,hopefully, getting deallocated as well. Its just by coincedence I happened...
132
5555
by: Zorro | last post by:
The simplicity of stack unraveling of C++ is not without defective consequences. The following article points to C++ examples showing the defects. An engineer aware of defects can avoid hard-to-find bugs. http://distributed-software.blogspot.com/2007/01/c-exception-handling-is-defective.html Regards, zorabi@ZHMicro.com http://www.zhmicro.com http://distributed-software.blogspot.com
5
5152
by: =?Utf-8?B?c3VydHVyeg==?= | last post by:
Hi, I feel like a noob for asking this. When I publish a VB windows application, I want to disable the ability of the the user to continue when there is an unhandled exception. For example, if there is a bug in the program that causes an exception, I want the program to crash. If there is an unhandled exception the program is in an undefined state, and continuing could be dangerous. I'm surprised the
0
8611
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9170
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9031
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8876
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7741
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5867
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4624
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.