1

In lib/thing.py:

class Class(object):
    def class_function1(self):

In app/thing.py:

def function2(class_object):
    class_object.class_function1()

In test/test_thing.py, I want to patch lib.thing.Class.class_function1 when function2 is called with a mocked Class() object to raise an AttributeError which should just perc up to test_function2 unimpeded. Something like this (which doesn't work):

def test_function2(self):
    mocked_class = mock.MagicMock(name="class", spec_set=lib.thing.Class)
    with assertRaises(AttributeError):
        with patch ('lib.thing.Class.class_function1', side_effect=AttributeError):
            function2(mocked_class)
idjaw
  • 25,487
  • 7
  • 64
  • 83
kiminoa
  • 2,649
  • 3
  • 16
  • 17
  • Dropping the patch and just setting `mocked_class.class_function1.side_effect = AttributeError` raises the `AttributeError` correctly when `class_function1` gets hit in `function2`, but `assertRaises` doesn't acknowledge it. Hm. One step closer or one step sideways ... – kiminoa Oct 26 '15 at 21:14

1 Answers1

1

I dropped patch entirely and worked with side_effect in the mocked class object.

def test_function2(class_object):
    mocked_class = mock.MagicMock(name="class", spec_set=lib.thing.Class)
    mocked_class.class_function1.side_effect = AttributeError("sorry for the pseudo code")
    with assertRaises(AttributeError):
         function2(mocked_class)
kiminoa
  • 2,649
  • 3
  • 16
  • 17