How to test that an exception is raised ?

StepH stephane.bronsart at bea.be
Fri Jan 28 11:02:38 CET 2005


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<Name>' + name + '</Name>\n')
    f.write('\t\t<Adr>' + adr + '</Adr>\n')
    f.write('\t</Var>\n')

def mps2xml(mps,verbose):
    """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(".*Var.*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(usage)

    parser.add_option("-v", "--verbose", action="store_true",
dest="verbose")
    parser.add_option("-q", "--quiet", action="store_false", dest="verbose")

    (options, args) = parser.parse_args()

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

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

    mps2xml(args[0],options.verbose)

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(self):
        """Check that an exception is raised if a bad filename is passed to
mps2xml"""
        self.assertRaises((IOError),mps2xml.mps2xml, "thisfiledoesntexists",
False)

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

        line = " irM1slotnoisePPtmp      Var.    g 0x0002F6"
        file = open("testWriteVar.xml","w+")
        mps2xml.writeVar(file, line)
        file.close()

        outputlines = list(open("testWriteVar.xml"))
        goodlines = list(open("testWriteVar.xml.good"))
        self.assertEquals(outputlines, goodlines, 'bad output format')

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

        mps2xml.mps2xml(self.mps, False)
        self.assert_(os.path.exists(self.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.





More information about the Python-list mailing list