tian jin
tian jin

Reputation: 13

How to replace a method during testing in Python?

I am trying to replace a method function during testing. The original method is complicated so I want to use a simple function to replace it in testing.

I have tried using mock library. But looks like it only modifies the object directly created in the test case. If some other functions inside the test case call the method, the method will not be replaced.


class1.py:

class Class1:
    def foo(self):
        #do a lot of calculation
        return 1

class2.py:

from .class1 import Class1

class Class2:
    def doo(self):
        my_class1 = Class1()
        return my_class1.foo()

test.py:

import mock
from .class1 import Class1
from .class2 import Class2

class Class1:
    def foo(self):
        # no calculation
        return 2

@mock.patch.object(Class1, "foo")
def test_case(mock):
    my_class2 = Class2()
    assert my_class2.doo() == 2

What I am trying is to replace the foo() inside Class1 to the new foo() created in test.py. But because the Class1 object is created inside the Class2 object, the method is not replaced in this way.`

Upvotes: 1

Views: 3345

Answers (1)

chepner
chepner

Reputation: 531125

You have to mock the right thing. Class2.doo creates an instance of class2.Class1, not test.Class1 (names are the important thing when mocking, and class2 and test each have their own global scope).

import mock
import class2


@mock.patch.object(class2.Class1, 'foo', return_value=2)
def test_case(mock):
    my_class2 = class2.Class2()
    assert my_class2.doo() == 2

Upvotes: 1

Related Questions