samedi 5 septembre 2015

Why does mock ignore the instance/object passed to a mocked out method when it is called?

I have recently noticed that if I mock out a method using mock.patch it doesn't list the instance object passed to the mocked method in the call_args field. Is this by design? Code/output below may better explain what I mean:

#!/usr/bin/env python2

from mock import patch

class Dog(object):
    def bark(self):
        print("Woof woof!")

Dog().bark()

def new_method(*args):
    print("args = %s" % str(args))

Dog.bark = new_method

Dog().bark()

with patch.object(Dog, "bark"):
    d = Dog()
    d.bark()
    print("d.bark was called: %s" % str(d.bark.called))
    print("d.bark was called with args/kwargs: %s" % str(d.bark.call_args))

Output is:

Woof woof!
args = (<__main__.Dog object at 0x7f42c2dbc3d0>,)

# Mocking bit
d.bark was called: True
d.bark was called with args/kwargs: ((), {})

You can see that the instance object is passed to new_method when it replaces bark. But you cannot see it in the call_args of the mocked out method. Isn't this strange? I am using version 1.01 of the python mock library.

Aucun commentaire:

Enregistrer un commentaire