Mock - the patch class method to raise an exception

Here is a generic code example that I am trying to test with mock. I get the AttributeError attribute.

Here is __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 you run the test, mock raises an AttributeError, saying: "The material has no method_b attribute"

What am I doing wrong here?

+4
source share
1 answer

The first argument of the decorator must be the class of the object; you mistakenly used the class name string

@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

+6
source

Source: https://habr.com/ru/post/1523520/


All Articles