mock - patch class method to raise exception

14,143

The decorator first argument should be the class of the object, you mistakenly used a string of the name of the class

@mock.patch.object('Stuff', 'method_b', some_error_mock)

should become

@mock.patch.object(Stuff, 'method_b', some_error_mock)

http://docs.python.org/dev/library/unittest.mock#patch-object

Share:
14,143
hannson
Author by

hannson

Updated on June 04, 2022

Comments

  • hannson
    hannson almost 2 years

    Here's a generalized example of the code I'm trying to test using mock. I get an AttributeError.

    Here's __init__.py:

    import logging
    log = logging.getLogger(__name__)
    
    class SomeError(Exception):
        pass
    
    class Stuff(object):
        # stub
    
        def method_a(self):
            try:
                stuff = self.method_b()
            except SomeError, e:
                log.error(e)
                # show a user friendly error message
                return 'no ponies'
            return 'omg ponies'
    
        def method_b(self):
            # can raise SomeError
            return ''
    

    In tests.py I have something like this:

    import mock
    import unittest
    
    from package.errors import SomeError
    from mypackage import Stuff
    
    some_error_mock = mock.Mock()
    some_error_mock.side_effect = SomeError
    
    class MyTest(unittest.TestCase):
    
        @mock.patch.object('Stuff', 'method_b', some_error_mock)
        def test_some_error(self):
            # assert that method_a handles SomeError correctly
            mystuff = Stuff()
            a = mystuff.method_a()
            self.assertTrue(a == 'no ponies')
    

    When running the test, mock raises AttributeError saying: "Stuff does not have the attribute 'method_b'"

    What am I doing wrong here?

  • hannson
    hannson over 10 years
    I can't believe I overlooked such a simple explanation. Thanks!