Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing in Python - how to use assertRaises in testing using unittest? [duplicate]

I am trying to do a simple test in Python using unittest, to see if a class throws an exception if it gets an unsuitable input for the constructor. The class looks like this:

class SummaryFormula:
    def __init__( self, summaryFormula):
        self.atoms = {}
        for atom in re.finditer( "([A-Z][a-z]{0,2})(\d*)", summaryFormula):
            symbol = atom.group(1)
            count = atom.group(2)

            if pocet != "":
                self.atoms[ symbol] = int(count)
            else:
                self.atoms[ symbol] = 1

My test is following:

    class ConstructorTestCase(unittest.TestCase):
      def testEmptyString(self):
        self.assertRaises(TypeError, ukol1.SummaryFormula(), "testtest")

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

All I want is the test to fail, meaning that the exception of unsuitable input for constructor is not handled.

Instead, I get an error: __init__() takes exactly 2 arguments (1 given).

What am I missing? What is the second argument I should specify?

Also, what type of Error should I use to handle exception that an input not matchable by my regexp was passed to the constructor?

Thank you, Tomas

like image 559
Tomas Novotny Avatar asked Oct 06 '10 21:10

Tomas Novotny


2 Answers

assertRaises is a little confusing, because you need to give it the callable, not an expression that makes the call.

Change your code to:

self.assertRaises(TypeError, ukol1.SummaryFormula, "testtest")

In your code, you are invoking the constructor yourself, and it raises an exception about not having enough arguments. Instead, you need to give assertRaises the callable (ukol1.SummaryFormula), and the arguments to call it with ("testtest"). Then it can call it, catching and checking for exceptions.

like image 193
Ned Batchelder Avatar answered Oct 12 '22 23:10

Ned Batchelder


A more pythonic way is to use with command (added in Python 2.7):

with self.assertRaises(SomeException):
    do_something()

Documentation: https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises

like image 39
Pratyush Avatar answered Oct 13 '22 00:10

Pratyush