kashiraja kashiraja - 4 months ago 27
Python Question

assertRaises does not catch exception / does not complain about no exception

This code does not work as expected. I'm getting pass when expecting fail; and fail when expecting pass for assertRaises().

test_db.py:


import unittest

class TestConnectDatabase(unittest.TestCase):
def test_close(self):
self.assertRaises(ReferenceError, self.close_database()) # <--- Problem #1
pass

# Just a stub for brevity...
def close_database(self):
#raise Exception(ReferenceError) # <--- Problem #2
pass

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


In this example the code passes the unit test even though the exception was not raised. If
#raise
is uncommented, the exception is just passed to command line and the test fails when it should pass.

Executing test using:
python -m test_db
or
python test_db.py

Answer

You're calling the method self.close_database, when you should just be passing a reference to it. Remove the parentheses e.g.

def test_close(self):
    self.assertRaises(ReferenceError, self.close_database)

Check out the docs for more details.

Comments