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:

Why is this an issue?

When 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.

Patching with a lambda that only returns a value

with patch("app.api.fetch", lambda: {"ok": True}):
    assert call_api()["ok"]

The lambda never uses its arguments; it only supplies a return value.

Prefer 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.

What is the potential impact?

Lambda-only stubs obscure intent and block standard mock assertions. Tests become harder to maintain when signatures change or when call arguments need verification.

How to fix it

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.

Code examples

Noncompliant code example

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

Compliant solution

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

Noncompliant code example

def test_compute(mocker):
    mocker.patch("module.target", lambda x, y: 7)  # Noncompliant
    assert compute(1, 2) == 7

Compliant solution

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)

Resources

Documentation