mercredi 25 novembre 2015

python assertRaise not catching MagicMock exception

I'm attempting to create a unit test to check the error handling on our Python 3.4 code. I'm using MagicMock from mock to replace a sub-function and raise the exception as a side_effect and then using assertRaises from unittest to check the exception is raised.

Unfortunately although the code seems to be handling the exception the test seems to be crashing out because of the exception. I've tried rewriting the test to use a try/except loop to no effect and I've tried translating it into a nose2 @raise AttributeError to no avail.

Is the error handling in the code somehow blocking the test from catching the raised exception?

The code:

import unittest2 as unittest
from mock import MagicMock

class Service():

    def _execute(self, entity, destport):

        print("setting format to json")
        self.format = "json"

        try:
            print("call _reply_in_json")
            getattr(self, "_reply_in_%s" % self.format)(entity, destport)
            return ""
        except AttributeError:
            print("Invalid format requested")
            err = "invalid format requested"
            return err


class TestService(unittest.TestCase):

    def test_executeAttributeError(self):
        self.entity = "butter"
        self.destport = 54
        self.ret = False

        print("## Starting test_executeAttributeError for CsvDs")

        # Set up test objects
        testDS = Service()
        testDS._reply_in_json = MagicMock(name='_reply_in_json', side_effect=Exception(AttributeError))

        # Run the test
        with self.assertRaises(AttributeError):
            print("Execute new request")
            self.ret = testDS._execute(self.entity, self.destport)

        if self.ret:
            self.assertEqual(self.ret, "invalid format requested")

            # Check the call was made correctly.
            testDS._reply_in_json.assert_called_once_with(self.entity, self.destport)
        else:
            print("nothing returned")

        print("test_executeAttributeError for CsvDs completed successfully\n")

if __name__ == '__main__':
   suite = unittest.TestLoader().loadTestsFromTestCase(TestService)
   unittest.TextTestRunner(verbosity=2).run(suite)

The output:

## Starting test_executeAttributeError for CsvDs
Execute new request
setting format to json
call _reply_in_json

Error
Traceback (most recent call last):
  File "daltest/test_test.py", line 37, in test_executeAttributeError
     self.ret = testDS._execute(self.entity, self.destport)
  File "daltest/test_test.py", line 13, in _execute
    getattr(self, "_reply_in_%s" % self.format)(entity, destport)
  File "/usr/lib/python3.4/site-packages/mock/mock.py", line 1062, in __call__
    return _mock_self._mock_call(*args, **kwargs)
  File "/usr/lib/python3.4/site-packages/mock/mock.py", line 1118, in _mock_call
    raise effect
Exception: <class 'AttributeError'>


Process finished with exit code 0

Aucun commentaire:

Enregistrer un commentaire