问题
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