Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock the return value of class method imported from another class in Python?

I have these files:

/foo.py 
/foo2.py 
/test_food.py

in foo.py, I have this:

from foo2 import Foo2

class Foo(object):

    def GetFoo2(self):
        f = Foo2()
        return f.Get()

and in foo2.py, I have:

class Foo2(object):

    def __init__(self):
        self.myvar = "eeee"

    def Get(self):
        return self.myvar

In test_foo.py,

import os, sys, json, pytest
from mock import *
from foo import Foo

def test_foo_ok(monkeypatch):

    monkeypatch.setattr(Foo, "GetFoo2", lambda x:"abc")
    f = Foo()
    result = f.GetFoo2()
    assert result == "abc"

So, in test_foo.py, I am able to mock or monkeypatch the method GetFoo2(). However, instead of doing that, how can I mock the return value of Foo2's Get() method from test_foo.py without changing the code in foo.py and foo2.py?

like image 283
murvinlai Avatar asked Oct 26 '25 19:10

murvinlai


1 Answers

Whenever you import using from, you can patch that module's namespace. Here is an example for your test_foo_ok function:

import os, sys, json, pytest
from mock import *
from foo import Foo

def test_foo_ok(monkeypatch):
    monkeypatch.setattr("foo.Foo2.Get", lambda x:"abc")
    f = Foo()
    result = f.GetFoo2()
    assert result == "abc"

See the where to patch section of the Mock library's documentation for more details. The same rules apply to pytest's monkeypatch.

like image 175
jordanm Avatar answered Oct 29 '25 08:10

jordanm