[Django]-How to mock function call inside other function using pytest?

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

Leave a comment