This rule raises an issue when unittest.mock.patch (or a pytest-mock mocker.patch call) is given a lambda
whose body only returns a value and does not use its parameters.
In Python, this refers to calls such as:
unittest.mock.patch("target", lambda: value) or patch("target", lambda *args: value) when the lambda body does not use
its parametersmocker.patch(...) / session_mocker.patch(...) calls from pytest-mockWhen writing tests, patch and mocker.patch often stub a dependency so the code under test receives a fixed value.
Passing a lambda that only returns a constant is less clear than return_value=. The lambda adds an unnecessary callable,
and the mock no longer supports the usual assertions such as assert_called_once_with. return_value= also stays valid if the
patched function’s signature changes.
with patch("app.api.fetch", lambda: {"ok": True}):
assert call_api()["ok"]
The lambda never uses its arguments; it only supplies a return value.
with patch("app.api.fetch", return_value={"ok": True}):
assert call_api()["ok"]
return_value= states the intent directly and keeps the mock usable for call assertions.
This rule does not raise when the lambda uses its parameters, because that expresses custom behavior rather than a constant stub.
Lambda-only stubs obscure intent and block standard mock assertions. Tests become harder to maintain when signatures change or when call arguments need verification.
Replace the lambda with return_value= set to the same constant. Keep a lambda (or side_effect) only when the stub must
use call arguments or run custom logic.
from unittest.mock import patch
def call_api():
from app.api import fetch
return fetch()
def test_call_api_ok():
with patch("app.api.fetch", lambda: {"ok": True}): # Noncompliant
assert call_api()["ok"]
from unittest.mock import patch
def call_api():
from app.api import fetch
return fetch()
def test_call_api_ok():
with patch("app.api.fetch", return_value={"ok": True}):
assert call_api()["ok"]
def test_compute(mocker):
mocker.patch("module.target", lambda x, y: 7) # Noncompliant
assert compute(1, 2) == 7
def test_compute(mocker):
mock_target = mocker.patch("module.target", return_value=7)
assert compute(1, 2) == 7
mock_target.assert_called_once_with(1, 2)