0

What's the difference between using @patch above the testing function or with patch within the testing function (example below). For context, I'm testing a function where patching using a with statement works as expected, but the @patch doesn't.

class MyClass:
    def __init__(self, arg_a, arg_b):
        self.arg_a = arg_a
        self.arg_b = arg_b
        
    def function_to_test(self):
        pass
    
@patch(
    "my_path",
    return_value=None,
)
def test_function_to_test(
    mock_,
):
    with patch("my_path") as mock_:
        pass
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Roma V
  • 31
  • 2

1 Answers1

0

The only difference should be the scope in which the target is patched. When used as a context manager, the patch() applies to the indented block beneath. When used as a test function decorator, it applies to the whole test function and when used as a TestCase class decorator, it applies to all test functions in that class (I'm not sure whether each test method gets the same mock object or whether each gets a new one).

Can you provide a working example to show the difference you observe? The only difference I can see in your example is that you give a return_value=None argument to your decorator and no such argument to your context manager.

FiddleStix
  • 3,016
  • 20
  • 21