4
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 Answer 1

3

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"]

Sign up to request clarification or add additional context in comments.

2 Comments

Does the above answer help? Let me know if you need more clarity or have additional question.
I am unsure if this answer has helped as it is not yet accepted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.