Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock function call inside other function using pytest?

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.

like image 314
Akash Pagar Avatar asked Sep 08 '25 10:09

Akash Pagar


1 Answers

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!