firestreak
firestreak

Reputation: 447

Python - Mocking the behavior of an object outside of a function

I have 3 files:

main.py

from util import ResultGetter

result_getter = ResultGetter()
result = result_getter.get_result()

def function_a():
    return result

util.py

class ResultGetter:
    def get_result(self):
        return False

and test_main.py

import main from _pytest.monkeypatch import MonkeyPatch

def test_function_a():
    def get_new_result():
        return True
    monkeypatch = MonkeyPatch()
    monkeypatch.setattr(main.result_getter, "get_result", get_new_result)
    result = main.function_a()
    assert(result == True)

I'm attempting to override the behavior of get_result with get_new result and make the assertion True. However it's still pulling in the False from util.py.

I am new to mocking in python, so any help would be appreciated.

Upvotes: 1

Views: 287

Answers (1)

Younes
Younes

Reputation: 421

The problem here is that this block below is set outside the scope of the function :

result_getter = ResultGetter()
result = result_getter.get_result()

I changed the main.py to :

from util import ResultGetter

def function_a():
    return ResultGetter().get_result()

And it worked. The problem here is you can't access the value of the object outside the function with the MonkeyPatch or even with the patch function like :

 with patch("__main__.ResultGetter.get_result") as get_new_result:
     get_new_result.return_value= True
     result = function_a()

Since it's set up beforehands your test from the object result_getter.

Upvotes: 1

Related Questions