Skip to content

Latest commit

 

History

History
38 lines (28 loc) · 991 Bytes

PT008.md

File metadata and controls

38 lines (28 loc) · 991 Bytes

PT008

use return_value= instead of patching with lambda

This checks calls to unittest.mock.patch from standard library, as well as mocker, session_mocker etc. fixtures from pytest-mock library.

e.g. mocker.patch('target', return_value=7) is OK, and mocker.patch('target', lambda *args: 7) is an error

Examples

Bad code:

def test_foo(mocker):
    mocker.patch('module.target', lambda x, y: 7)

Good code:

def test_foo(mocker):
    mocker.patch('module.target', return_value=7)
    # if lambda parameters are used, it's not a violation
    mocker.patch('module.other_target', lambda x, y: x)

Rationale

  • this style of patching allows to use all mock functionality, such as checking the list of calls to the patched function:
    def test_foo(mocker):
        mock_target = mocker.patch('module.target', return_value=7)
        do_something()
        mock_target.assert_called_once()