I was wondering if it was possible to use the with statement conditionally, like
if condition:
with mock.patch(....)
#code that is or is not patched
Is it theoretically possible to achieve this without losing the with statement?
I was wondering if it was possible to use the with statement conditionally, like
if condition:
with mock.patch(....)
#code that is or is not patched
Is it theoretically possible to achieve this without losing the with statement?
You can create a wrapper context manager that calls the wrapped context manager's __enter__
and __exit__
methods based on the given condition:
class conditional_context_manager:
def __init__(self, condition, context_manager):
self.condition = condition
self.context_manager = context_manager
def __enter__(self):
return self.context_manager.__enter__() if self.condition else self
def __exit__(self, *args, **kwargs):
if self.condition:
return self.context_manager.__exit__(*args, **kwargs)
so that:
with conditional_context_manager(False, mock.patch('builtins.print')):
print('hi')
outputs:
hi
while:
with conditional_context_manager(True, mock.patch('builtins.print')):
print('hi')
outputs nothing.
Alternatively, you can use a mock.MaigicMock
object as a context manager if the condition is not met:
with mock.patch('builtins.print') if condition else mock.MagicMock():
#code that is or is not patched