How to mock function call inside other function using pytest?

╄→гoц情女王★ 提交于 2020-12-13 03:16:43

问题


def publish_book(publisher):
    # some calculations
    factor = 4
    print('xyz')
    db_entry(factor) # db entry call which I want to mock
    print('abc')

def update():
    publish_book('xyz')

@pytest.mark.django_db
def test_update(mocker):
    # in here I'm unable to mock nested function call
    pass
    


I have db_entry() function call in publish_book(). how can we mock db_entry() function call inside publish_book.I want to perform other calculations of publish_book(), but only skip(mock) the db_entry() call.


回答1:


You can use monkeypatch to mock functions. Here is an example if it helps you.

def db_entry():
    return True


def add_num(x, y):
    return x + y


def get_status(x, y):
    if add_num(x, y) > 5 and db_entry() is True:
        return True
    else:
        return False


def test_get_stats(monkeypatch):
    assert get_status(3, 3)
    monkeypatch.setattr("pytest_fun.db_entry", lambda: False)
    assert not get_status(3, 3)

As you can see before doing the second assertion i am mocking the value of db_entry function to return false. You can use monkeypatch to mock the function to return nothing if you want by using lambda like lambda: None

I am not sure what your db_entry function does but say it is doing some db query and returning list of results you can mock that also using lambda by returning lambda: ["foobar"]



来源:https://stackoverflow.com/questions/65001334/how-to-mock-function-call-inside-other-function-using-pytest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!