简体   繁体   中英

How to mock a Python method that is called more than once inside a loop using Pytest

Let's say I have a Python method:

def good_method(self) -> None:
    txt = "Some text"
    response = self.bad_method(txt)
    resources = response["resources"]
    print (resources)
    while resources:
        response = self.bad_method(txt)
        resources = response["resources"]
        print (resources)

Now let's say I want to write a unit test for it. The bad_method() returns a dictionary and it could get called over and over in the while loop. I have been trying to Mock the bad_method() so it returns a nested dictionary, so the while loop runs once. This is the code:

from unittest.mock import MagicMock

def test_good_method():
    dic = {"resources": {"resources": "values"}}
    def side_effect():
        return dic
    self.bad_method() = MagicMock(side_effect=side_effect())

    self.good_method()

I expected to first get a {"resources": "values"} printed out, and then a values . But the only thing I get is a resources . What am I doing wrong? How can I achieve what I expect?

def test_good_method():
    thing = MyClassContainingGoodAndBadMethod()
    thing.bad_method = MagicMock(return_value={"a": "b"})
    thing.good_method()

    assert thing.bad_method.call_count == 10  # or however many times it is supposed to be called

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM