What is the difference between using the '@patch.object' and 'with patch.object' in Python?
<p>In writing unit tests for my application, I have always been using the <code>@mock.patch</code> and <code>@patch.object</code> decorators. But now, for some unit tests when I use the decorator, I receive an error '<strong>TypeError: staticmethod object is not an iterator</strong>'.</p>

<p>But with the same code, if I use <code>mock.patch.object</code> or <code>mock.patch.object</code>, everything works just fine.</p>

<p>For example, in my test class I have this method:</p>

<pre><code>@staticmethod
def my_mock():
   ...do something
</code></pre>

<p>When I try the following unit test</p>

<pre><code>@mock.patch('mypackage.mymodule.my_method', side_effect=my_mock)
def test_something(self, my_method_mocked):
    ...test something
</code></pre>

<p>I receive the error message stated before '<strong>TypeError: staticmethod object is not an iterator</strong>'.</p>

<p>But when I try this way</p>

<pre><code>def test_something(self):
    with patch.object(mymodule, "my_method") as mocked_method:
        mocked_method.side_effect = self.my_mock
        ...test something
</code></pre>

<p>then everything works perfectly.</p>

<p>I've read the Python documentation about mock and unit tests, but I couldn't find any explanation for this behavior. </p>

<p>What is the difference between using the <strong>decorator pattern</strong> and the <strong>with</strong> pattern? Where I can find more about this?</p>

<p>Just to be more clear, this my code structure:</p>

<pre><code>class TestClass(unittest.TestCase):

    @staticmethod
    def my_mock():
    ...mock
        return service

    # doesn't work
    @mock.patch('mypackage.mymodule.my_method', side_effect=my_mock)
    def test_something(self, my_method_mocked):
        ...test something

    # work 
    def test_something(self):
    with patch.object(mymodule, "my_method") as mocked_method:
        mocked_method.side_effect = self.my_mock
        ...test something
</code></pre>

<p>That's why I can't do <code>TestClass.my_mock</code>. If I do, I get a reference error.</p>