0

I am testing an exception using assertRaises, even though exception is raised, it is not detected by assertRaises

Here is the method under test:

def process_data(data):
    """
    process output data
    :return: dict object 
    """
    component = dict()
    try:
        properties = dict()
        properties['state'] = data['state']
        properties['status'] = data['status']
        component['properties'] = properties
    except KeyError as e:
        print "Missing key '{0}' in the response data".format(str(e))

    return component

sample_data = {}
process_data(sample_data)

And the test code is:

import unittest
import test_exception


class TestExceptions(unittest.TestCase):
    """
    test class
    """
    def test_process_data(self):
        """
        test
        :return: 
        """
        sample = {}
        self.assertRaises(KeyError, test_exception.process_data, sample)

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

But it is not working as expected, getting following errors:

unittest -p test_test_exception.py
Missing key ''state'' in the response data 


Missing key ''state'' in the response data


Failure
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 331, in run
    testMethod()
  File "/unittest/test_test_exception.py", line 16, in test_process_data
    self.assertRaises(KeyError, test_exception.process_data, sample)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 475, in assertRaises
    callableObj(*args, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 116, in __exit__
    "{0} not raised".format(exc_name))
AssertionError: KeyError not raised



Ran 1 test in 0.001s

FAILED (failures=1)

Process finished with exit code 1

What is wrong with unit test case?

1 Answer 1

1

Thank you for posting a clear question with the proper context and code. Here's the problem:

except KeyError as e:
    print "Missing key '{0}' in the response data".format(str(e))

This should be:

except KeyError as e:
    print "Missing key '{0}' in the response data".format(str(e))
    raise

Your Unit Test is checking that the Exception is RAISED (where the code is short circuited completely). Finding the exception type and printing the message is not the same as raising the error with the raise keyword.

Sign up to request clarification or add additional context in comments.

4 Comments

doesn't it mean that if you are in except block that means the exception is raised?
No, the except block is for when an exception is "caught" meaning noticed, but not raised. You have the option of raising or handling it. The assertRaises() is checking for that raise behavior in particular.
oh ok, so what is the best way to unit test such cases where we want to gracefully handle exception and not raise anything, may be just log and move on ??
You could assign a string variable to the error message and then use assertEqual to test the string against what you are expecting

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.