0

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

kashiraja
  • 740
  • 11
  • 24
  • @Mark, @DavidCullen: Making sure what's passed in is a reference seems to fix the issue of it not flagging the exception. However, if I uncomment `#raise Exception(ReferenceError)` the test still fails!? ```Traceback (most recent call last): File "C:\...\test_db.py", line 5, in test_close self.assertRaises(ReferenceError, self.close_database) File "C:\Anaconda2\lib\unittest\case.py", line 473, in assertRaises callableObj(*args, **kwargs) File "C:\...\test_db.py", line 9, in close_database raise Exception(ReferenceError) Exception: ``` – kashiraja Jul 26 '16 at 20:07
  • Have you tried `raise ReferenceError("This is an error.")` instead of `raise Exception(ReferenceError)`? @kashiraja – Mark Jul 26 '16 at 23:12
  • __That does seems to work...awesome!__ I'm really in new territory here.. Thx for your help! – kashiraja Jul 26 '16 at 23:20
  • That's not a problem, happy to help! :) @kashiraja – Mark Jul 26 '16 at 23:22
  • @alecxe This question should probably not be marked duplicate anylonger? – kashiraja Jul 27 '16 at 17:53
  • @kashiraja I still think is is a duplicate. Thanks. – alecxe Jul 27 '16 at 18:07

2 Answers2

1

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.

Mark
  • 768
  • 3
  • 7
  • 23
1

Remove the parentheses after self.close_database:

class TestConnectDatabase(unittest.TestCase):
    def test_close(self):
        self.assertRaises(ReferenceError, self.close_database)
        pass

You are calling self.close_database which means its result (None) gets passed to assertRaises. See the documentation for assertRaises.