Just to go one step further, and building on the "noautofixt" technique of The Compiler, you can also potentially disable individual patches within a fixture using the technique below. Here I have a "configure_me" function at the start of a project which has a long list of tasks (subfunctions, checks on return values, etc.) it has to do. But how do I deliver by default a "successful configuration" using patching, but at the same time allow the possibility of using individual real (non-patched) functions when I want to?
@pytest.fixture()
def configuration_good(request):
with mock.patch('start.main' if 'noautofixt_py_version_ok' in request.keywords else 'start.py_version_ok', return_value=True):
with mock.patch('start.cwd_is_prd', return_value=True):
with mock.patch('pathlib.Path.is_dir', return_value=True):
mock_module = mock.Mock()
mock_module.logger = mock.Mock()
mock_module.thread_check = mock.Mock()
with mock.patch('start.try_to_get_library_main_module', return_value=mock_module):
with mock.patch('start.try_to_get_lib_version', return_value=packaging_version.Version('5.0')):
with mock.patch('start.try_to_get_min_lib_project_version', return_value=packaging_version.Version('4.0')):
with mock.patch('start.other_instance_running', return_value=False):
with mock.patch('start.try_to_configure_logger'):
with mock.patch('start.try_to_get_app_version', return_value=packaging_version.Version('1.0')):
yield
If the mark noautofixt_py_version_ok
is detected, the if
expression patches main
instead of py_version_ok
. I know that patching main
for all the tests which will use this fixture will always be harmless. But a mock.patch
must always patch something real: you can't say this, for example:
with mock.patch(None if 'noautofixt_py_version_ok' in request.keywords else 'start.py_version_ok', return_value=True):
request.keywords["noautofixit"]
only returns boolTrue
when the mark is present. If your mark has args it's better torequest.node.iter_markers("noautofixit")
and then you get access to theMark
object withname
,args
andkwargs
available. – Cantillate